Skip to content

migrate: let a dry run and hosts see a stopped run's resume - #650

Open
Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd88-dryrun-stopped-resume
Open

Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd88-dryrun-stopped-resume

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

A dry run of a stopped copy-and-swap run's own statement now shows that the apply will resume that run, and hosts get a call that answers the same question.

Why

When a copy-and-swap run stops, rerunning the same statement resumes it from its checkpoint. The dry run did not look for the stopped run, so it showed the route the statement would take on the table as it is now, sometimes even a native one when the swap had already committed, while the apply would hand it back to copy-and-swap. A host had a call that says whether a statement is refused over a stopped run, but nothing that says it would resume.

What

  • New migrate.ResumesStoppedRun(ctx, pool, st, schema, table, opts) (plan.Resume, bool, error), beside AdmitStoppedRun and reading the row the same read-only way without the table lock: true only when the statement is the stopped one and --restart is not set. A host calls both: refused, resumes, or routes as usual.
  • New plan statement field resumes: {phase}, applied by plan.ResumeStoppedRun: route and backend copy-and-swap, disposition execute, no exec_sql, refusal fields and guidance cleared; the planner's decisions keep their classification. Not in the fingerprint; the route and backend it sets are.
  • Plan format_version 43 → 44, with plan-report.md, CLI output examples and the demo's pins.
  • The dry run text prints a "will resume … stopped in phase X" note.
  • schemabot-integration.md: the sentence saying the dry run shows today's route now describes the resume and the host call.
  • Tests: the CLI dry-run test over a run stopped in verifying keeps the refusal for another statement and now asserts resumes: {phase: verifying} for its own (absent under --restart), and fails when the dry run skips the read; a pkg/migrate integration test covers the three answers; a unit test pins the rewritten statement's JSON.

Before / after

A write-blocking ALTER TABLE orders ALTER COLUMN qty TYPE bigint stopped in verifying, previewed with the same statement.

Before
  migrate --dry-run   route/backend from today's table, no sign of the stopped run
  migrate             resumes the stopped run from verifying          ← preview did not say so
  host                AdmitStoppedRun → "not refused"   (resume and "no stopped run" look the same)

After
  migrate --dry-run   route copy-and-swap, execute, resumes: { phase: verifying }
  migrate             resumes the stopped run from verifying          ← matches
  host                AdmitStoppedRun → not refused; ResumesStoppedRun → { verifying }, true

Another statement on the same table still previews the copy-and-swap-run-stopped refusal.

A dry run of the stopped statement showed today's route while the apply
resumes the run, and a host had no call telling resume from no stopped
run. ResumesStoppedRun answers it; the plan gains resumes (format 44).
@Kiran01bm
Kiran01bm marked this pull request as ready for review November 30, 2026 08: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-11-30T08:15:23.701693Z
We couldn’t complete this review. Comment @codex review to try again.
55d9872 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 55d9872: 0 blocking, 5 non-blocking.

Inspected the whole change at 55d9872e5adeefb929a93052c56603438dba16af against its base main (merge base ed1ba99e): ResumesStoppedRun (copy_swap_stopped.go#L274-L297), plan.ResumeStoppedRun and the new Resumes field (plan.go#L303-L319, plan.go#L612-L643), the call site in the imperative dry run (dryrun.go#L197-L211), the text note (dryrun_text.go#L322-L330), the format_version 44 bump across the docs, demo and tests, and the two tests. I read them against the apply path they forecast: Run's stopped-run block (migrate.go#L393-L461), the dry-run admissions that already read the same row (dry_run_copy_swap.go#L26-L129), and the Runner's restart dispatch.

The change is sound for what it sets out to do. The resume condition is the apply's own (stopped.resumedBy(st) is the predicate Run uses at migrate.go#L404), the gates Run runs before it resumes (destructive, closed route, other-mode run) are all asked earlier in the dry run, and the plan's marking runs after them, so it cannot turn a refusal into an executable plan. The marked statement skips the native sequence admissions in the loop at dryrun.go#L220-L277 because its route is no longer native, which matches the apply handing it straight to copyAndSwap. The fingerprint covers the route, backend and disposition it sets and not resumes, which the doc row and the test both say. Upholds ST-2 (an unreadable or incompatible row still holds the table, since resumedBy needs a judged row) and ST-6 (the forecast writes nothing). No finding is a regression against main.

Non-blocking

  1. Under --restart the plan still shows the route against the table's current shape, while the apply sends the stopped statement to copy-and-swap, and for a swapped cutover row it refuses. ResumesStoppedRun returns no resume whenever Restart is set (copy_swap_stopped.go#L293-L295), and plan-report.md#L127 says why: "--restart discards the stopped run and starts over". Run decides differently. resumes is computed without looking at Restart (migrate.go#L404), the restart route check is skipped for it (migrate.go#L408-L412), and it calls copyAndSwap with the restart option (migrate.go#L453). The Runner then discards the row first (runner_dispatch.go#L77-L80), and refuses with restart-swap-committed when the row is a cutover whose swap the catalog shows committed (runner_restart.go#L46-L47, #L83-L92). So a dry run of qty TYPE bigint --copy-and-swap --block-writes public.orders --restart public.orders over a cutover row whose swap committed routes the statement natively against the already-retyped table and prints an executable plan with exit 0, where the apply ends in a refusal. The admission layer already agrees with the apply here (AdmitCopySwapPreflight calls runsCopySwap(rs, resumes, opts), which is true for a resume whatever Restart says, dry_run_copy_swap.go#L87-L88), so after this change the preflight and the plan describe two different runs under --restart. Before a swap commits the two coincide, since the statement still routes to copy-and-swap, and the PR's test covers that case; this is not a regression, the dry run printed the native plan before too. Not run here (needs the database). A fix is to keep the copy-and-swap route and backend on the plan for a statement resumedBy accepts under --restart as well (with Resumes left empty) and let the dry run forecast restart-swap-committed from the same catalog read the Runner uses, or to say in the doc row that --restart plans are not forecast for a cutover row.

  2. Most of ResumeStoppedRun has no test: only the happy native-to-copy-and-swap input is exercised. TestResumeStoppedRunPlansTheResume (plan_test.go#L1052) starts from an execute native statement with no refusal fields, so every line that withdraws a refusal is a no-op on its input: the statement and report Disposition, Reason/Class/Owner, BlockingPassthroughEligible, RefusalCause, Guidance, and the safer SQL on the decisions (plan.go#L631-L642). Deleting all of them leaves the test green, and the length guard at plan.go#L625 has no test either. That is the branch a post-swap resume actually takes when the current shape routes to a refusal, and it is the one a host would read to decide the plan is executable.

Test that passes on 55d9872 and fails when those withdrawals are deleted
func TestResumeStoppedRunWithdrawsARefusal(t *testing.T) {
	eligible := true
	r := plan.NewReport(plan.SourceAlter)
	r.Schema, r.Table = "app", "orders"
	r.Disposition = router.DispositionRewriteRequired
	r.Reason, r.Class, r.Owner = verdict.ReasonUnsupportedStatement, verdict.ClassByDesign, verdict.OwnerDirectOperator
	r.Statements = []plan.Statement{{
		SQL:                         "ALTER TABLE app.orders ALTER COLUMN qty TYPE bigint",
		Route:                       planner.RouteRefuse,
		Disposition:                 router.DispositionRewriteRequired,
		Reason:                      verdict.ReasonUnsupportedStatement,
		Class:                       verdict.ClassByDesign,
		Owner:                       verdict.OwnerDirectOperator,
		BlockingPassthroughEligible: &eligible,
		RefusalCause:                verdict.CauseColumnFirstForeignKey,
		Guidance:                    suggest.GuidanceSplitStatement,
		Decisions: []planner.Decision{{
			Operation: "ALTER COLUMN qty TYPE bigint",
			Route:     planner.RouteRefuse,
			SaferSQL:  []string{"SELECT 1"},
		}},
		ExecSQL:   []string{"SELECT 1"},
		Execution: planner.ExecutionAutocommit,
	}}
	require.NoError(t, plan.ResumeStoppedRun(&r, plan.Resume{Phase: "cutover"}))
	st := r.Statements[0]
	assert.Equal(t, planner.RouteCopyAndSwap, st.Route)
	assert.Equal(t, router.BackendCopyAndSwap, st.Backend)
	assert.Equal(t, router.DispositionExecute, st.Disposition)
	assert.Equal(t, router.DispositionExecute, r.Disposition)
	assert.Empty(t, st.Reason)
	assert.Empty(t, st.Class)
	assert.Empty(t, st.Owner)
	assert.Empty(t, r.Reason)
	assert.Empty(t, r.Class)
	assert.Empty(t, r.Owner)
	assert.Nil(t, st.BlockingPassthroughEligible)
	assert.Empty(t, st.RefusalCause)
	assert.Empty(t, st.Guidance)
	assert.Empty(t, st.ExecSQL)
	assert.Empty(t, st.Execution)
	assert.Nil(t, st.Decisions[0].SaferSQL)
	assert.Equal(t, &plan.Resume{Phase: "cutover"}, st.Resumes)
}

func TestResumeStoppedRunRefusesAnyOtherLength(t *testing.T) {
	r := plan.NewReport(plan.SourceAlter)
	require.Error(t, plan.ResumeStoppedRun(&r, plan.Resume{Phase: "copying"}))
	r.Statements = make([]plan.Statement, 2)
	require.Error(t, plan.ResumeStoppedRun(&r, plan.Resume{Phase: "copying"}))
}

Both pass on 55d9872. With plan.go lines 631-633, 638, 639, 641 and 642 deleted, TestResumeStoppedRunPlansTheResume still passes and the first test fails: --- FAIL: TestProbeResumeStoppedRunWithdrawsARefusal (the probe copy of the test above), expected: "execute" actual : "rewrite-required" on the statement and report disposition, plus Should be empty, but was unsupported-statement on Reason.

  1. The text note for a resume has no test that runs without a database. The resume branch in writeExecutionNotes (dryrun_text.go#L324-L329) is reached only by TestMigrateDryRunRefusesAnotherStatementOverAStoppedCopySwapRun, which sets retype.JSON = true (stopped_run_integration_test.go#L170), so no test renders the human report for a resume at all, and the neighbouring copy-and-swap renderings are pinned by unit tests in dryrun_text_test.go. Rendering it also shows one thing worth a look: the planner's decision for the current shape still prints above the resume note, so the operator reads note[metadata-only]: ALTER COLUMN qty TYPE bigint — a brief catalog-only change; takes a short exclusive lock but does not scan or rewrite the table and then pg-sprite will resume the copy-and-swap run of this statement stopped in phase cutover. The note's last clause ("whatever the statement routes to against the table's current shape") reconciles the two, but a reader skimming the diagnostics sees a metadata-only change beside a copy-and-swap. Suppressing the current-shape decision lines for a statement with Resumes (they describe a run that will not happen) would be the clearer report.
Test that passes on 55d9872 and fails when the resume branch is removed
func TestDryRunTextNamesTheResumeOfAStoppedRun(t *testing.T) {
	r := plan.NewReport(plan.SourceAlter)
	r.Schema, r.Table, r.ServerVersion = "public", "orders", "16.10"
	r.Disposition = router.DispositionExecute
	r.Statements = []plan.Statement{{
		SQL:         `ALTER TABLE "orders" ALTER COLUMN "qty" TYPE bigint`,
		Route:       planner.RouteNative,
		Backend:     router.BackendNative,
		Disposition: router.DispositionExecute,
		Decisions: []planner.Decision{{
			Operation: "ALTER COLUMN qty TYPE bigint",
			Route:     planner.RouteNative,
			Reason:    planner.ReasonMetadataOnly,
		}},
		ExecSQL:   []string{`ALTER TABLE "orders" ALTER COLUMN "qty" TYPE bigint`},
		Execution: planner.ExecutionAutocommit,
	}}
	require.NoError(t, plan.ResumeStoppedRun(&r, plan.Resume{Phase: "cutover"}))

	var out strings.Builder
	require.NoError(t, writeDryRunTextWithCopySwapFlags(&out, palette{}, r, copySwapRunFlags{blockWrites: "public.orders"}))
	flat := strings.Join(strings.Fields(out.String()), " ")
	assert.Contains(t, flat, "pg-sprite will resume the copy-and-swap run of this statement stopped in phase cutover")
	assert.NotContains(t, flat, "will run it as a copy-and-swap")
	assert.Contains(t, out.String(), "plan:\n  public.orders (PostgreSQL 16.10) — 1 statement, 1 step to run, 0 refused\n")
}

ok github.com/block/pg-sprite/internal/cli on 55d9872; with the branch disabled (if false && ps.Resumes != nil) it fails: does not contain "pg-sprite will resume the copy-and-swap run of this statement stopped in phase cutover".

  1. The desired-state dry run is left out, and the integration guide reads as if it were covered. ResumeStoppedRun is called from the imperative dry run only (dryrun.go#L207), and the doc row scopes resumes to the alter source. But AdmitPlanStoppedRun lets a desired plan whose first statement is the stopped one through as a resume (copy_swap_stopped.go#L304-L305), and the paragraph the PR edits in the integration guide opens with "--dry-run reads the row the same way, imperative and desired-state alike" before saying "the dry run of the stopped statement itself ... shows the resume the apply makes" (schemabot-integration.md#L1506-L1511). A desired-state dry run over the same stopped run still shows the first statement against the current shape with no resumes. Either mark the first statement of a desired plan the same way, or say in that paragraph that the resume is shown for the imperative dry run only. Found from source; not run here.

  2. Two stale spots left behind by the version bump and the new door. docs/cli.md#L1147 still prints "format_version": 43 in the jq example (no docs test pins it, so it was missed). And the ST-2 paragraph in invariants.md#L1269-L1271 lists the dry-run doors that read the stopped-run row (AdmitStoppedRun, AdmitPlanStoppedRun, AdmitRowSecurityStoppedRun) but not the new ResumesStoppedRun; the disposition is "upholds ST-2", and the citation is the only thing that needs the update.

Verified

Ran, on 55d9872: TestResumeStoppedRunPlansTheResume, TestDocStatesCurrentFormatVersion, TestEveryDoorChecksForAStoppedRunBeforeItExecutes (the new exported ResumesStoppedRun reads through findStoppedRun and runs nothing, so the door walk accepts it), each as a single anchored -run; and go vet ./pkg/plan ./pkg/migrate ./internal/cli is clean. The two integration tests the PR adds need a database and were not run here; I read them against the code.

Mutant Caught by
Delete st.Route = planner.RouteCopyAndSwap (plan.go#L629) TestResumeStoppedRunPlansTheResume (route reads native)
Delete the refusal withdrawals (plan.go lines 631-633, 638, 639, 641, 642) Survives the PR's tests; killed by the test in finding 2
Disable the resume branch of the text note (dryrun_text.go#L324) Survives every test that runs without a database; killed by the test in finding 3
Drop the resumedBy check or the Restart check in ResumesStoppedRun Not run here (database). By reading, TestResumesStoppedRunAnswersOnlyForTheStoppedStatement asserts both: another statement resumes nothing, and restart returns false

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

Read the change from two seats: an importer that plans through pkg/migrate and pkg/plan and renders or gates on the report (SchemaBot is the obvious one), and an operator who meets the plan through migrate --dry-run and the guide. The addition fits the package's shape. ResumesStoppedRun returns (value, bool, error) the way the Admit* family returns (verdict, bool, error), it takes the same (ctx, pool, st, schema, table, opts) arguments as AdmitStoppedRun, and its doc comment says how the two relate. plan.ResumeStoppedRun follows the other Route* mutators on a report (it edits in place and refuses a report of the wrong shape). The contract change is handled the way the repo's own rule asks: FormatVersion goes to 44 with a history entry in plan-report.md#L48, a field row at plan-report.md#L127, the pinned JSON-shape tests and the demo's pins move together, and TestDocStatesCurrentFormatVersion passes. A consumer that pins format_version 43 will see every dry-run plan change version, not only the stopped-run ones, which is how the contract has worked for each earlier field and is stated in the doc.

Non-blocking

  1. A host has to assemble the answer from several separate reads of the row, in the right order. The new doc comment describes the protocol: "refused there, resumed here, and routed as usual when neither" (copy_swap_stopped.go#L281-L283). In the CLI that is AdmitStoppedRun (dryrun.go#L109), then the route and preflight admissions that each read the row again (dryrun.go#L139, #L154), then ResumesStoppedRun (dryrun.go#L202): four unlocked reads of the same checkpoint row on the default path, five with --restart. Each is a forecast and the run reads the row again under the lock, so none is unsafe, but the reads are independent: a row that finishes or is discarded between the preflight and ResumesStoppedRun gives a plan whose admissions ran as a resume and whose route shows the current shape, with no error. An importer copying the CLI's sequence inherits that. A single entry point that reads the row once and answers "refused (with the verdict) / resumes (with the plan.Resume) / neither", or a small exported StoppedRun value the Admit* functions and ResumesStoppedRun could each take, would let a host get one consistent answer and would make the order dependency (call it after the admissions) something the type carries rather than the comment.

  2. plan.Resume carries only the phase, and the contract is now versioned around it. The row ResumesStoppedRun already holds knows more than the plan reports, and two of those facts decide what a host shows or offers. Whether the stopped run blocked writes or streamed through a slot decides which flags the apply accepts (refuseOtherModeRun refuses a resume in the other mode, migrate.go#L431-L435), and stoppedRun.stoppedBlockingWrites() / stoppedLive() are the predicates for it (copy_swap_stopped.go#L136-L149). When the row was last saved is what the apply writes to its audit line (migrate.go#L450-L452), and is what tells an operator whether the run is minutes or weeks old. A host that renders "this will resume" with only a phase has to call the checkpoint store itself for the mode and the age. Adding either field later is another format_version bump for every consumer, so it is cheaper to decide now whether the plan should carry them. The same applies to the Phase string: the doc row lists the five values, but nothing in pkg/plan exports them, so a host switching on it matches string literals (the checkpoint package's Phase.String() is the source, and a typed or documented-closed vocabulary would sit with the other vocabularies the docs test enumerates).

Verified

Read for adoption: the doc row and history entry, the integration guide paragraph, the Admit* family's signatures and doc comments for consistency, the exported surface the PR adds (ResumesStoppedRun, plan.Resume, plan.ResumeStoppedRun, Statement.Resumes), and the format_version pins (the doc, demo, and tests are all at 44, with one stale 43 in docs/cli.md, reported in 1/2). Ran TestDocStatesCurrentFormatVersion and TestEveryDoorChecksForAStoppedRunBeforeItExecutes as single anchored -runs on 55d9872: both pass. The finding-1 read counts come from the call sites cited above; no test was run for them.

Mutant Caught by
Not applicable: both findings are about the exported surface, not a production line covered by the mutation table in 1/2

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, 7 non-blocking (see the review comments above).

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

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