Skip to content

migrate: let --accept-default-write-window run an attach beside a DEFAULT partition - #644

Open
Kiran01bm wants to merge 8 commits into
mainfrom
kiran01bm/partitioned-attach-default-window
Open

Kiran01bm wants to merge 8 commits into
mainfrom
kiran01bm/partitioned-attach-default-window

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

Adds --accept-default-write-window SCHEMA.TABLE (Options.AcceptDefaultWriteWindow), so migrate --alter can run an ATTACH PARTITION ... FOR VALUES online on a table that has a DEFAULT partition once the operator accepts its brief write window.

Why

Many partitioned tables keep a DEFAULT partition to catch rows no other partition takes. To attach a new partition without scanning that DEFAULT partition under a lock that blocks it, pg-sprite first adds a CHECK to it saying none of its rows fall inside the new bound. From that moment until the attach commits, any write that would land in the DEFAULT partition inside the new bound fails. That is a real, if short, cost to the application, so pg-sprite refused every attach beside a DEFAULT partition. This PR lets the operator accept the window explicitly, by naming the table, the way the other acknowledgements work.

What

  • Options.AcceptDefaultWriteWindow and --accept-default-write-window SCHEMA.TABLE. When the value names the resolved partitioned table, the online attach runs with AttachPartitionOptions.AcceptDefaultWriteWindow set, and a warn-level audit record names the table before it starts.
  • It is a typed acknowledgement like the others:
    • a value naming any other table is ErrAcceptDefaultWriteWindowMismatch, an AcknowledgementMismatchError, before anything runs;
    • RunDesired rejects it with ErrAcceptDefaultWriteWindowNotSupported, and WithoutAcknowledgements clears it;
    • Acknowledgements() lists accept-default-write-window;
    • the irreversible-operations registry has an entry for it (availability loss).
  • The CLI refuses it with --force (which runs the blocking ATTACH and opens no window), with --dry-run (which does not read the DEFAULT partition yet), and with --desired (a desired file cannot express an attach). Options.validate refuses it beside Force too.
  • Without the acknowledgement, the refusal stays, but its class moves from capability-boundary to by-design: the engine can run the attach, and only the operator's consent is missing. Its detail now names the flag and the 23514 writes the window refuses.
  • Docs: cli.md, limitations.md, refusal-classes.md, schemabot-integration.md, invariants.md, and the attach-partition capability row.

The dry run still plans an attach beside a DEFAULT partition as executing without reading the catalog. Making it report the refusal, and take this flag, is a follow-up.

Before / after

The change is what happens when a DEFAULT partition sits beside the new bound. An attach on a table with no DEFAULT partition is unchanged, and --force still runs the blocking ATTACH.

Example: app.orders has orders_2026 and orders_default, and the operator attaches orders_2027 for 2027.

pg-sprite migrate --alter "ALTER TABLE app.orders ATTACH PARTITION orders_2027 FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')"

Before
  online attach finds orders_default
    └─ refused, capability-boundary, exit 2, nothing added
       no way to accept the window; only the blocking --force ATTACH, which
       scans orders_default under ACCESS EXCLUSIVE

After, without the flag
  online attach finds orders_default
    └─ refused, by-design, exit 2, nothing added
       detail: "... rerun with --accept-default-write-window app.orders"

After, with --accept-default-write-window app.orders
  orders_2027 gets its bound proof, the parent's CHECKs, indexes and FKs   (writes continue)
  orders_default gets "no row in 2027" CHECK, then it is validated
      ┐ window: a 2027 row routed to orders_default fails with 23514
  ATTACH (brief, scans neither table), both proof CHECKs dropped
      ┘ window ends
  → executed, exit 0

A lone ATTACH PARTITION ... FOR VALUES from migrate --alter now runs as
executor.AttachPartitionOnline instead of ending rewrite-required, and its
dry run plans it with the new online-attach execution (plan format 39).
A parent with a DEFAULT partition is refused for now; --force keeps
running the blocking ATTACH as written.
Main took plan format_version 42 for catalog_only_steps, so the
online-attach contract moves to 43, with the doc examples and pins.
Adds unit tests for the attach's routing, fingerprint and refusal
classes, and documents what its dry run and DEFAULT-window refusal do.
…AULT partition

The online attach refused any parent with a DEFAULT partition, since its
exclusion proof refuses writes there inside the new bound until the attach
commits. A typed acknowledgement naming the parent now accepts that window;
without it the refusal stays, now by design and naming the flag.
Base automatically changed from kiran01bm/partitioned-attach-route to main November 30, 2026 04:48
@Kiran01bm
Kiran01bm marked this pull request as ready for review November 30, 2026 05:48
@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-30T05:48:40.915315Z
We couldn’t complete this review. Comment @codex review to try again.
d17048a 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.

Main carries #605 as a squash, so the online attach files take main's copy
with this branch's DEFAULT-partition change on top.
@aparajon

Copy link
Copy Markdown
Collaborator

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

Inspected the whole change at 1aa637af017d7e0b5492c429e0cbff6ec25cdbfc (the head after the merge of main): the gate at the call site (online_attach.go#L55-L73), the new file online_attach_default_window.go (acknowledgement check, audit record, refusal verdict), the Force exclusion in validate() (migrate.go#L231-L232) and the runStatement check (migrate.go#L391-L392), the CLI flag and its three exclusions (cli.go#L155, cli.go#L210-L213), the registry and mismatch wiring, and the executor code the flag steers, which this PR does not change (attach_partition_flow.go#L457-L459 for the refusal, #L498 for the DEFAULT proof added last, #L332 for its withdrawal on a stop).

The question for a change that widens an acknowledgement is whether the new path opens only for the person who typed it, and whether what it accepts is exactly what the text says. Both hold up on a read:

  • The flag is read once. acceptWindow := opts.AcceptDefaultWriteWindow != "" at online_attach.go#L55 is the only place the option becomes the executor's boolean, and the executor refuses before it adds anything when the parent has a DEFAULT partition and the boolean is false. Without the flag the plan still refuses, with a verdict that names the flag.
  • The acknowledgement is exact. checkAcceptDefaultWriteWindowAck compares against qualified(st) with ==. I ran a probe: app.orders_2027 (the partition being attached), orders, APP.ORDERS, "app.orders " (padded), "app"."orders" (quoted) and other.orders are each refused with ErrAcceptDefaultWriteWindowMismatch and an *AcknowledgementMismatchError carrying the resolved table and the given text. Only app.orders passes.
  • It does not leak. The flag changes one thing, the boolean above. The other upfront refusals (CodeAttachPartitionTable, CodeAttachPartitionBoundUnprovable) are mapped separately in onlineAttachRefusal and are unaffected; Force plus the window is rejected by validate() and by the CLI; --dry-run and --desired reject the flag, and RunDesired rejects it too.
  • The executor is unchanged. The new route adds no lock or timing: the DEFAULT proof is still the last step, ADD ... NOT VALID then VALIDATE under the Validate budget, then the attach, and a stop withdraws the proof through a context that survives cancellation. LK-2 and ST-7 are upheld by that, with nothing for this PR to restate.

Invariants (docs/invariants.md): this extends RF-10. It adds a typed acknowledgement and follows the entry's checklist (Options field, registry entry, mismatch and not-supported sentinels, CLI flag with the table placeholder, RunDesired rejection), and the *Enforced:* list at invariants.md#L2189-L2193 names it. The PR body should say this in those words. It upholds LK-2 and ST-7 as above and weakens nothing.

Non-blocking

  1. The window is described as "brief" in one place and as long as the validation in another, and neither the flag's help nor cli.md says it scales with the DEFAULT partition. The proof's VALIDATE scans the whole DEFAULT partition under the Validate budget (the CLI's --validate-timeout, 30 minutes by default), and writes routed there inside the new bound fail from the ADD ... NOT VALID until the attach commits, so the window is as long as that scan, not a moment. limitations.md#L139 says the flag "accepts its brief write window", while limitations.md#L23 says it "lasts as long as that proof's validation and the attach". The help text at cli.go#L155 and cli.md#L313-L319 give no length at all, and none of them says that a run killed without a chance to clean up (a SIGKILL or a lost host; a plain stop withdraws the proof) leaves the proof, and so the window, until the same statement is run again. A typed acknowledgement is only as informed as the text that prompts it; "brief" is the word an operator weighs against a 30 minute scan. Saying "as long as the validation of the DEFAULT partition, up to the validate budget" and "until the attach commits or the run is stopped and the proof withdrawn; rerun after a killed run" in the flag help and cli.md, and dropping "brief" from limitations.md#L139, would make the acknowledgement mean what it is accepted for.

  2. The refusal says "nothing was executed", and the same PR documents that the refusal can drop a leftover proof. defaultWindowRefusalVerdict (online_attach_default_window.go#L67) says the refusal executed nothing, while limitations.md#L23 says the refusal first drops an exclusion CHECK an earlier run with the window accepted left on the DEFAULT partition, after waiting for its readers and writers. That is the safe thing to do, and an operator who reads the log would want to know it happened. "nothing was added" would be true in both cases; the doc comment on onlineAttach describes the upfront refusals in those terms (online_attach.go#L33-L36: "refusals with nothing added").

  3. No unit test pins the call-site gate or two of the policy rules; only the integration tests (not run here) do. Three mutants of online_attach.go survived the unit tests I ran: M1 acceptWindow := true, M2 the pass-through to AttachPartitionOptions dropped, and M6 the errors.Is(err, executor.ErrAttachPartitionDefaultWindow) branch removed (it falls through to the failed-verdict path, which TestOnlineAttachRefusalClassifiesTheUpfrontStops does not exercise because it calls onlineAttachRefusal directly). The audit record has no test at all (no test references auditAcceptDefaultWriteWindow). M1 is the safety-relevant one: every attach would run with the window accepted. The integration tests at online_attach_integration_test.go#L153 and #L168 and attach_partition_flow_integration_test.go#L184 look like they would kill M1, M2 and M6, but they need a live PostgreSQL and I did not run them. Two rules the PR states but does not pin in unit tests pass at head and are worth keeping:

Test case: the acknowledgement names the parent exactly, and Force beside the window is a usage error
func TestAcceptDefaultWriteWindowAckNamesTheParentExactly(t *testing.T) {
	st, err := statement.ParseOne(`ALTER TABLE app.orders ATTACH PARTITION app.orders_2027 FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`)
	require.NoError(t, err)
	require.NoError(t, checkAcceptDefaultWriteWindowAck(st, "app.orders"))
	for _, given := range []string{"app.orders_2027", "orders", "APP.ORDERS", "app.orders ", `"app"."orders"`, "other.orders"} {
		err := checkAcceptDefaultWriteWindowAck(st, given)
		require.ErrorIs(t, err, ErrAcceptDefaultWriteWindowMismatch, given)
		mismatch, ok := err.(*AcknowledgementMismatchError)
		require.True(t, ok, given)
		assert.Equal(t, "app.orders", mismatch.Table)
		assert.Equal(t, given, mismatch.Given)
	}
}

func TestOptionsRefuseForceBesideTheDefaultWindowAcknowledgement(t *testing.T) {
	opts := DefaultOptions()
	opts.Force = "app.orders"
	opts.AcceptDefaultWriteWindow = "app.orders"
	err := opts.validate()
	require.Error(t, err)
	assert.Contains(t, err.Error(), "Options.AcceptDefaultWriteWindow")

	opts.Force = ""
	require.NoError(t, opts.validate())
}

Both pass on 1aa637a (ok github.com/block/pg-sprite/pkg/migrate). The call-site mutants above need a test that drives onlineAttach against a database, so they stay covered only by the integration tests.

Verified

  • Ran only anchored unit tests with a timeout, after reading their bodies and checking the packages for database use: the two probes above in pkg/migrate (both pass) and TestOnlineAttachRefusalClassifiesTheUpfrontStops (passes, including under mutant M6). I did not run any integration, fault, load-proof, Supabase, docker or e2e test, and I did not connect to a database.
  • Mutants applied one at a time to online_attach.go, the unit tests run, then git checkout:
Mutant (production change) Caught by
M1 acceptWindow := true survived the unit tests I ran; the integration tests at online_attach_integration_test.go#L153 and #L168 should catch it (not run here)
M2 AcceptDefaultWriteWindow not passed to the executor survived the unit tests I ran; integration tests (not run here)
M6 the window-refusal branch removed survived TestOnlineAttachRefusalClassifiesTheUpfrontStops; integration tests (not run here)
M7 the audit call removed not applied: no test references auditAcceptDefaultWriteWindow, so it would survive

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 1aa637a: 0 blocking, 2 non-blocking.

Read the change from two seats: an importer that embeds pkg/migrate and routes on the verdict and the typed errors (SchemaBot is the obvious one), and an operator who meets the flag through --help, --dry-run and the refusal text. The addition fits the package's shape: the same typed acknowledgement as --force and the other flags (an Options field, a registry entry, ErrAcceptDefaultWriteWindowNotSupported and ErrAcceptDefaultWriteWindowMismatch sentinels, an *AcknowledgementMismatchError with the resolved table and the given text, a SCHEMA.TABLE placeholder, WithoutAcknowledgements and Acknowledgements() coverage), a refusal verdict that names what to rerun with, and docs in the five places the registry expects (cli.md, limitations.md, schemabot-integration.md, refusal-classes.md, capabilities.yaml/capabilities.md). An adapter that reads the acknowledgement list from the library picks the new flag up with no code of its own, as schemabot-integration.md#L1231 says. Review 1/2 covers the gate itself and finds it sound.

Non-blocking

  1. --dry-run is silent about the window and about the refusal a run may hit, so the one place a reviewer reads the plan never mentions the flag. The dry run reads no catalog, so it cannot know whether the parent has a DEFAULT partition, and the PR says so in limitations.md#L23 ("it plans the attach as executing on such a parent too, and the run is the first to refuse it"). The note it prints for the online attach (dryrun_text.go#L348-L349) describes the proofs and the brief attach and does not mention a DEFAULT partition or the flag. A change that is reviewed from the plan (the point of --dry-run, and of a plan an importer renders in a PR comment) therefore reads as certain to run, and the first sign of the acknowledgement is a refusal at apply time. One more clause in that note, such as "on a table with a DEFAULT partition this is refused unless --accept-default-write-window SCHEMA.TABLE accepts the write window it opens", would put the decision where it is made, without the catalog read the dry run does not do.
Test case: the dry-run note for an online attach names the DEFAULT partition window
func TestDryRunTextOnlineAttachNamesTheDefaultPartitionWindow(t *testing.T) {
	report := plan.NewReport(plan.SourceAlter)
	report.Schema, report.Table, report.ServerVersion = "app", "orders", "16.10"
	report.Disposition = router.DispositionExecute
	sql := `ALTER TABLE "app"."orders" ATTACH PARTITION "app"."orders_2027" FOR VALUES FROM ('2027-01-01') TO ('2028-01-01')`
	report.Statements = append(report.Statements, plan.Statement{
		SQL:         sql,
		Route:       planner.RouteNative,
		Backend:     router.BackendNative,
		Disposition: router.DispositionExecute,
		ExecSQL:     []string{sql},
		Execution:   planner.ExecutionOnlineAttach,
	})

	var out strings.Builder
	require.NoError(t, writeDryRunText(&out, palette{}, report))
	flat := strings.Join(strings.Fields(out.String()), " ")
	assert.Contains(t, flat, "will attach the table online")
	assert.Contains(t, flat, "DEFAULT partition")
	assert.Contains(t, flat, "--accept-default-write-window")
}

The first assertion passes on 1aa637a; the second and third fail (--- FAIL: TestDryRunTextOnlineAttachNamesTheDefaultPartitionWindow), since the note carries neither phrase. Passes once the note says so.

  1. The new refusal has no machine-readable cause, and its text names only the CLI flag. The verdict is Reason: unsupported-statement, Class: by-design (online_attach_default_window.go#L63-L70), which is a reason and class other refusals share, and the only thing that tells it apart is the detail string. The verdict package already has a typed discriminator for this (verdict.go#L503-L507, CauseCopyAndSwapNotEnabled, a refusal whose remedy is an operator opt-in just as this one's is). An importer that wants to offer "accept the window" as its own action, instead of showing the text, would otherwise match the detail. The detail also says rerun with --accept-default-write-window <table>, which is the CLI's wording; an importer embedding the library sets Options.AcceptDefaultWriteWindow, as schemabot-integration.md#L905-L913 documents, and would show a flag it does not have. Separately, the refusal for this case used to be capability-boundary and is now by-design (see refusal-classes.md#L121), so a consumer that branched on the class sees a different value for the same statement; a release note line that says so is the whole fix. A Cause value (and a detail that names both spellings, or a field the importer renders itself) would make the refusal routable; this is the same shape as the other opt-in refusals, not a defect in this PR's behavior.

What reads well for adopters

  • Everything an adopter needs to cite the rule is in one place: the typed error, the registry entry, and the refusal-classes.md row that names defaultWindowRefusalVerdict.
  • The flag cannot be left on a script by accident: the value must name the resolved parent exactly, the partition being attached is refused as a mismatch, and --force, --dry-run and --desired all reject it with a message that says why.
  • The refusal states what will happen if accepted (a CHECK on the DEFAULT partition, SQLSTATE 23514 for writes inside the bound, until the attach commits) and the other way out (detach the DEFAULT partition first), which is what a person reading it at 3am needs.

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.

🤖 First-pass review of 1aa637a: 0 blocking, 5 non-blocking (3 in the correctness review, 2 in the OSS adoption review, both posted as PR comments). The new path opens only with the typed acknowledgement, the accepted window is the documented one, and without the flag the plan still refuses.

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

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.
docs/capabilities.md is regenerated from the merged capabilities.yaml:
the attach row keeps the DEFAULT write window, the detach row takes main's
nested, referenced, and cross-schema text.
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