Skip to content

executor: refuse a replayed DETACH ... FINALIZE step in RunSequence - #689

Open
Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd134-refuse-finalize-replay
Open

Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd134-refuse-finalize-replay

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

executor.RunSequence now refuses a sequence that carries ALTER TABLE ... DETACH PARTITION ... FINALIZE before any of its steps runs.

Why

Detaching a partition concurrently can be interrupted, leaving the partition "detach-pending"; the plan then shows the FINALIZE statement that finishes it. A library caller that copied that statement back into a sequence had it run as a plain step inside a transaction, after earlier steps had already changed the table, instead of through the detach step that checks the partition's state first. Now the caller is told up front to rerun the original concurrent detach, and nothing in the sequence runs.

What

  • admitAlterTableStep checks the parsed statement's FinalizesDetach() first and returns ErrUnsupportedSequenceStep, pointing at the DETACH PARTITION ... CONCURRENTLY that finishes the detach. The existing sentinel keeps the typed code mapping unchanged.
  • The dry run is unaffected: it admits the concurrent form before previewing FINALIZE.
  • docs/plan-report.md's exec_sql row states the refusal.
  • Tests: a unit test (refused at step 2 of 2, nothing admitted, the concurrent form still admits) and an integration test (the note column is never added and the partition stays attached).

Before / after

The same two-step sequence goes to RunSequence. Before, step 1 commits and step 2 then runs as a plain transactional step; after, the sequence is refused before step 1.

input: RunSequence([
  "ALTER TABLE events ADD COLUMN note text",
  "ALTER TABLE events DETACH PARTITION events_2024 FINALIZE",
])

Before
  admit step 2 ──▶ parser: unrecognized op ──▶ brief class (admitted)
  run step 1   ──▶ note column added, committed
  run step 2   ──▶ FINALIZE runs inside a transaction as a plain step,
                   with no read of the partition's detach state

After
  admit step 2 ──▶ FinalizesDetach() is true ──▶ refused
  result       ──▶ ErrUnsupportedSequenceStep: "sequence step 2 of 2:
                   DETACH PARTITION ... FINALIZE: run the DETACH PARTITION
                   ... CONCURRENTLY that started the detach again"
  table        ──▶ unchanged: no note column, events_2024 still attached

A FINALIZE step ran as an ordinary brief step inside a transaction,
skipping the detach step's partition read; refuse it before anything runs.
@Kiran01bm
Kiran01bm marked this pull request as ready for review December 2, 2026 02:43
@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-02T02:43:14.615171Z
We couldn’t complete this review. Comment @codex review to try again.
e79ba54 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 e79ba54: 0 blocking, 4 non-blocking.

Inspected the whole change at e79ba54939af043ecd93c09637be05109ea83f5e: the new refusal in admitAlterTableStep, the two new tests, and the exec_sql row in docs/plan-report.md, against every path that sends a DETACH PARTITION ... FINALIZE to the server or hands one to admission. CI at the time of posting: all 18 checks green, including build, lint, unit tests (docs guards), the PostgreSQL 14 to 18 legs, Supabase compatibility, smoke, all-green and DCO.

The PR is +69/-2. A sequence step that parses as ALTER TABLE ... DETACH PARTITION ... FINALIZE is now refused at admission with ErrUnsupportedSequenceStep, before any step runs. The refusal is correct, and it cannot reach a legitimate first FINALIZE: the engine's own FINALIZE never goes through admission. detachPartitionConcurrently reads the partition's state, swaps target.finalizeSQL in for the statement when inhdetachpending is set, and sends it with runDetachAttempt on a session of its own. A caller reaches that path by submitting the original DETACH PARTITION ... CONCURRENTLY, which still admits as StepDetachPartition (#L619-L625); the PR's unit test pins that beside a brief step.

What "replayed" means here, from the code: nothing is detected. The check is on the parsed statement (FinalizesDetach(), statement/detach_partition.go#L27), so it refuses every FINALIZE a caller puts in a sequence, whether a crash left the partition pending, an earlier run already finished it, or nothing was ever pending. That is the right design (admission reads no catalog, ST-6), and it is why the legitimate path loses nothing.

Invariants (docs/invariants.md): ST-6 ("every knowable prerequisite is validated before the engine writes anything", #L1639) and the INV: ST-6 comment at sequence.go#L317: the PR upholds it and extends the shapes decided before the first step. ST-7 (#L1741): upheld, since shape is judged before the target check. LK-2 (#L840): upheld; its text (#L861-L866) says a rerun of the same statement finishes a pending detach, which is exactly what the refusal message tells the caller to do. No entry needs rewording.

Non-blocking

  1. The PR, the test name and the comment say "replayed", but the code cannot tell a replay from a first FINALIZE. The title, TestAdmitSequenceRefusesAReplayedDetachFinalize (sequence_internal_test.go#L193) and the new comment ("a step that replays it", sequence.go#L610-L613) describe a catalog-state check that does not exist. A later reader who sees "replayed" will look for the inhdetachpending read and conclude a first FINALIZE might be admitted. Naming it for what it checks (...RefusesADetachFinalize, "a step that carries a FINALIZE") says the true thing: the refusal is by shape, independent of catalog state. The integration test's name already does this.

  2. The refusal is tested for one spelling of the statement; alterFinalizesDetach has other branches. alterFinalizesDetach walks every subcommand, so ADD COLUMN ..., DETACH PARTITION ... FINALIZE and the IF EXISTS and ONLY spellings are refused, but both new tests use the single qualified form. A change that checked only the first subcommand, or only one AlterTableStmt shape, would pass both tests while a multi-command FINALIZE ran as a brief step again. The spellings are reasoned from the parser code, not run (no local build here).

Test case (not run here): a FINALIZE in any spelling is refused
func TestAdmitSequenceRefusesADetachFinalizeInEverySpelling(t *testing.T) {
	for name, sql := range map[string]string{
		"beside another subcommand": `ALTER TABLE s.t ADD COLUMN note text, DETACH PARTITION s.p FINALIZE`,
		"if exists":                 `ALTER TABLE IF EXISTS s.t DETACH PARTITION s.p FINALIZE`,
		"only":                      `ALTER TABLE ONLY s.t DETACH PARTITION s.p FINALIZE`,
	} {
		t.Run(name, func(t *testing.T) {
			require.ErrorIs(t, AdmitSequenceShape([]string{sql}), ErrUnsupportedSequenceStep)
		})
	}
}

Not run: the three spellings are expected to parse and be refused by the loop in alterFinalizesDetach; if one does not parse, drop it from the table.

  1. The legitimate counterpart is pinned elsewhere, not beside the new test. Nothing is missing, but a reader of detach_partition_integration_test.go sees only the refusal. The finish of a pending detach by the concurrent statement is pinned in the same file by TestRunSequenceReportsTheFinalizeThatEndedItsOwnInterruptedDetach (the step's own retry), and across runs in TestRunRefusesADetachWhileAnotherPartitionIsPending (a partition left pending outside pg-sprite is finished by running the detach statement). A one-line pointer to the first from the new test's comment, which already says what the refusal leaves intact, would let the next contributor see both halves of the contract together.

  2. A refusal that fires before the first step leaves no state, and the integration test proves it, but it does not assert the typed code a host branches on. TestRunSequenceRefusesADetachFinalizeBeforeAnythingRuns checks ErrorIs, an empty rep.Steps, the missing note column and the still-attached partition. A host reads the outcome through executor.OutcomeCode (code.go#L695; the sentinel mapping is at #L868-L869), and ErrorIs already implies the code, so this is a polish: one assert.Equal(t, executor.CodeUnsupportedSequenceStep, executor.OutcomeCode(err)) states the contract a host depends on. Reasoned from the mapping, not run.

Verified

  • Read admission end to end: runSequence calls admitSequence first (#L320), admitSteps wraps a refusal with "sequence step N of M" (#L543), and the FINALIZE check sits first in admitAlterTableStep, so it fires before the target check and before any connection is used for a step. No SequenceStepError is produced, so nothing executed and the run is retryable by resubmitting a corrected sequence; the error text names the step, the statement shape, and what to run instead.
  • The dry run is unaffected, as the PR says: internal/cli/dryrun.go#L249 admits ps.ExecSQL (the concurrent form) first, and only afterwards #L289-L301 substitutes the FINALIZE into the report. migrate.Gate already refused a submitted FINALIZE (verdicts.go#L33-L44), so the library door is now consistent with the CLI door.
  • The refusal class is the existing one: ErrUnsupportedSequenceStep maps to unsupported-statement, capability-boundary (docs/refusal-classes.md#L95), as Gate's FINALIZE refusal does. No registry or classification change is needed.
  • Ran no test and built nothing here (the review read the diff and the files at the head over the GitHub API; the integration test also needs a PostgreSQL container); the new unit test, the new integration test and the existing pending-detach tests passed in CI at this head. I did not verify against a live server what the old brief-step path did with a FINALIZE; the refusal makes that moot.
  • Mutation table (by reading; CI shows the tests at this head pass):
Mutant Caught by
FinalizesDetach check deleted from admitAlterTableStep TestAdmitSequenceRefusesAReplayedDetachFinalize (ErrorIs fails), and the integration test (the note column is added)
check moved after isConcurrentDetach not caught; behavior is the same (a FINALIZE is not a concurrent detach), harmless
%w dropped from the error require.ErrorIs in both tests
AdmitSequenceShape stops refusing it the second assertion of the unit test (#L205)
alterFinalizesDetach checks only the first subcommand survives (finding 2)
concurrent detach no longer admitted beside a brief step the third block of the unit test

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

Read the change from two seats: a host that plans through the library and hands steps back to executor.RunSequence (the integration the guide describes for importers), and an operator or contributor who meets the refusal in a log and has to know what to do next. The refusal itself is the right call for both: it moves a failure that could land after earlier steps committed to before the first step, and it reuses ErrUnsupportedSequenceStep, so a host that already routes unsupported-statement needs no new branch.

Non-blocking

  1. The refusal text does not name the statement to run, and its wording differs from the CLI door's for the same statement. A host holding a plan's exec_sql that carries a FINALIZE gets "DETACH PARTITION ... FINALIZE: run the DETACH PARTITION ... CONCURRENTLY that started the detach again, which finishes it" (sequence.go#L615-L618). Its operator then has to rebuild which table and partition from the log line. The statement is derivable from the one that was refused: the refused statement names the table, and the partition is in the same parse tree (DetachedPartition deliberately returns ok=false for a FINALIZE, so a small sibling reader would be needed; I did not check the shape of the FINALIZE subcommand's node), so the error could print ALTER TABLE s.t DETACH PARTITION s.p CONCURRENTLY. And migrate.Gate says the same thing in other words, adding "or run this statement directly against the database", which is the shorter path for an operator who only wants the partition finished. Two doors, two wordings, one cause: a host that surfaces both to a user shows different advice. Reusing one sentence, or one shared helper that builds the message, keeps them aligned, and the operator-facing path (finish it directly) stays visible to the library door too. The worry is small because the typed code and the sentinel are the same; the text is what a human reads.

  2. The integration guide still reads as if the FINALIZE is a step to run. docs/schemabot-integration.md#L1200-L1202 tells a library host that migrate.PreviewDetachPartition "returns the FINALIZE that finishes a pending detach as the step", and nothing near it says to hand the original statement back. This PR updates the exec_sql row of the plan report (plan-report.md#L136) but not this paragraph, which is the one an importer reads when it writes the apply half. The consequence is concrete: a host that stores a dry run's steps and later passes them to executor.RunSequence, or to migrate.AdmitRoutedSteps (dry_run_admission.go#L43-L45) as a re-check, is now refused for exactly the table where a partition was pending when it planned. One sentence there, "the FINALIZE is shown, not run: submit the original DETACH PARTITION, which finishes the detach", mirrors the plan-report row and closes it. The docs guard in the unit-test job passed, so nothing mechanical catches the gap.

What reads well for adopters

  • The PR body shows one input run through the old and the new behavior, with the exact refusal text and the unchanged table (note never added, events_2024 still attached), which is what a host's author needs to decide whether their stored plans are affected.
  • The refusal happens before step 1, so a host never has to reconcile a half-run sequence: it resubmits a corrected one. That is the property an importer cares about most, and the integration test asserts it against the real catalog rather than only the error.
  • The sentinel is reused instead of a new code, so typed handling (unsupported-statement, capability-boundary) and the refusal classes table (refusal-classes.md#L95) stay true without edits.
  • The dry run keeps working: it admits the concurrent form first and shows the FINALIZE only as the report, so diff --json and migrate --dry-run consumers see no change.

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

Copy link
Copy Markdown
Collaborator

🤖 I reviewed the complete four-file diff at e79ba54939af043ecd93c09637be05109ea83f5e. The sequence admission rejects parsed DETACH PARTITION … FINALIZE before the executor reaches any step, preserves the typed unsupported-step error, and still admits the original concurrent detach form. The unit and integration tests check that the earlier statement never executes and the partition stays attached. I found no blocker.

P2 · Exercise a detach-pending fixture. The integration case starts with a normally attached partition. A fixture left in detach-pending state would additionally demonstrate that a FINALIZE obtained from a real preview is refused before step one and that retrying the original concurrent form finishes the pending detach. Sequence admission

GitHub reported all 18 checks successful. I did not run local tests. Direct Builderbot lookup failed to resolve its host. GitHub showed no current-head Builderbot check or review, and I did not independently enumerate unresolved inline threads.

@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 Codex on Jash’s behalf after reviewing the current head, as instructed. See my substantive review comment for findings and validation limits; approval does not resolve those findings.

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