Skip to content

migrate: let the dry run decide an attach's DEFAULT write window - #652

Merged
Kiran01bm merged 2 commits into
kiran01bm/partitioned-attach-default-windowfrom
kiran01bm/partitioned-attach-default-dryrun
Nov 30, 2026
Merged

Kiran01bm merged 2 commits into
kiran01bm/partitioned-attach-default-windowfrom
kiran01bm/partitioned-attach-default-dryrun

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

migrate --dry-run now ends an online ATTACH PARTITION beside a DEFAULT partition in the same refusal the run ends in, and takes --accept-default-write-window to plan the accepted attach.

Why

A partitioned table can have a DEFAULT partition that catches rows no other partition takes. Attaching a new partition online next to it briefly refuses writes that land in the new range, so pg-sprite only does it when the operator accepts that window with --accept-default-write-window. The dry run did not look at the table for this: it reported such an attach as ready to run, so a CI check on the dry run passed a change the real run then refused, and the flag could not be passed to the dry run at all.

What

  • executor.AdmitAttachPartition makes the online attach's own checks, in the attach's order, up to the point where the attach would change anything: the tables resolve, the bound is provable, the table to attach is a child of nothing, and a DEFAULT partition needs the accepted window. A table already attached is admitted, as the rerun only drops leftover proofs. The attach flow and the admission share resolveTarget, readMembership and refusePrepare, so they cannot drift.
  • migrate.AdmitOnlineAttachCatalog turns those refusals into the run's verdicts, the DEFAULT window into the run's by-design refusal; migrate.AdmitAcceptDefaultWriteWindow rejects a flag naming another table, as the run does.
  • The dry run calls both, and --accept-default-write-window is no longer rejected with --dry-run.
  • Docs (cli.md, limitations.md, plan-report.md, schemabot-integration.md) no longer say the dry run skips this check.

Before / after

The same statement on a parent orders that has a DEFAULT partition, without the flag: the dry run used to pass it, and the run refused it. Now both refuse it. With the flag, the dry run plans the attach the accepted run executes. Nothing changes for an attach on a parent without a DEFAULT partition.

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

Before
  migrate --dry-run                                  migrate (the run)
  ┌──────────────────────────────────────────┐      ┌──────────────────────────────────────────┐
  │ reads no catalog for the attach          │      │ finds app.orders_default under the lock  │
  │ plans it: execute, online-attach         │      │ refuses: unsupported-statement, by-design│
  │ exit 0 — the CI gate passes              │      │ exit 2                                   │
  └──────────────────────────────────────────┘      └──────────────────────────────────────────┘
  migrate --dry-run --accept-default-write-window app.orders
    → rejected: "cannot be combined with --dry-run"

After
  migrate --dry-run                                  migrate (the run)
  ┌──────────────────────────────────────────┐      ┌──────────────────────────────────────────┐
  │ finds app.orders_default in the catalog  │      │ finds app.orders_default under the lock  │
  │ refuses: unsupported-statement, by-design│      │ refuses: unsupported-statement, by-design│
  │ exit 2 — the same verdict as the run     │      │ exit 2                                   │
  └──────────────────────────────────────────┘      └──────────────────────────────────────────┘
  migrate --dry-run --accept-default-write-window app.orders
    → plans it: execute, online-attach, nothing changed on either table

The dry run planned an online attach beside a DEFAULT partition as
executing, so a CI gate on it passed an attach the run refuses. It now
makes the attach's own catalog checks and takes --accept-default-write-window.
…bm/partitioned-attach-default-dryrun

The base now carries main's online attach route; the dry run's doc keeps
main's list of checks and adds the attach's catalog checks.
@Kiran01bm
Kiran01bm marked this pull request as ready for review November 30, 2026 07:31
@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-11-30T07:31:38.718123Z
We couldn’t complete this review. Comment @codex review to try again.
33a3e9e 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

Copy link
Copy Markdown
Collaborator

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

Inspected the whole change at 33a3e9e6bd1ef8102aca495544c39ccd77548e85, taken against the PR's base branch (1aa637af): the dry run's new acknowledgement check and catalog admission (dryrun.go#L129-L135, dryrun.go#L301-L310), migrate.AdmitOnlineAttachCatalog and migrate.AdmitAcceptDefaultWriteWindow (dry_run_admission.go#L108-L148, online_attach_default_window.go#L47-L63), the executor refactor that carves resolveTarget, readMembership and refusePrepare out of the attach flow and the new AdmitAttachPartition (attach_partition_flow.go#L312-L385, attach_partition_admit.go#L1-L46), the removed Validate rule, the doors-test list, the integration test, and the five doc edits.

The change does what it says. The apply refuses a parent with a DEFAULT partition inside prepare, after it has resolved the tables, derived the bound proofs and read the table's membership; the refactor moves exactly those reads and the two refusals into helpers that prepare and the new AdmitAttachPartition both call, in the same order, so the dry run and the apply read one set of checks rather than two copies. The new admission is read-only: it runs through briefTx, so it keeps the LK-2 lock and statement budgets, it rolls back, and it takes no advisory lock and writes nothing, which the integration test pins by counting CHECKs on both tables after the dry runs. A table already attached to the parent is admitted without the flag, as in the apply (it only drops leftover proofs and opens no window). The window refusal is routed apart from onlineAttachRefusal and gets the same defaultWindowRefusalVerdict the run builds, so the refusal verdict, class and exit code match the run's for the case the test pins. hasDefault() is deflt.tableOID != 0, the same test the old r.deflt.oid == 0 branch made. No failure here is fail-open: a refusal the dry run now reports is one the apply would also report, and the dry run never claims more than the apply admits.

Invariants (docs/invariants.md): upholds RF-10, whose acknowledgement set and "dry run ends in the same refusal" clause now also cover --accept-default-write-window (the mismatch check is mirrored, and ErrAcceptDefaultWriteWindowMismatch is the error it returns); upholds LK-2 (the admission reads run under briefTx's bounded budgets, and AdmitAttachPartition is listed in the stopped-run doors test as a function that runs nothing); upholds ST-6 (the read happens before any write). No *Enforced:* line names a moved file.

Non-blocking

  1. A stop on an unprovable bound now returns a report with no Schema or Table. run used to set f.rep.Schema, f.rep.Table right after resolve and before deriveAttachBoundCheck; the refactor sets them only after resolveTarget returns, and resolveTarget returns the derivation error first (attach_partition_flow.go#L312-L318, #L334-L350). The base had them set at attach_partition_flow.go#L318. AttachPartitionReport is exported and its doc says Schema and Table identify the attached table; an importer that calls AttachPartitionOnline and logs rep.Table beside an attach-partition-bound-unprovable stop used to get the name and now gets an empty string. resolveTarget already returns table beside that error (return table, attachPartitionTarget{}, err), which run discards, so the value is there to use. No test reads the report on this path (the only rep.Table assertion, attach_partition_flow_integration_test.go#L138, is on a success). Setting the two fields when table is non-zero, before the early return, restores the report.
Test case (not run here: needs a live server): the report names the table when the bound is unprovable
func TestAttachPartitionOnlineNamesTheTableWhenTheBoundIsUnprovable(t *testing.T) {
	withAttachProofServer(t, func(t *testing.T, newFixture func(t *testing.T) attachProofFixture) {
		f := newFixture(t)
		f.exec(t, `
			CREATE TABLE %[1]s.readings (sensor integer NOT NULL) PARTITION BY RANGE (sensor);
			CREATE TABLE %[1]s.readings_low (sensor integer NOT NULL)`)
		rep, err := f.attachOnlineTo(t, "readings", f.pool,
			`ALTER TABLE %[1]s.readings ATTACH PARTITION %[1]s.readings_low FOR VALUES FROM (0) TO ('one hundred')`,
			attachFlowOptions, RunStep{})
		require.ErrorIs(t, err, errAttachBoundUnprovable)
		assert.Equal(t, "readings_low", rep.Table)
	})
}

Written against the fixture helpers in the neighbouring tests; expected to fail on 33a3e9e (rep.Table is empty) and pass once the fields are set before the early return.

  1. The dry run checks the acknowledgement for statements the apply never checks it for. Run returns from renameIndex and addEnumValue before it reads any acknowledgement (migrate.go#L354-L365, the check is at #L392), and the dry run's own copy-and-swap acknowledgement check is guarded for exactly this reason (tableFound && !runsOwnExecutor(st), dryrun.go#L100, with a comment saying so). The new check at dryrun.go#L132-L136 has no guard. --alter 'ALTER INDEX i RENAME TO j' --accept-default-write-window other.table therefore runs (the flag is ignored) but its --dry-run ends in ErrAcceptDefaultWriteWindowMismatch, the one direction in which the dry run is stricter than the run it previews. The check also sits after AdmitStoppedRun and AdmitDestructive, where the apply reads it before findStoppedRun, so a mismatched flag beside a stopped copy-and-swap run gets the stopped-run refusal from the dry run and the mismatch error from the apply; the destructive acknowledgement above it has the same placement, so that part follows the file's precedent. Adding && !runsOwnExecutor(st) to the condition (and, ideally, moving the call next to CheckCopySwapAcknowledgements) keeps the two aligned. The integration test does not reach either case.

  2. The dry run's other new refusals have no test; only the DEFAULT window path does. AdmitOnlineAttachCatalog classifies with onlineAttachRefusal, so a missing table, a table that is not a plain table, a table that is already a child of another table, and an unprovable bound now end the dry run in an unsupported-statement refusal with exit code 2, where the base planned them as executing with exit 0. That is a larger behavior change than the title says, and TestMigrateDryRunDecidesTheDefaultWriteWindowLikeApply (migrate_online_attach_integration_test.go#L79-L150) exercises only the window, the mismatch and the already-attached rerun. A mutant that classifies with admissionRefusal instead of onlineAttachRefusal would leave every PR test green (mutant M5 below, by reading the test: no input in it reaches those branches), and the table error would then come out as an operational error with exit 1 instead of a refusal. The apply's own integration tests cover resolve and the bound derivation, not the dry run's routing of their errors.

Test case (not run here: needs a live server): a dry run of an attach of a missing table ends in the run's refusal
func TestMigrateDryRunRefusesAnAttachOfAMissingTableLikeApply(t *testing.T) {
	url := testutil.StartPostgres(t)
	pool, err := dbconn.NewPool(t.Context(), dbconn.Config{URL: url})
	require.NoError(t, err)
	t.Cleanup(pool.Close)
	schema := testutil.NewSchema(t, pool)
	_, err = pool.Exec(t.Context(), fmt.Sprintf(
		`CREATE TABLE %[1]s.orders (id bigint NOT NULL, day date NOT NULL) PARTITION BY RANGE (day)`, schema))
	require.NoError(t, err)
	alter := fmt.Sprintf(`ALTER TABLE %[1]s.orders ATTACH PARTITION %[1]s.orders_2027 FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`, schema)

	applied, err := runMigrate(t, newMigrateCmd(url, alter))
	require.ErrorIs(t, err, verdict.ErrRefused)

	dry := newMigrateCmd(url, alter)
	dry.DryRun = true
	planned, err := runMigrate(t, dry)
	require.ErrorIs(t, err, verdict.ErrRefused)
	assert.Equal(t, applied, planned)
}

Modelled on the PR's own test and its helpers (runMigrate, newMigrateCmd); not run, so whether the two verdicts compare equal field for field is unconfirmed. The refusal and exit code are the point.

Verified

  • Ran only anchored unit tests with a timeout, after grepping their bodies and helpers for database use (no sql.Open, StartPostgres, dbtest, 13306 or build tag in either; neither package has a TestMain): TestAcceptDefaultWriteWindowFlagGrammarAndWiring (internal/cli) and TestEveryDoorChecksForAStoppedRunBeforeItExecutes (pkg/migrate). Both pass at 33a3e9e. go vet -tags integration ./internal/cli ./pkg/executor ./pkg/migrate is clean at the head. I did not run TestMigrateDryRunDecidesTheDefaultWriteWindowLikeApply or any executor attach test (they need a live PostgreSQL), so the integration test's claims are read, not measured.
  • Compared the head against its base branch for every refactored line of run, attachTarget and prepare: the order is resolve, derive the bound proofs, read membership, then refuse a child table, then refuse an unaccepted window, then prepare, as before; the only difference on the apply path is the report fields in finding 1.
  • Mutation table (each change applied alone, the two unit tests above run or the package vetted, then git checkout):
Mutant (production change) Caught by
M1 Validate rejects --dry-run with the flag again TestAcceptDefaultWriteWindowFlagGrammarAndWiring/takes_a_dry_run
M2 the dry run's acknowledgement check removed survived the unit tests; the integration test asserts the mismatch error (not run here)
M3 acceptWindow hard-wired to true in the catalog closure survived the unit tests; the integration test's refusal-without-flag assertion (not run here)
M4 AdmitAttachPartition returns after reading membership, so it never refuses a child table or a window survived the unit tests (vet clean); the integration test's refusal assertion (not run here)
M5 AdmitOnlineAttachCatalog classifies with admissionRefusal survived every PR test, by reading: no test input reaches a table or bound refusal in the dry run; killed by the second test case above (not run here)

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 33a3e9e: 0 blocking, 3 non-blocking.

Read the change from two seats: an importer that embeds the engine and builds its own dry run from the exported migrate.Admit* functions (SchemaBot is the obvious one), and an operator who meets the change only through --dry-run output, the exit code and the guides. The change fits the package's shape: the catalog half sits beside AdmitPartitionedKeyCatalog and AdmitPartitionedForeignKeyCatalog with the same (verdict, refused, error) signature, the executor function it calls is listed in the doors test as one that runs nothing, and the CLI keeps one wiring point (partitionedCatalogAdmission) for all the builds.

Non-blocking

  1. For an operator or CI gate, a dry run of the same command line now changes document and exit code, and the guides cover only one of the new cases. An ATTACH PARTITION beside a DEFAULT partition used to print a plan and exit 0; without the flag it now prints the refusal verdict and exits 2, and --json returns a verdict document where a pipeline expected a plan report (docs/cli.md#L319-L321 says so for the window). The same switch now applies to a missing table, a table that is not a plain table or is already a child of another table, and an unprovable bound (review 1/2, finding 3), and none of those is written down for the dry run: docs/schemabot-integration.md#L913-L915 says the dry run "makes the same catalog checks" in general terms, the attach-partition-table and attach-partition-bound-unprovable rows of the outcomes table (#L937, #L941) still describe only the run, and docs/refusal-classes.md#L121 names the window refusal without its dry-run source, where the neighbouring key and foreign key rows name AdmitPartitionedKeyCatalog and AdmitPartitionedForeignKeyCatalog as the dry run's source. A release note that says a dry run of an attach can now end in exit 2 for a table or bound the run refuses, and a clause in those rows, would let a pipeline owner see why a previously green gate turned red. The plan report's schema version does not change, which is right, but a consumer that pins on it will not learn of the change from the version either.

  2. AdmitOnlineAttachCatalog takes the acceptance as a bool, so an importer can accept the window without the typed acknowledgement the flag exists to require. The CLI validates the string with AdmitAcceptDefaultWriteWindow first, then reduces it to acceptWindow := c.AcceptDefaultWriteWindow != "" (dryrun.go#L129-L135, #L303-L307); an importer that calls the catalog half alone with true plans an attach as accepted for a table nobody named, and the order of the two calls lives only in dryrun.go. The guide names AdmitOnlineAttachCatalog (docs/schemabot-integration.md#L913) but not AdmitAcceptDefaultWriteWindow, and does not say to call that one first. This is a dry run, so nothing unsafe follows, and Run still checks the string; the concern is that the exported pair reads as independent when the second assumes the first. Naming the pair and the order in the guide (or taking the acknowledgement string and checking it inside the catalog half, as Run does) would make the supported route the obvious one.

  3. An accepted dry run does not say that it planned under an accepted window. The text output echoes the copy-and-swap flags a plan assumed (writeCopySwapRunFlags), but for an attach planned with --accept-default-write-window it prints the ordinary plan, and neither the JSON report nor the fingerprint records the acceptance. A reader of a saved plan, or an importer that stores the report and runs it later, cannot tell whether the plan was made for an accepted window, which is the one fact that decides whether the run refuses. The flag is the operator's own and apply: says to re-run the same command line, so this is a clarity gap rather than a defect. A single plan line naming the window (for example that writes the DEFAULT partition receives inside the new bound fail with SQLSTATE 23514 until the attach commits) would let the text stand on its own, and the docs/cli.md sentence that lists the flags a dry run takes (#L365-L367) does not list this one.

What reads well for adopters

  • The dry run and the apply now share their checks through resolveTarget, readMembership and refusePrepare rather than two copies, so a later change to what the attach refuses reaches the preview without a second edit. That is the property a SchemaBot-style importer wants from a preview.
  • The integration test pins the refusal verdict, class, reason, table and exit code against the run's own, and checks that neither dry run leaves a proof on either table, which is the claim an operator relies on.
  • The docs edits are in the right places (the flag's help text, docs/cli.md, docs/limitations.md, docs/plan-report.md, the integration guide) and the stale sentences that said the dry run reads no catalog for the attach are gone; a search of the docs finds no remaining claim that the flag cannot be combined with --dry-run.

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 comment(s) above).

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

@Kiran01bm
Kiran01bm merged commit f6526c3 into kiran01bm/partitioned-attach-default-window Nov 30, 2026
18 checks passed
@Kiran01bm
Kiran01bm deleted the kiran01bm/partitioned-attach-default-dryrun branch November 30, 2026 09:51
@Kiran01bm

Copy link
Copy Markdown
Collaborator Author

🤖 Adversarial review response — created by Kiran's code review agent (Amp, Claude Opus 5.5) — pull/652, follow-up PR

#652 merged into #644's branch at the reviewed head, so 5 of 6 non-blocking findings are fixed in a follow-up PR from kiran01bm/attach-default-dryrun-review-fixes, stacked on #644; 1 is deferred.

# Finding Status Explanation
C1-F2 The dry run checks the window acknowledgement for an index rename or enum value add, which the run never checks, and after the stopped-run gate rather than before it fixed The check moved next to CheckCopySwapAcknowledgements, before AdmitStoppedRun, and is guarded by !runsOwnExecutor(st). TestMigrateDryRunIgnoresTheDefaultWindowFlagForAnIndexRenameLikeApply pins that the dry run plans what the run executes, and fails without the guard.
C1-F1 A stop on an unprovable bound returns a report with no Schema or Table fixed run sets both from the table resolveTarget returns before it checks the error. TestAttachPartitionOnlineNamesTheTableWhenTheBoundIsUnprovable (a hash bound on a text key) fails when the assignment is moved back after the return.
C1-F3 The dry run's table and bound refusals have no test; classifying with admissionRefusal survives fixed The suggested TestMigrateDryRunRefusesAnAttachOfAMissingTableLikeApply is added. It asserts exit 2, unsupported-statement, and a verdict equal to the run's, and fails under the admissionRefusal mutant (M5).
C2-F1 A dry run of an attach now ends in exit 2 for a table or bound refusal, and the guides cover only the window fixed The integration guide's paragraph and its attach-partition-table and attach-partition-bound-unprovable rows say the dry run reports them (AdmitOnlineAttachCatalog). refusal-classes.md names the dry run's source, and cli.md says the dry run ends in the run's refusal for them.
C2-F2 AdmitOnlineAttachCatalog takes the acceptance as a bool, and the order of the two calls lives only in dryrun.go fixed The function's doc comment and the guide say acceptWindow is taken as given, set only after AdmitAcceptDefaultWriteWindow passes. The signature is kept, as the review allows.
C2-F3 An accepted dry run does not say it planned under an accepted window deferred Tracked as an internal follow-up: a plan line naming the window and a typed report field. It changes the plan report's contract, so it gets its own PR.

No action: the "Verified" section and the mutation table in C1, and "What reads well for adopters" in C2.

Source: block/pg-sprite#652, review comments 7272019135 and 7272021239 and review 6108407522 at head 33a3e9e6. Fixes are in the follow-up PR.

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