Skip to content

migrate: run a CREATE TABLE ... PARTITION OF as the online create of a partition - #684

Merged
Kiran01bm merged 5 commits into
mainfrom
kiran01bm/partition-of-route
Dec 3, 2026
Merged

Kiran01bm merged 5 commits into
mainfrom
kiran01bm/partition-of-route

Conversation

@Kiran01bm

@Kiran01bm Kiran01bm commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

migrate --alter now runs a bare, schema-qualified CREATE TABLE schema.name PARTITION OF schema.parent FOR VALUES … as the online create of a partition, instead of refusing it.

Why

Adding a partition (next month's, next year's) is the most routine change on a partitioned table, and the plain statement locks the whole partitioned table exclusively, so it waits behind every running query and stalls every query that arrives after it. Until now pg-sprite had no way to run it at all: migrate --alter refused every CREATE TABLE and pointed at the desired-file front door, which refuses PARTITION OF too. This PR gives the statement a route that never locks the parent against reads or writes.

What

  • The gate lets a bare CREATE TABLE schema.name PARTITION OF … FOR VALUES … through. A DEFAULT bound, an unqualified partition name, or any clause beside the bound (column list, constraints, IF NOT EXISTS, UNLOGGED, WITH, TABLESPACE, USING, PARTITION BY) is now refused as a capability-boundary that names the cause, with no pointer at the declarative door, which refuses it too. An unqualified name is refused because PostgreSQL creates it in the first schema of the session's search_path, which need not be the schema pg-sprite would use. Every other CREATE TABLE keeps its refusal.
  • migrate.Run sends it to executor.CreatePartitionOnline (previous PR): create the table with LIKE the parent, then the online attach with the statement's own bound.
    • Preflight: the parent is preflighted and the role needs the index-build tier on it, plus CREATE on the new table's schema.
    • A copy-and-swap run stopped on a table of the new partition's name refuses the create.
    • The verdict's table is the partitioned parent, as the online attach's is; statement is the submitted CREATE.
    • Refusals and failed verdicts are the online attach's: an unqualified parent, a parent with a DEFAULT partition, and an unprovable bound are refused before anything is created; any later stop leaves what was made and a rerun resumes.
  • Every acknowledgement (--force, --accept-blocking, --restart, --block-writes, --allow-destructive) is a usage error (ErrCreatePartitionAcknowledgement): there is no blocking form to force or accept.
  • --dry-run refuses the statement as a capability-boundary without planning it. Planning it, with its own execution in the plan report, is the next PR.
  • The create-table-partition-of capability row moves to ✅ ga for migrate (the desired-file door still refuses it), with a representative statement in the front-door claims test; limitations.md gets a row for the shapes still refused, and schemabot-integration.md says what a host sees: the verdict's table, the connection it needs, the acknowledgement error, and the dry run's refusal. No README bullet covers this.

Before / after

The same statement, submitted while a report query is reading the parent:

CREATE TABLE app.events_2027 PARTITION OF app.events
  FOR VALUES FROM ('2027-01-01') TO ('2028-01-01');

Before
  migrate --alter
    gate: kind CREATE TABLE  ->  refused, "use the declarative front door"
  migrate --desired (a file with the same CREATE)
    plan: PARTITION OF       ->  refused, ErrDesiredPartitionOf
  operator runs it by hand   ->  waits for ACCESS EXCLUSIVE on app.events
                                 behind the report; every new query queues

After
  migrate --alter
    gate: bare PARTITION OF  ->  admitted
    CREATE TABLE app.events_2027 (LIKE app.events ...)   reads app.events, no wait
    online attach: indexes built concurrently, FKs validated, writes go on
    ATTACH PARTITION (no scan)                           -> outcome: executed,
                                                            table: app.events
  migrate --alter --dry-run  ->  refused (capability-boundary) until the
                                 dry run plans it in the next PR

The same statement with an unqualified name (CREATE TABLE events_2027 PARTITION OF app.events …) is refused at the gate before a connection is used: qualify it with the schema it belongs in.

First step of creating a partition online: the run creates the table
standalone and attaches it with the online attach, which needs the
CREATE's own bound as an ATTACH statement.
CREATE TABLE ... PARTITION OF takes ACCESS EXCLUSIVE on the parent; creating
the table with LIKE and running the online attach reaches the same partition
while the tree keeps serving reads and writes.
…a partition

The imperative door refused every CREATE TABLE and pointed at the
declarative door, which refuses PARTITION OF too, so adding a partition had
no route through pg-sprite.
@Kiran01bm
Kiran01bm marked this pull request as ready for review December 1, 2026 20:11
@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-01T20:11:39.158211Z
We couldn’t complete this review. Comment @codex review to try again.
53609c5 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 1, 2026

Copy link
Copy Markdown
Collaborator

🤖 Review of 53609c5: 0 blocking, 6 non-blocking. (1/2: correctness, 4 of the 6. 2/2 covers adoption and integration ease, the other 2.)

I read the PR at 53609c5 against the base it builds on (the statement.CreatedPartition reader and executor.CreatePartitionOnline). The change fails closed: the gate admits only the bare CREATE TABLE name PARTITION OF schema.parent FOR VALUES ... shape, every other PARTITION OF form is a typed capability-boundary refusal before a connection, and the run itself is delegated to the executor, which re-proves the target under the parent's advisory lock. I found nothing that blocks the merge.

Invariants

Invariant Disposition Where
ST-7 (the executor runs exactly the statement that was gated) upholds pkg/migrate/online_create_partition.go:144 hands the executor the gated st.SQL() and the preflight proof pt of the new table; the executor re-proves the target before it creates anything
LK-1 (one schema change per table) upholds the create and the attach run under the parent's advisory lock inside executor.CreatePartitionOnlineAsStep; refuseOverStoppedRun (online_create_partition.go:131) refuses over a copy-and-swap run stopped on the new name
LK-2 (one ACCESS EXCLUSIVE window, every strong lock bounded) upholds the budgets are passed through (online_create_partition.go:144-149); the only strong lock is the attach's brief catalog transaction
RF-5, RF-7, RF-8 (refusal class and typed proof) upholds gateCreatePartition (online_create_partition.go:29-44) and CreatePartitionDryRunVerdict (:50-56) build refusals through WithRefusal(verdict.CapabilityBoundary(...)), so each carries one class
RF-10, AB-4 (acknowledgements) upholds, with a gap (F2) rejectCreatePartitionAcks (:184-200) refuses four acknowledgements; --accept-blocking is not among them
CO-7 (every statement parses or is an error) upholds a CREATE the reader cannot take falls through to the gate's existing refusal (online_create_partition.go:38-42), and a parse error from CreatedPartition after the gate is returned (:83-86)

Findings (all non-blocking)

F1. A refused PARTITION OF is pointed at diff --desired, which refuses it too

cliSaferIdiom (internal/cli/migrate.go:129-134) sets SaferIdiom = "pg-sprite diff --desired schema.sql" on every KindCreateTable gate refusal. Before this PR every CREATE TABLE refusal was the generic "use the declarative front door" one, so that was right. Now the gate also returns the shape refusal of gateCreatePartition for CREATE TABLE ... PARTITION OF ... DEFAULT and friends, and the CLI still attaches the same pointer to it (called at internal/cli/migrate.go:49-51). The declarative door refuses a PARTITION OF desired file too (docs/limitations.md:397, ErrDesiredPartitionOf), so an operator who follows the hint hits a second refusal. The Detail of the shape refusal already gives the right advice (create with LIKE, then ATTACH PARTITION). The dry run path (internal/cli/dryrun.go:50-52) emits the same refusal without the hint, so the two commands disagree today.

Suggested fix: attach the idiom only to the generic refusal, for example by skipping it when v.Class is capability-boundary, or have Gate leave SaferIdiom to the CLI only for the refusal it builds at pkg/migrate/verdicts.go:58-62.

Test case (run here against the PR head; fails as shown): the CLI does not point a refused PARTITION OF at diff
package cli

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/block/pg-sprite/pkg/verdict"
)

// A PARTITION OF the online create does not take is refused as a capability
// boundary, and the CLI must not point it at the declarative front door,
// which refuses a PARTITION OF too.
func TestRefusedCreateOfAPartitionDoesNotPointAtDiff(t *testing.T) {
	cmd := newMigrateCmd("postgres://pgsprite@127.0.0.1:1/none", `CREATE TABLE app.events_default
		PARTITION OF app.events
		DEFAULT`)

	v, err := runMigrate(t, cmd)
	require.Error(t, err, "a refusal exits with the refusal code")
	assert.Equal(t, verdict.OutcomeRefused, v.Outcome)
	assert.Equal(t, verdict.ClassCapabilityBoundary, v.Class)
	assert.Empty(t, v.SaferIdiom, "the declarative door refuses PARTITION OF")
}

Observed on the head: Should be empty, but was pg-sprite diff --desired schema.sql, with the detail "the online create of a partition takes only a bare CREATE TABLE name PARTITION OF parent with a FOR VALUES bound: the statement has a DEFAULT bound; ...".

F2. --accept-blocking is silently ignored, against the docs and the other acknowledgements

docs/limitations.md:24 says "every acknowledgement, --force included, is a usage error", and the doc comment of ErrCreatePartitionAcknowledgement (online_create_partition.go:18-22) says the same for acknowledgements in general. rejectCreatePartitionAcks (online_create_partition.go:184-200) checks Force, CopySwap.Restart, CopySwap.BlockWrites and AllowDestructive, but not AcceptBlocking. A caller that passes Options.AcceptBlocking (or --accept-blocking) gets a normal online create and no signal that the acknowledgement meant nothing. That is harmless for the table, since nothing blocking runs, but it is the only acknowledgement that behaves differently, and an operator who typed it expecting the blocking form to run is misled about what ran. Suggested fix: add case opts.AcceptBlocking != "": with a message that the online create has no blocking form to accept.

The unit coverage hides this. rejectCreatePartitionAcks is exercised only for --force (the third subtest of TestRunCreatesAPartitionOnline, which needs Docker). I removed the AllowDestructive case as a mutant and nothing in the PR's tests failed (see Verified).

Test case (run here against the PR head; the accept-blocking subtest fails as shown): every acknowledgement is refused
package migrate

import (
	"testing"

	"github.com/stretchr/testify/require"
)

// Every typed acknowledgement is refused for the online create of a partition:
// none of them names a blocking form, a copy-and-swap run, or a discard it has.
func TestCreatePartitionRefusesEveryAcknowledgement(t *testing.T) {
	cases := map[string]func(*Options){
		"force":             func(o *Options) { o.Force = "app.events_2028" },
		"accept-blocking":   func(o *Options) { o.AcceptBlocking = "app.events" },
		"allow-destructive": func(o *Options) { o.AllowDestructive = "app.events" },
		"restart":           func(o *Options) { o.CopySwap.Restart = "app.events_2028" },
		"block-writes":      func(o *Options) { o.CopySwap.BlockWrites = "app.events_2028" },
	}
	for name, set := range cases {
		t.Run(name, func(t *testing.T) {
			var opts Options
			set(&opts)
			require.ErrorIs(t, rejectCreatePartitionAcks(opts), ErrCreatePartitionAcknowledgement)
		})
	}
}

Observed on the head: only accept-blocking fails, with "Expected error ... in chain but got nil". It needs no database, so it belongs in pkg/migrate/online_create_partition_test.go next to the TestGate cases.

F3. Doc comments that describe the gate as before

Gate's doc comment (pkg/migrate/verdicts.go:21-32) lists the statements that proceed to classification and says everything else is unsupported, and gateRefusal's says the admitted kinds exclude CREATE TABLE (pkg/migrate/refusal_registry.go:150-153). Both are now incomplete: a bare CREATE TABLE ... PARTITION OF proceeds (verdicts.go:45-49) to run as the online create of a partition. One sentence in each keeps the next reader from concluding the new branch is dead code. docs/postgres-online-ddl-reference.md:264 still ends the CREATE TABLE ... PARTITION OF row with "create the table on its own and attach it instead"; that remains true of the raw SQL, but the row could say that migrate --alter now does it.

F4. Test gaps that matter for a refusal-heavy change

  • Online routing (TestRunCreatesAPartitionOnline) is covered only by integration tests, which I did not run here (Docker is out of bounds for this review). CI on the head is green on all PostgreSQL 14 to 18 jobs, so I treat the happy path as covered by those runs.
  • rejectCreatePartitionAcks has no unit test for any case except through --force (F2).
  • The refusal ordering in runOnlineCreatePartition (shape admission, table check, privilege tier, create privilege, stopped run, connection check) has no unit-level test that a refusal at each step leaves nothing created; the integration test covers the unqualified parent only.

Verified

I ran the PR's unit tests for the changed paths and 4 hand-made mutants, each reverted with Edit (the tracked tree is clean at the head).

Mutant Caught by
gateCreatePartition stops admitting a bare partition (return ..., false, ok && false) TestGate ("a bare create of a partition passes")
gateCreatePartition returns the shape refusal with refused=false (a DEFAULT-bound create passes the gate) TestGate ("a create of a DEFAULT partition is a capability boundary")
internal/cli/dryrun.go no longer diverts a CREATE TABLE to CreatePartitionDryRunVerdict (... && false) TestDryRunRefusesTheOnlineCreateOfAPartition
rejectCreatePartitionAcks drops the AllowDestructive case not caught by any test in the PR; caught only by the probe test in F2

CI at the head: all 18 checks are green (lint, build, unit tests, PostgreSQL 14 to 18 matrix, Supabase compatibility, smoke test, DCO). I did not rerun anything.

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

@aparajon

aparajon commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

🤖 Review of 53609c5: 0 blocking, 6 non-blocking. (2/2: OSS adoption and integration ease for SchemaBot and other importers. 1/2 covers correctness: 4 of the 6.)

An importer of pkg/migrate sees this PR as one new way for migrate.Run to end: a CREATE TABLE ... PARTITION OF that used to be a flat refusal now runs. The code is easy to wire, since it reuses the online attach's Options, refusal mapper and failure verdict. The gaps are in what an embedder is told.

A1. The dry run refuses a statement the run would execute, in the same class as a real refusal

CreatePartitionDryRunVerdict (pkg/migrate/online_create_partition.go:50-56, wired at internal/cli/dryrun.go:53-57) ends --dry-run with unsupported-statement / capability-boundary for a statement that migrate --alter without --dry-run accepts and runs. docs/limitations.md:24 states this, which is the right place for it, but the verdict itself is indistinguishable from the permanent refusal of ... DEFAULT, which is a statement that can never run online. A script that uses --dry-run as a gate before the real run (exit 2 means do not run), or a SchemaBot-style plan preview that maps capability-boundary to "blocked", will report a statement that would succeed as impossible, and the two cases differ only in the Detail text. The attach already has a dry-run plan (online-attach, docs/schemabot-integration.md:957-960), so the asymmetry is visible to anyone comparing the two.

This is a deliberate, documented limit, so I am not asking for the plan to be built here. Two cheap options: say in docs/schemabot-integration.md that a consumer must not map this verdict to "cannot run" (name CreatePartitionDryRunVerdict so it can be matched), or give it its own reason code later so the two are separable. A follow-up issue for the dry-run plan would also do.

A2. The integration guide covers the online attach but not the online create

An embedder reads docs/schemabot-integration.md to learn how each route ends. It has "Outcomes of an online ATTACH PARTITION" (line 944) and a wiring paragraph that names the routes needing Options.Connection (lines 1016-1026, which lists the online attach), and ErrConnectionRequired is documented against "the builds above" (line 1034). The online create of a partition is in neither place, yet it:

  • needs Options.Connection and returns ErrConnectionRequired with no verdict when it is unset (online_create_partition.go:139, which calls checkPartitionedIndexConnection in partitioned_index.go:99-102);
  • returns ErrCreatePartitionAcknowledgement as an error with no verdict for any acknowledgement (:80-82), so an adapter that only maps verdicts will surface a plain error to its user;
  • ends with a verdict whose Table is the partitioned parent and whose Statement is the CREATE (:93-94, :163-167), while the partition it made is named only in the Detail, so an adapter that locks or reports by Table sees the parent;
  • shares the online attach's refusals and failure codes (onlineAttachRefusal, onlineAttachFailureVerdict), so a retry of the same statement resumes, as for the attach.

A short subsection next to the attach outcomes, or one sentence in each of those two places, would let SchemaBot map the new route without reading the source. Nothing here blocks the merge.

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 1, 2026

Copy link
Copy Markdown
Collaborator

🤖 Reviewed the complete diff at 53609c5d832cf5e80645295ff7c2fc2da16ef162. I found one merge blocker.

[P1] Preserve the creation schema for an unqualified partition name. In pkg/migrate/online_create_partition.go:114–129, an unqualified child falls back to created.Attach.ParentSchema for the CREATE privilege and stopped-run checks. The route documents that same parent-schema default for online creation. PostgreSQL resolves an unqualified CREATE target in the session's current creation schema, independently of the parent's schema. For example, with search_path = tenant, public, CREATE TABLE events_2028 PARTITION OF app.events FOR VALUES ... creates tenant.events_2028 in PostgreSQL. The online route uses app.events_2028, so it can create or attach the wrong table and report success. The qualified-child integration case cannot catch this. Please require a qualified child at the gate until the connection can resolve the normal creation namespace and use that same qualified child for preflight, the stopped-run check, standalone creation, and attachment. A test with different parent and creation schemas should assert the child's namespace and that the same name in the parent schema is untouched. PostgreSQL search-path rules

The separate dry-run capability refusal, default-bound shape refusal, and reuse of the online attach verdict are consistent with the intended staged rollout. The exact-head GitHub checks were green when I reviewed. This was a static review without local test execution or independent enumeration of inline review threads.

Base automatically changed from kiran01bm/partition-of-create-attach to main December 2, 2026 23:26
PostgreSQL creates an unqualified CREATE TABLE in the session's first
search_path schema, which need not be the parent's schema the route used.
--accept-blocking is now refused like every other acknowledgement, and a
refused PARTITION OF no longer points at diff --desired.
@Kiran01bm

Copy link
Copy Markdown
Collaborator Author

🤖 Adversarial review response — created by Kiran's code review agent (Amp, claude-opus-5-5) — pull/684, follow-up commit

The blocker is fixed: an unqualified partition name is now refused at the gate. Five of the seven findings are fixed in full, and the other two are fixed in part. The dry-run plan and the refusal-order tests are a follow-up.

# Finding Status Explanation
C3-F1 P1: an unqualified partition name falls back to the parent's schema, where PostgreSQL uses the session's creation schema fixed gateCreatePartition refuses a bare PARTITION OF whose partition name is unqualified, as unsupported-statement/capability-boundary, before any connection. The detail says to qualify the name. runOnlineCreatePartition uses the qualified name for the create privilege, the stopped-run check, and the run, with no fallback. A new TestGate case pins the refusal. The capability row, limitations.md, and the guide list the unqualified name with the other refused shapes.
C1-F2 --accept-blocking is silently ignored fixed rejectCreatePartitionAcks refuses it: the online create has no blocking form to accept. The suggested table test is added as TestCreatePartitionRefusesEveryAcknowledgement, covering all five acknowledgements and the empty case. It also catches the AllowDestructive mutant from the review.
C1-F1 A refused PARTITION OF is pointed at diff --desired, which refuses it too fixed cliSaferIdiom attaches the pointer only to a CREATE TABLE refusal that is not a capability-boundary, which is the generic one. The suggested test is added and passes, and it fails without the fix.
C1-F3 Gate and gateRefusal doc comments, and the online-DDL reference row, describe the gate as before fixed Gate names the admitted PARTITION OF. gateRefusal says a CREATE TABLE that reaches it is any other one. The reference row says migrate --alter runs the bare, qualified form without locking the parent, on a parent with no DEFAULT partition.
C2-A2 The integration guide does not cover the online create fixed schemabot-integration.md has a list after the executor paragraph: the verdict's Table is the parent, Options.Connection and ErrConnectionRequired, ErrCreatePartitionAcknowledgement with no verdict, and refusals and resume shared with the attach. The connection wiring paragraph names the route.
C2-A1 The dry run refuses a statement the run executes, in the class of a real refusal fixed (guide) / deferred (plan) The guide now says a host must not map CreatePartitionDryRunVerdict to "cannot run", and how to tell it apart. Planning the statement in the dry run, with an execution that shows both executed statements, is tracked as an internal follow-up for the next PR.
C1-F4 Test gaps: acknowledgements, refusal order fixed (acknowledgements) / deferred (order) The acknowledgement gap is closed by the table test above. A test per refusal in runOnlineCreatePartition's order, each asserting nothing is created, is tracked as an internal follow-up.

No action: both reviews' invariant tables and "Verified" sections, whose mutants are caught as reported.

Source: block/pg-sprite#684, review comments 7324745413, 7324748166 and 7325273698, and reviews 6139537008 and 6139885526 at head 53609c5d; fixes in the follow-up commit

@Kiran01bm
Kiran01bm merged commit c4947ac into main Dec 3, 2026
18 checks passed
@Kiran01bm
Kiran01bm deleted the kiran01bm/partition-of-route branch December 3, 2026 04:30
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