Skip to content

executor: add a partitioned table's key through sub-partitioned partitions - #694

Open
Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/partitioned-key-subpartitions
Open

Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/partitioned-key-subpartitions

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

The online ADD PRIMARY KEY / ADD UNIQUE build for a partitioned table now runs on trees whose partitions are themselves partitioned, instead of refusing them.

Why

pg-sprite adds a key to a partitioned table online: it builds each partition's unique index concurrently, gives it a constraint, and then adds the parent's constraint, which adopts the partitions' constraints instead of building anything under a blocking lock. Until now that only worked when every partition sat directly under the parent. A table partitioned by year and then by month, a common layout, was refused outright, so its owner had to fall back to PostgreSQL's blocking ADD CONSTRAINT.

What

  • The build now gives the key from the bottom of the tree up: every leaf as before, then each sub-partitioned partition, deepest first, then the parent. A sub-partitioned partition's step is the parent's step applied to it: lock it, prove each partition directly under it has the constraint its step recorded, run its ADD CONSTRAINT under the derived name <name>_p<partition OID>, and read back that it adopted each one without building an index.
  • The parent's step now proves and reads back only the partitions directly under it, since a sub-partitioned partition's constraint already adopted the ones below.
  • A rerun resumes from a sub-partitioned partition that already has the key: it is reported found, and the partitions under it need no step. One with a conflicting key constraint, or a relation under its derived name, is refused before any leaf is touched.
  • The report gains the action adopted for a sub-partitioned partition, and the verdict detail counts them.
  • The partitioned-key-sub-partitioned refusal and its code are removed, from the build, its dry-run admission, and the desired-plan admission. The capability row, docs/limitations.md, the design doc, and the SchemaBot integration tables are updated to match.

Before / after

The only change is what happens to a tree with a sub-partitioned partition; a tree with only direct leaves runs exactly as before. Take ALTER TABLE app.events ADD CONSTRAINT events_pkey PRIMARY KEY (id, created_at) on this tree:

app.events                         (partitioned by year)
├── events_2025                    (leaf)
└── events_2026                    (partitioned by month)
    ├── events_2026_01             (leaf)
    └── events_2026_02             (leaf)
Before
  read the tree ──▶ events_2026 is itself partitioned
                ──▶ refused: partitioned-key-sub-partitioned, nothing built
  the only way left is PostgreSQL's own ADD CONSTRAINT, which builds every
  partition's index while holding ACCESS EXCLUSIVE on the whole tree

After
  1. leaves, each online:  events_2025, events_2026_01, events_2026_02
       CREATE UNIQUE INDEX CONCURRENTLY, then ADD CONSTRAINT ... USING INDEX
  2. events_2026, one brief transaction:
       ADD CONSTRAINT events_pkey_p<oid> adopts the two month constraints
       (builds nothing; reported as "adopted")
  3. events, one brief transaction:
       ADD CONSTRAINT events_pkey adopts events_2025's and events_2026's
  result: 4 partitions, 3 built, 1 sub-partitioned given the key by adoption

…tions

Sub-partitioned partitions now get the key bottom up, each ADD CONSTRAINT
adopting the level below, instead of the build refusing the whole tree.
The partitioned-key-sub-partitioned code is retired with the refusal.
@Kiran01bm
Kiran01bm marked this pull request as ready for review December 2, 2026 03:15
@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-02T03:15:24.663830Z
We couldn’t complete this review. Comment @codex review to try again.
1677f5f 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 2, 2026

Copy link
Copy Markdown
Collaborator

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

Inspected the whole change at 1677f5ff6261f4374de7c55f8b0989bc288097cf (26 files): the new bottom-up step in partitioned_key_subpartition.go, the reworked pass in partitioned_key_flow.go#L168-L187, the parent step now shared with sub-partitions (partitioned_key_parent.go#L107-L163), the retired partitioned-key-sub-partitioned refusal, the five new scenarios (three executor, two CLI), and the docs. I read the surrounding catalog code the new step reuses (decideLeafKey, matchingLeafConstraint, listPartitionTree, relationFacts.definitionKey) rather than only the hunks.

CI: only three checks exist at this head (DCO, Semgrep, zizmor), all green. The PostgreSQL matrix has not run, and the reason is finding 1.

The design reads correct. The build gives each leaf its key as before, then each sub-partitioned partition deepest first (its ADD CONSTRAINT adopts the constraints directly under it, in one brief transaction under lock_timeout), then the parent's. I checked the points that decide whether that is sound:

  • Order. listPartitionTree orders by depth, oid, so parents come before children, findSubPartitionKeys's done[n.parentOID] skip sees a keyed partition before its descendants, and slices.Backward (#L177) is deepest first.
  • Proof scope. Each step proves and reads back only the partitions directly under it (childrenOf, #L115), which is right: a grandchild's constraint is adopted by its own parent's constraint, not by the one above.
  • Partitions that appear mid-run. A partition attached under a sub-partitioned partition between the listing and its step has no recorded constraint, so the step adds nothing (partitioned_key_parent.go#L117-L123, partitioned_key_subpartition.go#L153-L155) and the next pass, which re-lists the tree and finds the already-keyed partitions, covers it.
  • Resume. A keyed sub-partitioned partition (an earlier run's, or an operator's under another name) is reported found and its descendants are skipped; a conflicting constraint or an occupied derived name refuses before any leaf is touched (decideSubPartitionKey, #L105-L125).
  • Locks. lockSubPartition takes ACCESS EXCLUSIVE on the partition and everything under it, inside the same briefTx.run bounded by lock_timeout as the parent's step, and proves the partition is still the listed one before the statement. It takes the sub-partitioned partition first and its descendants after, the order a write routed through the parent takes them, and takes no lock on the parent, so I found no inversion with a concurrent writer.

Invariants (docs/invariants.md): LK-1 (one run per table, #L725) is upheld; the build still runs under the table's advisory lock. LK-2 (#L840) is extended to a new bounded strong-lock step, and ST-7 (#L1741) is extended to the sub-partitioned partition's name proof; the entries' text does not say so yet (2/2, finding 1).

Blocking

  1. The PR conflicts with main, so none of its tests have run on any PostgreSQL version. gh pr view reports mergeable: CONFLICTING, mergeStateStatus: DIRTY. A pull_request workflow does not dispatch for a conflicting PR, which is why the head has three checks and no workflow runs at all (the Actions API lists none for this SHA). Every new scenario here (TestAddPartitionedKeyThroughSubPartitionedPartitions, TestAddPartitionedKeyResumesFromAKeyedSubPartition, TestAddPartitionedKeyRefusesAConflictingSubPartitionKeyFirst, the two CLI tests) needs a live PostgreSQL, so the claims in the description (adoption builds nothing, 3 levels, resume) are unverified at this head, and I could not run them either. main has moved four commits since the merge base a97ca7f, and the changed files overlap this PR's: pkg/executor/code.go, code_test.go, internal/cli/dryrun.go, pkg/capabilities/capabilities.yaml, and docs/{capabilities,execution-model,invariants,limitations,refusal-classes,schemabot-integration}.md. Merge main in (do not rebase after review), then let the matrix run; the removed code and error must come out of whatever code.go and code_test.go now list. This is mechanical, not a defect in the design, but it keeps the change from being measured.

Non-blocking

  1. Comments that still say a sub-partitioned partition refuses a key, in exported docs. The PR's own description says the refusal is removed "from the build, its dry-run admission, and the desired-plan admission", but three places still describe it: the exported migrate.RunDesired doc (desired.go#L224-L226, "for a partition key column the key leaves out or a sub-partitioned partition, is refused before anything runs"), and AdmitPartitionedKeyCatalog (dry_run_admission.go#L238-L239) and its helper partitionedKeyCatalogRefusal (#L255-L256, "the sub-partitioned tree is the build's own catalog refusal"). A host reading RunDesired's doc is told a plan the build now runs will be refused. Because AdmitPartitionedKey now returns only the partition key refusal, the partitionedKeyRefusal(err) fallback in that helper has nothing left to match from the admission and can go with the comment (reasoned from the admission's remaining error sources, not run).

  2. The new step's own failure and deferral branches have no test, unlike the parent step they copy. The parent step is pinned by TestAddPartitionedKeyParentStepFailsClosed, ...RefusesChangesSinceTheLeafSteps and ...Locks; the sub-partitioned step reuses adoptPartitionKeys but its own surface is only exercised on the happy path. Not pinned by any test I can find in the diff: the !out.added deferral in addSubPartitionKey (#L153-L155), where a partition attached under a sub-partitioned partition after the listing must send the build round again and still end with every level adopted; the ST-7 branch of lockSubPartition (#L174-L177) for a partition renamed or dropped after the listing; the step giving up at lock_timeout behind a reader or writer on a descendant leaf (the doc claims every strong lock is bounded); a UNIQUE key instead of a PRIMARY KEY through sub-partitions (all three executor scenarios and both CLI tests use the primary key, which also exercises requireNotNullForPrimaryKey); and a DEFAULT partition at a nested level. Each needs the same fixture the existing parent-step tests use; I did not write a test sketch because I did not read those helpers closely enough to name them honestly.

  3. A sub-partitioned partition's existing unique partitioned index (no constraint) is not reused, so its whole subtree gets a second index. For a leaf, decideLeafKey reuses a valid matching index "attached to nothing" (partitioned_key_catalog.go#L162-L164, #L287-L294). A leaf under a sub-partitioned partition that already has a plain CREATE UNIQUE INDEX of the key's columns has its leaf index attached to that partitioned index, so it is not "attached to nothing", and decideSubPartitionKey only looks at constraints. The result is a new concurrent index on every leaf under it (named <name>_p<leaf OID>), a second partitioned index on the sub-partitioned partition, and the old one left in place. This is safe and PostgreSQL gives no way to turn a partitioned index into a constraint (the docs already say so for the parent), but the PR text does not say what happens at a sub-partition level, and the duplicate storage is real on a large tree. A sentence in the design doc's step 5, or a refusal that tells the operator to drop the old index first, would settle it. Reasoned from the decision code, not run.

Verified

  • Read the full diff and the head versions of the files above; no local build or test run (no clone, per the disk floor). The five new scenarios need PostgreSQL, so nothing could be checked against a server, and the PR's matrix has not run (blocking 1).
  • Walked a two-level and a three-level tree through pass by hand, including a second pass after a deferral: the sub-partitioned partitions already keyed in the first pass are found keyed in the second, their descendants are skipped, and the parent's step proves only its direct partitions. The report keeps each partition's first result (record), so a deferred pass does not duplicate a Leaves entry.
  • Mutation table, by reading (the scenarios need a live PostgreSQL, so none was run):
Mutant Caught by
slices.Backward replaced by forward order in pass (flow.go#L177) TestAddPartitionedKeyThroughSubPartitionedPartitions: a higher sub-partitioned partition's step runs before the one below it is recorded, defers every pass, and the build ends partitioned-key-unsettled
done[n.parentOID] skip removed (subpartition.go#L35) TestAddPartitionedKeyResumesFromAKeyedSubPartition: the leaves under the keyed partition are stepped again and meet "already attached to a parent's constraint"
childrenOf(tree, ...) replaced by tree in adoptPartitionKeys (parent.go#L115) the three-level scenario: the parent would require its grandchildren adopted by its own constraint and fail the read-back
decideSubPartitionKey skipping matchingLeafConstraint TestAddPartitionedKeyRefusesAConflictingSubPartitionKeyFirst
lockSubPartition deleted survives: no test (non-blocking 2)
!out.added returning true in addSubPartitionKey survives: no test (non-blocking 2)

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

@aparajon

aparajon commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

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

The one blocking finding of this review is in 1/2 (the merge conflict that kept the PostgreSQL matrix from running); the marker below carries the PR-wide count.

Read the change from two seats: an operator or contributor who reads docs/invariants.md and the design doc to learn what the key build guards and where, and a host that imports pkg/executor and pkg/migrate (the SchemaBot adapter or any other importer) and switches on the build's codes, report and verdict text. The behavior is a plain win for adopters: a table partitioned by year and then by month, a common layout, used to be refused outright and now gets the same online key, and the PR description's before and after diagram, drawn from one concrete tree, makes that checkable in a minute.

Non-blocking

  1. The invariant registry still describes a leaf-only build, and one sentence now says the opposite of the code. LK-2's text on the key build (invariants.md#L956-L971) says AddPartitionedKey runs "the parent's plain ADD CONSTRAINT, which takes ACCESS EXCLUSIVE on the parent and every leaf, in one brief transaction" and that the read-back covers "every leaf". With this change there is also one such transaction per sub-partitioned partition, each locking its whole subtree, so the number of strong-lock windows a run takes now grows with the sub-partitioned partitions, and an operator sizing lock_timeout from LK-2 will not find that. ST-7's text (#L1783-L1793) likewise says the parent proves "that every leaf has exactly one constraint of the requested key" and omits the sub-partitioned partition's name and tree proof (lockSubPartition). Worse, #L2004 still lists "a sub-partitioned partition" among the key refusals that stop a desired plan before its first statement, which the PR removes everywhere else. The PR touched six docs but not this file. Disposition: LK-2 extended (a new bounded strong-lock step), ST-7 extended (a new name proof), both upheld in substance; the entries should say so and name the three new tests where they name the parent-step tests, since the registry is what a later reviewer trusts.

  2. The change removes an exported error, an exported code and a Codes() entry, and says nothing about it for importers. ErrPartitionedKeySubPartitioned and CodePartitionedKeySubPartitioned are gone from pkg/executor (and from Codes(), Code.Permanent and the sentinel map in code.go), which is the right call since the condition no longer exists. But the integration guide describes the codes as stable (schemabot-integration.md#L84: "the stable code"), a host that names either symbol stops compiling on the bump, and a host that persisted the string partitioned-key-sub-partitioned in a stored verdict or plan history will no longer find a constant for it. Nothing in the diff points a host at the change (the capability row and the tables drop the code, but a reader of those never learns it existed). If the repository keeps release notes, one line there ("a partitioned key on a tree with sub-partitioned partitions now runs; the code partitioned-key-sub-partitioned and its error are gone") would let an importer find out from the notes rather than the compiler.

  3. The verdict detail of every partitioned key build changed, in wording that reads oddly, and the report's leaves now mixes two kinds of entry. The description says a tree with only direct leaves "runs exactly as before", but partitionedKeyDetail now always appends a clause, so a plain two-partition build ends "... 0 found already constrained, 0 sub-partitioned given the key by adopting their partitions'", with a dangling apostrophe and a zero most runs will never need. Dropping the clause when the count is zero keeps the common message as it was and the new one for the tree that has sub-partitions. Separately, PartitionedKeyReport.Leaves (JSON leaves, partitioned_key.go#L86-L89) now also lists the sub-partitioned partitions, with action adopted, after the leaves; the guide mentions it in a parenthesis (schemabot-integration.md#L884). A host that renders "leaves" as a list of leaf tables, or counts them against Partitions, will see sub-partitioned partitions in it and a count that no longer equals the tree size minus one level. Renaming the field is a breaking change, so the doc comment on the field should say it lists every partition the run gave the key, sub-partitioned ones included, and which order they come in (leaves in tree order, then sub-partitioned partitions deepest first, as the new scenario asserts).

What reads well for adopters

  • The step is the parent's step applied one level down: the same adoptPartitionKeys body runs for the parent and for each sub-partitioned partition, so the proof, the read-back and the "builds nothing" check (LK-2, index OIDs unchanged) are one code path rather than two that can drift.
  • The derived name <name>_p<partition OID> is the one a leaf already gets, so an operator inspecting the tree sees one naming pattern at every level.
  • Resuming from a keyed sub-partitioned partition works whatever name its key has, and a conflicting constraint or an occupied derived name refuses before any leaf is built, so the failure an operator can fix shows up before the expensive part.
  • The ST-7-style comments on lockSubPartition and the doc comments on the new functions say what each step proves and why, in the repository's usual style, and the three executor scenarios draw the tree they run on (including the three-level case) in the test comment.

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: 1 blocking, 6 non-blocking (see the review comments above). The blocking finding is the merge conflict with main, which kept the PostgreSQL matrix from running; the design itself reads correct.

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

@JashLal

JashLal commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

🤖 Two blockers on 1677f5f.

  1. GitHub reports this head as conflicting with the base. The three reported checks pass, but there is no PostgreSQL matrix result. Resolve the conflict and run the nested-primary-key, resume, and desired-state cases in the matrix. Existing CI discussion
  2. Revalidate ancestry back to the requested root before mutating a nested node. The pass uses a tree snapshot, and lockSubPartition locks the node and its descendants, then checks the node's immediate parent. Given root → year → month → leaf, a detach of year from root after the snapshot can leave month under the same year. The month step can then commit its key on the detached tree before the year or root step detects the change. Guard the full ancestry against detach through each mutating step, and add a regression that detaches an ancestor between the snapshot and a deeper step. This is a static race finding. Pass and lock proof

The full diff shows leaf builds followed by bottom-up adoption, with each adoption checking the recorded constraint and index OIDs on its direct children.

Review based on the full GitHub diff, PR discussion and reported checks. Builderbot and inline review threads were unavailable. I did not run tests locally.

@JashLal JashLal 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.

🤖 Approved by Jash’s AI agent after reviewing 1677f5f. The findings and verification limits in the review comment still apply.

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