Skip to content

fix(cli): point a desired-file plan at migrate --desired, not --alter - #625

Open
Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/desired-apply-pointer
Open

Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/desired-apply-pointer

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

After reviewing a desired-file plan, pg-sprite now tells you to run that plan with migrate --desired, pinned to the fingerprint it printed, instead of hand-running each statement through migrate --alter.

Why

pg-sprite can converge a live table onto a desired CREATE TABLE file: diff --desired (or migrate --desired --dry-run) shows the plan, and migrate --desired runs it. The report's closing apply: hint was written before migrate --desired existed and still told readers to paste each statement into migrate --alter one at a time. Doing that drops the plan's ordering, the fingerprint that guarantees the reviewed plan is the one that runs, and the final check that the table converged, and an agent reading the hint follows it literally.

What

  • The apply: entry prints pg-sprite migrate --schema <schema> --desired <file> with the file and schema flags the plan was derived under (--extension-schema, --foreign-key-schema), plus --expect-fingerprint <fp> when the report prints a fingerprint.
  • Flags that acknowledge something are named in prose, not added to the command: --allow-destructive SCHEMA.TABLE for a plan that drops something, --copy-and-swap and --free-disk SIZE for a copy-and-swap statement.
  • A greenfield plan (table missing) now gets the pointer too, since migrate --desired creates the table.
  • migrate --desired --dry-run closes with dry-run: instead of diff:, and its sql: entry points at pg-sprite diff … --sql, since migrate has no --sql.
  • A one-step safer sequence's verdict reads "its 1 step committed" instead of "all 1 steps committed".
  • docs/cli.md shows the new tail; docs/primary-keys.md picks up the pluralization.

Before / after

The README quick start pulls app.orders, adds a column and an index to schema/orders.sql, and runs pg-sprite diff --schema app --desired schema/orders.sql. The statements, plan summary, and fingerprint are unchanged; only the apply: entry differs, and it now names the command that runs this exact plan.

Before                                                   After
──────                                                   ─────
plan:                                                    plan:
  app.orders (PostgreSQL 16.15) — 2 statements,            app.orders (PostgreSQL 16.15) — 2 statements,
  2 steps to run, 0 refused                                2 steps to run, 0 refused

fingerprint:                                             fingerprint:
  sha256:6f0c1d52…0c9b2a                                   sha256:6f0c1d52…0c9b2a

diff:                                                    diff:
  nothing was executed                                     nothing was executed

sql:                                                     sql:
  re-run with --sql to print the plan as an                re-run with --sql to print the plan as an
  executable SQL script                                    executable SQL script

apply:                                                   apply:
  run each statement via pg-sprite migrate                 pg-sprite migrate --schema app --desired
  --alter '…', which refuses blocking forms and              schema/orders.sql --expect-fingerprint
  substitutes safer online sequences                         sha256:6f0c1d52…0c9b2a
                                                           runs the plan in order, refusing blocking forms
  ▲ reader pastes each statement by hand: no               and substituting safer online sequences, then
    order, no pin, no convergence check                    plans again to confirm nothing is left; the pin
                                                           refuses, executing nothing, a plan that changed
                                                           since this review

The real output prints the command on one unwrapped line so it can be copied whole; it is folded here to fit the diagram. migrate --schema app --desired schema/orders.sql --dry-run prints the same apply: entry, with dry-run: in place of diff: and a sql: entry that points at pg-sprite diff … --sql.

The apply hint after diff --desired and migrate --desired --dry-run sent
readers to hand-run each statement through migrate --alter, losing the
plan's order, the fingerprint pin, and the convergence check.
@Kiran01bm
Kiran01bm marked this pull request as ready for review November 29, 2026 23:47
@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-29T23:47:57.460975Z
We couldn’t complete this review. Comment @codex review to try again.
8ad31f2 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 8ad31f2: 0 blocking, 3 non-blocking.

Inspected the whole change at 8ad31f23df44141b8d4137adba7019f4271ac8cf, with the question the title poses: does the apply: line diff and migrate --desired --dry-run print run the operation the operator planned, for every input shape? The pointer is built by writeDesiredApply from desiredArgs and shellWord, and it is fed by the diffFraming that diff.go#L107 and the three dryRun: true preview sites (migrate_desired.go#L167, #L314, migrate_row_security.go#L30) set. I also read the new saferSequenceDetail (migrate.go#L801-L807), the doc changes and the new tests.

The pointer holds up on every input shape I could reach:

  • Desired file. The only shape that prints a pointer. --desired is existingfile, so kong expands it to an absolute path before the report sees it, and the printed command names that same file. The schema comes from the report, the extension schemas from the report (the fingerprint covers them), and the foreign key schemas from the framing, so the re-derived plan is the one reviewed.
  • Desired directory. existingfile rejects it, so no report exists and no pointer is printed.
  • --alter. diff has no such flag, and a migrate --alter run never goes through this renderer; the --alter hints at diff.go#L250 and #L283 are in writePlanText, the --sql script writer, which this PR does not touch.
  • Stdin (-). kong lets - through without a stat, and the later os.ReadFile("-") fails, so no report and no pointer.
  • Paths with spaces and shell metacharacters. I wrote a throwaway test that prints the command for spaces, single and double quotes, $, backtick, ;, &, *, ~, #, leading -, unicode and an empty schema, runs the printed line through /bin/sh word splitting, and feeds the words back to kong. Every case came back as the original path and the original flags, so the quoting round-trips. (A filename containing a newline broke my own test harness, not shellWord; I dropped that case.)
  • Fingerprint. pinFingerprint prints PinnableFingerprint when the plan has one, so a dry run's refused preview of a destructive plan pins the fingerprint a run accepts, not the preview's own. Both routes through CheckPlanPin accept what is printed.
  • Row-security and enum-type desired files. Both dry-run previews pass the same Desired, Schema and dryRun, so the pointer names a command those paths run.
  • The step counts in saferSequenceDetail read correctly for one step and for several.

Invariants (docs/invariants.md): this upholds RF-12 (invariants.md#L2109). The pointer never carries --allow-destructive, --accept-blocking or --copy-and-swap; those stay in prose, so running the line as printed can only be refused by the acknowledgement gates, never skip one. The pin is added from the plan itself, which is what RF-12 requires beside a destructive acknowledgement. No *Enforced:* line moves, because the change is in the renderer and not in the gates.

Non-blocking

  1. The refused == 0 half of the apply guard is not pinned: a plan with one runnable and one refused statement has no test. diff_text.go#L93 prints the pointer only when nothing is refused and at least one step runs. The existing test for it, TestDiffTextRefusedStatementDropsApply, uses a plan whose only statement is refused, so steps > 0 already suppresses the pointer and refused == 0 is never the deciding term. A change that keeps steps > 0 and drops refused == 0 passes the whole suite (I ran TestDiffTextRefusedStatementDropsApply and both TestDiffTextGreenfieldRefused* tests under it, all green; mutant M6 below). That change would print a runnable-looking command for a plan that AdmitPlan refuses whole, with the same pin, so the operator would paste it and be refused. It fails safe, but the guard is what keeps the pointer honest for a mixed plan.
Test case: a mixed plan (one runnable statement, one refused) drops the apply pointer
func TestDiffTextMixedRefusedPlanDropsApply(t *testing.T) {
	report := desiredReport(false)
	report.Statements[0].ExecSQL = []string{report.Statements[0].SQL}
	report.Statements[0].Backend = router.BackendNative
	report.Statements = append(report.Statements, plan.Statement{
		SQL:         `ALTER TABLE app.orders ADD COLUMN joined timestamptz DEFAULT now()`,
		Route:       planner.RouteCopyAndSwap,
		Backend:     router.BackendCopyAndSwap,
		Disposition: router.DispositionUnavailable,
	})
	report.Disposition = router.DispositionUnavailable
	report.Fingerprint = report.ComputeFingerprint()

	var out strings.Builder
	require.NoError(t, writeDiffText(&out, palette{}, report, diffFraming{desired: "schema/orders.sql"}))
	text := out.String()
	assert.Contains(t, text, "2 statements, 1 step to run, 1 refused\n")
	assert.NotContains(t, text, "apply:")
}

Passes on 8ad31f2; --- FAIL: TestDiffTextMixedRefusedPlanDropsApply (0.00s) with "should not contain apply:" under mutant M6.

  1. A plan that both drops something and routes a statement to copy-and-swap gets a pointer and prose that no run accepts. When a destructive statement and a copy-and-swap statement sit in one plan, the report prints the pointer, then "the run also needs --allow-destructive app.orders" and "also needs --copy-and-swap ... --free-disk SIZE" (diff_text.go#L119-L124). AdmitPlan refuses that plan whole with destructive-change whatever flags are added (desired.go#L767-L769, #L814-L830), and RF-12 states the same rule. I confirmed it with a hand-built report (a drop plus a copy-and-swap statement) through writeDiffText and AdmitPlan, not against a live database: the text names both flag sets, the run refuses with the drop-then-copy-and-swap detail. The operator is refused before anything executes, so nothing unsafe happens, and the refusal text says to split the change. The report is the place that could say so first, by dropping the pointer for that shape or adding one clause, since a reader following the printed prose adds two flag sets and still cannot run it. refuseDestructiveWithCopySwap is already the one predicate for the shape, so the renderer could ask it instead of re-deriving.

  2. The pointer carries the file and schema flags but not the connection flags, so a run can use different session settings than the plan was derived under. DBFlags has --ca-cert, --lock-timeout and --statement-timeout besides the URL (cli.go#L50-L55), and none of them is in desiredArgs. Leaving out --url is right (a URL can hold a password). For the others the effect is a run under different settings than the plan was derived under: the default timeouts instead of the ones the reader chose, and, for a reader who passed --ca-cert on the command line, the URL's own sslmode instead of the flag's verification (the flag's help text says it overrides the URL's sslmode). Whether that is weaker depends on the URL, and I did not trace a connection through it. The docs sentence "with the file and schema flags you passed" (cli.md#L507-L512) is accurate; adding "not the connection flags, which you pass again" would tell the reader what the line leaves for them to supply.

Verified

  • Ran only anchored unit tests with a timeout, after reading their bodies (all pure: writeDiffText and saferSequenceDetail on in-memory reports, no sql.Open, container or DSN): TestDiffTextApplyPinsTheFingerprint, TestDiffTextApplyNamesTheDestructiveAcknowledgement, TestWriteDesiredPreviewPointsAtTheRun, TestSaferSequenceDetailCountsSteps, TestDiffTextRefusedStatementDropsApply and the two TestDiffTextGreenfieldRefused* tests. All pass at 8ad31f2. I ran no integration or live-database test.
  • Mutation table (each change applied alone, the named test run, then git checkout):
Mutant (production change) Caught by
M1 --expect-fingerprint not appended to the command TestDiffTextApplyPinsTheFingerprint
M2 shellWord returns its argument unquoted TestDiffTextApplyPinsTheFingerprint (the my schema/orders.sql case)
M3 destructive acknowledgement prose disabled TestDiffTextApplyNamesTheDestructiveAcknowledgement
M4 --foreign-key-schema never added TestDiffTextApplyPinsTheFingerprint
M5 the migrate --desired --dry-run preview passes dryRun: false TestWriteDesiredPreviewPointsAtTheRun
M6 refused == 0 removed from the apply guard survived TestDiffTextRefusedStatementDropsApply and both TestDiffTextGreenfieldRefused* tests; killed by the first test case above
M7 saferSequenceDetail says "its 1 step" for two steps TestSaferSequenceDetailCountsSteps

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

Read the change from two seats: a first-time operator who runs diff or migrate --desired --dry-run and follows the last line, and an importer or CI job that reads the report. The change fits the CLI's shape: the old pointer sent a desired-file reader to migrate --alter, which takes a statement and not a file, so the first thing a new user did after the review was run a different operation than the one reviewed. The new pointer names the same file, schema and pin, so review and run are the same plan, and the acknowledgement flags stay in prose so the pointer never decides a drop or a route on the reader's behalf. The dry-run: label (and nothing was executed under it) now says which command produced the report, so a reader who ran the dry run does not read "diff" in the output. The JSON report and the --sql script are untouched, so an importer that parses either sees no change; only the text rendering moves.

Non-blocking

  1. The docs example shows a relative --desired path, but the command prints an absolute one. --desired is an existingfile, which kong expands to an absolute path before the report is built (I checked with a throwaway test: schema/orders.sql comes back as <cwd>/schema/orders.sql). The tests pass schema/orders.sql straight into diffFraming, so they never see the absolute form, and the guide's sample output at cli.md#L494-L498 prints the line the same way, next to the apply example at #L517. A reader who compares the guide with a real run sees a long path where the guide shows a short one, and a CI log or PR comment that carries the report shows the runner's directory layout. The absolute path is the safer behaviour (the line runs from any directory), so the fix is to the docs: say in the sentence at #L507-L512 that the file is printed as an absolute path, or show one in the sample.

  2. The quoting is POSIX shell quoting, and the guide does not say so. shellWord single-quotes with '\'' (diff_text.go#L157-L172), which sh, bash and zsh read as one word. PowerShell and cmd.exe read '\'' differently, so a path with an apostrophe or a space would not paste back as the same word there. I did not check which platforms the binary ships for, so this may not matter; if it does, a one-line note in the guide ("quoted for a POSIX shell") would set the expectation, and a path with no unsafe character (the common case) prints bare and works anywhere.

What reads well for adopters

  • The report is the one place an operator is told what to run next, and it now tells them the command that runs what they just read, with the pin that refuses a plan that changed since the review.
  • Quoting is conservative: the safe set is ASCII letters, digits and _-./:@%+=,, and everything else is quoted, so a path with a space, $ or a quote cannot split or expand when pasted.
  • The prose beside the line names --allow-destructive with the exact table and the copy-and-swap flags without adding them, so a first-time user sees what each acknowledgement is for and has to type it.

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, 5 non-blocking (see the review comment(s) 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