From 4aa0a56b4e6f3eec410078b719c85edcec61e0d4 Mon Sep 17 00:00:00 2001 From: Kiran Muddukrishna Date: Thu, 3 Dec 2026 05:51:12 +0530 Subject: [PATCH 1/2] verdict: name what a stopped run leaves in a typed standing_run field A wrapper that warns about a standing slot or write fence had to parse the refusal's detail sentence. --- docs/cli-output-examples.md | 34 +++++-- docs/schemabot-integration.md | 25 ++++- internal/cli/color_test.go | 1 + internal/cli/docs_test.go | 26 +++++- .../stopped_run_standing_integration_test.go | 92 +++++++++++++++++++ pkg/migrate/copy_swap.go | 7 ++ .../copy_swap_drift_live_integration_test.go | 7 ++ pkg/migrate/copy_swap_standing.go | 32 ++++++- pkg/migrate/copy_swap_test.go | 67 ++++++++++++++ pkg/verdict/standing_run.go | 45 +++++++++ pkg/verdict/standing_run_test.go | 66 +++++++++++++ pkg/verdict/verdict.go | 11 +++ 12 files changed, 401 insertions(+), 12 deletions(-) create mode 100644 internal/cli/stopped_run_standing_integration_test.go create mode 100644 pkg/verdict/standing_run.go create mode 100644 pkg/verdict/standing_run_test.go diff --git a/docs/cli-output-examples.md b/docs/cli-output-examples.md index 2c40c39ac..6922d61bd 100644 --- a/docs/cli-output-examples.md +++ b/docs/cli-output-examples.md @@ -187,7 +187,7 @@ in `detail`. The set is closed and pinned by test (`verdict.Reasons()`). | `destructive-change` | The change discards live data or structure — a dropped column, constraint, index, or `NOT NULL`. `migrate --alter` runs it only when `--allow-destructive` names the table, and a refused statement that drops a column and adds it back carries the `alter-column-type-in-place` guidance; a desired-state plan that drops anything is refused whole until the run pins the reviewed plan with `--expect-fingerprint` and names its table with `--allow-destructive` ([Apply a reviewed drop](cli.md#apply-a-reviewed-drop), [execution model](execution-model.md)). | | `plan-fingerprint-mismatch` | The plan recomputed at execution time does not carry the pinned fingerprint: the plan a reviewer approved is not the plan that would execute, so nothing runs ([execution model](execution-model.md)). Cause `pinned-refused-preview`: the pin is a dry run's refused preview of the plan, which no run executes; pin the plan's own fingerprint, which the detail names. | | `declarative-foreign-key` | The desired-state plan drops a foreign key it does not run. Cause `changed-foreign-key`: the file changes the key under the same name on a partitioned table, where the new key cannot be added in the same statement; declare it under a new name. Cause `column-first-foreign-key`: the plan also retypes a column, or drops one beside an added column that may rewrite the table, so it drops the key before the new one is added; apply the column change on its own first, then the foreign key change. Cause `undeclarable-foreign-key`: a desired file cannot declare the key (one into a schema `ForeignKeySchemas` does not list, or onto its own table through a standalone unique index); the plan still shows the statement, and `migrate --alter` runs it. | -| `copy-and-swap-refused` | The change routes to copy-and-swap and the route's own gates declined it: the run did not open the route (the route is in preview; cause `copy-and-swap-not-enabled`, class `capability-boundary`, raised before the route's preflight runs or anything is written — pass `--copy-and-swap`), a copy-and-swap run stopped on the table keeps any other statement from running (cause `copy-and-swap-run-stopped`, class `environmental` — run the stopped statement again to finish it, with `--block-writes` when it blocked writes, whose verdict then carries `writes_blocked: true`, or, before its cutover, start it over with `--restart SCHEMA.TABLE` or abandon it with `pg-sprite discard SCHEMA.TABLE`), the preflight found a table shape or an environment it cannot run against, or a shadow operation refused mid-run to keep an invariant. A run whose table was changed by hand while it ran or stood stopped cannot go on: its cutover is refused with `cutover-schema-drift` or `cutover-fidelity-drift`, its resume with `resume-source-changed` (class `environmental`), and the `detail` names the shadow, the fence or the replication slot and publication, and the checkpoint row the run leaves, and the `--restart` and `discard` commands past them. The verdict's `cause` carries the route's own refusal token (`copy-and-swap-…` from the gate and the preflight, `shadow-…` from the shadow operations) and `class` its routing class; [refusal-classes.md](refusal-classes.md#copy-and-swap-refused-keyed-on-copyswaprefusalcause) lists every cause. A table refused for its shape also carries `causes`: every shape cause it has, the verdict's `cause` first, each an object with `cause`, `class`, `detail` (naming the triggers, foreign keys, views, publications, or other objects behind it), and `next_step`, so one run reports them all ([example](copy-and-swap.md#what-each-run-needs)); a `migrate --desired` result refused whole for the table's shape carries the same `causes`, and so does its `--dry-run`, which runs the route's preflight against the live table as the run's admission does. A table refused with `copy-and-swap-pk-unsupported` because it has no primary key also carries `"guidance": "add-integer-primary-key"`, and its `detail` links the [steps to add one online](primary-keys.md#add-a-primary-key-online). | +| `copy-and-swap-refused` | The change routes to copy-and-swap and the route's own gates declined it: the run did not open the route (the route is in preview; cause `copy-and-swap-not-enabled`, class `capability-boundary`, raised before the route's preflight runs or anything is written — pass `--copy-and-swap`), a copy-and-swap run stopped on the table keeps any other statement from running (cause `copy-and-swap-run-stopped`, class `environmental` — run the stopped statement again to finish it, with `--block-writes` when it blocked writes, whose verdict then carries `writes_blocked: true`, or, before its cutover, start it over with `--restart SCHEMA.TABLE` or abandon it with `pg-sprite discard SCHEMA.TABLE`), the preflight found a table shape or an environment it cannot run against, or a shadow operation refused mid-run to keep an invariant. A run whose table was changed by hand while it ran or stood stopped cannot go on: its cutover is refused with `cutover-schema-drift` or `cutover-fidelity-drift`, its resume with `resume-source-changed` (class `environmental`), and the `detail` names the shadow, the fence or the replication slot and publication, and the checkpoint row the run leaves, and the `--restart` and `discard` commands past them; the verdict's `standing_run` names the same leftovers typed ([example](#refused-the-table-changed-under-a-stopped-copy-and-swap-run-resume-source-changed--exit-2)). The verdict's `cause` carries the route's own refusal token (`copy-and-swap-…` from the gate and the preflight, `shadow-…` from the shadow operations) and `class` its routing class; [refusal-classes.md](refusal-classes.md#copy-and-swap-refused-keyed-on-copyswaprefusalcause) lists every cause. A table refused for its shape also carries `causes`: every shape cause it has, the verdict's `cause` first, each an object with `cause`, `class`, `detail` (naming the triggers, foreign keys, views, publications, or other objects behind it), and `next_step`, so one run reports them all ([example](copy-and-swap.md#what-each-run-needs)); a `migrate --desired` result refused whole for the table's shape carries the same `causes`, and so does its `--dry-run`, which runs the route's preflight against the live table as the run's admission does. A table refused with `copy-and-swap-pk-unsupported` because it has no primary key also carries `"guidance": "add-integer-primary-key"`, and its `detail` links the [steps to add one online](primary-keys.md#add-a-primary-key-online). | | `create-collision` | The greenfield create plan's table name or a claimed index, constraint-index, or sequence name is occupied. Nothing runs; re-derive the plan against the live catalog to see what holds the name, then drop or rename the occupant, name a constraint's index explicitly, or for a sequence use an explicitly named sequence or a non-serial column — re-planning alone reproduces the refusal. Catalog absence checks handle existing occupants. Duplicate-name SQLSTATEs backstop races for explicit names; for server-chosen names, the probe narrows the race to the time-of-check window, and after the `CREATE TABLE` commits the executor reads the constraint-index and sequence names the table actually owns and compares them against the claimed first-choice names — a name taken inside the window makes the server pick a suffixed replacement, which surfaces as a typed `create-name-mismatch` failure at step 1 with the born table left in place for an operator to rename the relation or drop, then re-diff. | Two codes that look like refusals are not: `create-name-mismatch` and @@ -539,15 +539,33 @@ shadow from the table as it is now, keeping the column added by hand, and `discard` drops what the run left without running the change. A run that was still in progress when the table changed stops at its cutover instead, with cause `cutover-schema-drift`, and its detail adds the same account. A consumer -branches on the `cause` field, not on the detail's wording: +branches on the `cause` field, not on the detail's wording. What the run leaves +is also the verdict's `standing_run`, so a consumer can warn that the slot +retains WAL without parsing the detail: `shadow`, quoted as `DROP TABLE` takes +it; `hold`, `slot` here, or `write-fence` for a run that blocked writes, which +names no `slot` or `publication`; the slot as `pg_replication_slots` names it +and the publication quoted; and the checkpoint row's `phase`. Every refusal +that names what a stopped run leaves carries it, the cutover's drift refusals +included: ```console -$ pg-sprite migrate --alter 'ALTER TABLE orders ALTER COLUMN user_id TYPE bigint' --copy-and-swap --free-disk 10GiB -refused (copy-and-swap-refused) - table: public.orders - class: environmental - statement: ALTER TABLE public.orders ALTER COLUMN user_id TYPE bigint - detail: public.orders changed since this run built its shadow (for example a column or index added by hand); the stopped run cannot resume, and it leaves shadow table public._pgsprite_c74da4a21f58f903_new, replication slot pgsprite_a725d037, which retains WAL on the server until it is dropped, publication pgsprite_a725d037, and the checkpoint row in phase verifying; start over by running the same pg-sprite migrate command with --restart public.orders, or abandon the run without running the change with pg-sprite discard public.orders +$ pg-sprite migrate --alter 'ALTER TABLE orders ALTER COLUMN user_id TYPE bigint' --copy-and-swap --free-disk 10GiB --json +{ + "outcome": "refused", + "reason": "copy-and-swap-refused", + "class": "environmental", + "cause": "resume-source-changed", + "statement": "ALTER TABLE public.orders ALTER COLUMN user_id TYPE bigint", + "table": "public.orders", + "detail": "public.orders changed since this run built its shadow (for example a column or index added by hand); the stopped run cannot resume, and it leaves shadow table public._pgsprite_c74da4a21f58f903_new, replication slot pgsprite_a725d037, which retains WAL on the server until it is dropped, publication pgsprite_a725d037, and the checkpoint row in phase verifying; start over by running the same pg-sprite migrate command with --restart public.orders, or abandon the run without running the change with pg-sprite discard public.orders", + "standing_run": { + "shadow": "\"public\".\"_pgsprite_c74da4a21f58f903_new\"", + "hold": "slot", + "slot": "pgsprite_a725d037", + "publication": "\"pgsprite_a725d037\"", + "phase": "verifying" + } +} ``` ### Refused: a stopped run of the other mode (`copy-and-swap-refused`) — exit 2 diff --git a/docs/schemabot-integration.md b/docs/schemabot-integration.md index e6474f433..4d905d5ae 100644 --- a/docs/schemabot-integration.md +++ b/docs/schemabot-integration.md @@ -647,9 +647,32 @@ backend ends in exactly one of four verdicts: | --- | --- | --- | | `outcome: executed-via-copy-and-swap` | The shadow was built, filled, verified, and swapped in under the source's name; `detail` says how many rows and chunks the verification pass covered, whether the retained source was dropped or kept under its `_old` name — when kept, the name and the `DROP TABLE` that ends the rollback window — whether the run first reconciled a lost slot, and — for a run that blocked writes (`--block-writes`) — that the source's writes were fenced for the run's length, since exit 0 otherwise reads as online-safe; `writes_blocked: true` says the same for a machine, on this outcome and on a failed run whose fence went on: one whose fence the catalog shows still standing after the stop, or that was abandoned after the fence went on. A blocked-writes run that stopped before its fence went on reports `false`, since the table kept taking writes; its detail says so and that running the statement again starts from the beginning, or, for a run refused at a table lock another session holds (`table-lock-held`), that it created nothing and which holder to wait for. One refused at a table lock another session holds reports `false` whatever that session left on the table, since this run placed no fence and saved no row; its detail says so. So does a stopped run whose checkpoint row remains with no fence standing on the table — dropped and created again, or its fence dropped or disabled by hand — whose detail says the table takes writes until the run is resumed. A fence that stands with no row behind it (its row deleted by hand, or a fresh run's row that never landed) reports `true`. When the catalog read after the stop fails, the fence is reported and the read's error is joined to the run's; that joined error, matched by neither a sentinel nor a type, is the only marker of a fence reported but not confirmed, so an adapter that must tell the two apart calls `schemachange.WriteFenceStands` itself. A run whose done row is saved is this outcome even when what came after failed — `OnCheckpoint` handed the done row, or the release of the lock session; the detail then names that error. `swap_lsn` is the server's WAL position, as `pg_lsn` text, read inside the swap transaction under its lock right before it committed: a write to the table that committed below it is in the retained source and was carried over, and writes after it exist only in the new table. It is absent when the run did not hear its own swap commit — a run resumed after the swap, or one that learned of the commit from the catalog after losing its connection. `verification` carries the verification pass's figures — `rows`, `chunks`, `settled`, `unsettled`, and `carried` (`detail` states only the first three), the number of keys the live pass left for the swap to compare under its lock (a count, never the keys), every figure present, zero included — so an adapter records them without parsing prose; it is absent when the pass compared no chunk: a run resumed after its swap, or an empty table, and from a pg-sprite build older than the object, so an adapter that must tell those apart records the binary's version beside the verdict. `retained_table` is the kept retained source's name, schema-qualified with every identifier quoted, as `DROP TABLE` takes it (for example `"public"."_pgsprite_c74da4a21f58f903_old"`) — a quoted SQL identifier pair, not the plain `schema.name` form of `table`, so an adapter that binds or looks the name up unquotes it first, or derives it from `table` the way `schemachange.OldName` does —, so an adapter can end the rollback window without parsing `detail`; it is absent when the run dropped the retained source. On this outcome a non-zero `unsettled` or `carried` is a record, not a warning: the swap compared those keys under its lock and would have refused had any differed. `statistics_refresh` reports the `ANALYZE` the run made of the shadow before the swap, so the swapped-in table has planner statistics the moment it commits, in the same shape as the native type change's refresh: `columns` the statement retyped (an empty list when none), `refreshed`, and `pending`, the `ANALYZE` still to run, when it could not run within its budgets, which stops neither the run nor the swap, to be run as the table's owner; a run that only finished an earlier run's swap reports `pending` when the swapped-in table has never been analyzed and leaves the field out otherwise, so an absent `statistics_refresh` says nothing about the table's statistics, and `statistics_refresh`, not the end of `detail`, is the stable way to read it. The error is nil | Done. Exit 0 at the CLI; the outcome token is distinct from `executed-natively` so an adapter can tell the two paths apart in its record | | `outcome: refused`, `reason: backend-unavailable` | The plan routes an operation to copy-and-swap that the engine does not carry yet; nothing executed. With `cause: add-column-probe-locked` (`class: environmental`), every operation routed there is an `ADD COLUMN` whose catalog-only proof met another session's lock, from `migrate.Run` and `migrate.RunDesired` alike; a desired plan carries the cause only when every statement it refuses is such an add, since a retry would meet any other refusal again. The error is nil | With the cause, plan and run the same statement or file again once the lock is released, with a bounded backoff; without it, planning again refuses the same way, so route it to the operator | -| `outcome: refused`, `reason: copy-and-swap-refused` | The route's own gates declined: the run did not open the route (`cause: copy-and-swap-not-enabled`, `class: capability-boundary` — the route is in preview and runs only when `CopySwap.Enabled` is set; raised before the route's preflight runs or anything is written, after target resolution and planning have read the catalog), the preflight found a table shape or an environment it will not run against, or a shadow operation refused mid-run to keep an invariant. `cause` is the route's token unchanged — a `copy-and-swap-…` cause from the gate or the preflight, a `shadow-…`, `cutover-…`, `resume-…`, or `copy-…` cause from the shadow operations — and `class` is its routing class. A `migrate.Run` shape refusal also carries `causes`, every shape cause the table has with its own `class`, `detail`, and `next_step`, the verdict's `cause` first. `cause` and `class` are the verdict's routing authority; `causes` is for showing each cause, and a shape refusal's class is environmental only when its replica identity is its one cause. A `migrate.Run` live run follows them with the environment causes a read-only preview finds without the shape proof (logical decoding, a slot collision, slot or WAL sender headroom), each with `advisory: true`, which decided nothing: the environment check runs once the shape passes. A consumer that loops over `causes` skips the advisory ones or shows them as a heads-up, not as more reasons the table is refused. A `migrate.RunDesired` result refused for the table's shape carries the same list on `DesiredResult.Causes` (`causes` in the JSON), whether the plan was refused whole at admission or a statement was refused at its own preflight during execution, where its entry of `Verdicts` carries the list too; the field is absent on every other result. Desired-state execution always runs live, so the list carries the same advisory causes after the shape causes, in a plan refused whole at admission (and its dry run, `migrate.AdmitPlanCopySwapPreflight`) as at execution. Branch on the typed `cause` and `causes`, not on `detail`, whose text a release may extend. The error is nil | Route on `cause` with the two tables above and [refusal-classes.md](refusal-classes.md#copy-and-swap-refused-keyed-on-copyswaprefusalcause). The not-enabled refusal and a preflight refusal touched nothing. A refusal raised after the row was saved — a `cutover-…` or `resume-…` cause — leaves the row, the shadow, and the run's hold on the source in place: the write fence of a run that blocked writes, or the replication slot of a live run, which pins WAL until it is dropped; the cause says whether the next run clears it or the run is abandoned first. A `migrate.Run` verdict refused `copy-and-swap-pk-unsupported` for a table with no primary key carries `guidance` `add-integer-primary-key`, the online key addition after which the change runs again and meets the table's other shape checks; render it beside `cause` and `detail`. `migrate.RunDesired` carries the same cause and class and no `guidance`. A missing privilege is not this reason: it is the same `insufficient-privileges` refusal the native route reports, with the exact `GRANT` in `detail` | +| `outcome: refused`, `reason: copy-and-swap-refused` | The route's own gates declined: the run did not open the route (`cause: copy-and-swap-not-enabled`, `class: capability-boundary` — the route is in preview and runs only when `CopySwap.Enabled` is set; raised before the route's preflight runs or anything is written, after target resolution and planning have read the catalog), the preflight found a table shape or an environment it will not run against, or a shadow operation refused mid-run to keep an invariant. `cause` is the route's token unchanged — a `copy-and-swap-…` cause from the gate or the preflight, a `shadow-…`, `cutover-…`, `resume-…`, or `copy-…` cause from the shadow operations — and `class` is its routing class. A `migrate.Run` shape refusal also carries `causes`, every shape cause the table has with its own `class`, `detail`, and `next_step`, the verdict's `cause` first. `cause` and `class` are the verdict's routing authority; `causes` is for showing each cause, and a shape refusal's class is environmental only when its replica identity is its one cause. A `migrate.Run` live run follows them with the environment causes a read-only preview finds without the shape proof (logical decoding, a slot collision, slot or WAL sender headroom), each with `advisory: true`, which decided nothing: the environment check runs once the shape passes. A consumer that loops over `causes` skips the advisory ones or shows them as a heads-up, not as more reasons the table is refused. A `migrate.RunDesired` result refused for the table's shape carries the same list on `DesiredResult.Causes` (`causes` in the JSON), whether the plan was refused whole at admission or a statement was refused at its own preflight during execution, where its entry of `Verdicts` carries the list too; the field is absent on every other result. Desired-state execution always runs live, so the list carries the same advisory causes after the shape causes, in a plan refused whole at admission (and its dry run, `migrate.AdmitPlanCopySwapPreflight`) as at execution. Branch on the typed `cause` and `causes`, not on `detail`, whose text a release may extend. The error is nil | Route on `cause` with the two tables above and [refusal-classes.md](refusal-classes.md#copy-and-swap-refused-keyed-on-copyswaprefusalcause). The not-enabled refusal and a preflight refusal touched nothing. A refusal raised after the row was saved — a `cutover-…` or `resume-…` cause — leaves the row, the shadow, and the run's hold on the source in place: the write fence of a run that blocked writes, or the replication slot of a live run, which pins WAL until it is dropped; the cause says whether the next run clears it or the run is abandoned first. When the refusal names what the run leaves, the verdict carries it typed as `standing_run`, which the paragraph after this table describes. A `migrate.Run` verdict refused `copy-and-swap-pk-unsupported` for a table with no primary key carries `guidance` `add-integer-primary-key`, the online key addition after which the change runs again and meets the table's other shape checks; render it beside `cause` and `detail`. `migrate.RunDesired` carries the same cause and class and no `guidance`. A missing privilege is not this reason: it is the same `insufficient-privileges` refusal the native route reports, with the exact `GRANT` in `detail` | | `outcome: failed`, with `code` | The run stopped on an error that is not a refusal; the error is returned alongside the verdict. `code` is `cancelled-by-caller` when the caller's context ended — whatever cause the caller cancelled it with: the code says only that the context ended, so an adapter that cancels with reasons of its own (a lost lease, a failed health gate) tells them apart with `errors.Is(err, )` on the returned error, `invariant-violation` when the engine caught a breach of its own contract, `data-fault` when the server rejected the rows as the statement would shape them — a `*pgconn.PgError` in SQLSTATE class `22` or `23`: a value the new type will not hold, a constraint the copied rows break — `pool-too-small` when the pool holds fewer than `migrate.CopySwapMinConns(Copier)` connections — refused before the preflight with nothing created, the error matching `errors.Is(err, executor.ErrPoolTooSmall)`; resize the pool rather than retry — `table-lock-unconfirmed` when the table lock session runs as a role that cannot read when its own session started (the connection logs in as one role and runs as another, through the `role` connection parameter or `SET ROLE`) — refused before the lock is taken with nothing created or saved, the error matching `errors.Is(err, dbconn.ErrSessionStartHidden)`; a pool whose sessions switch role the same way is refused with the same code and error before the preflight, since the swap runs on the pool and identifies its own session by its start; it is permanent, so connect as the role directly, or grant it `pg_read_all_stats`, which also lets it read every session's query text and statistics across the cluster, rather than retry — `table-lock-held` when another session holds the table's lock (a run in progress, a discard, a partitioned build, or a row security change on the table) — refused at once, after the preflight and before the lock is taken, with nothing created or saved, the error matching `*dbconn.TableLockHeldError` naming the holder; it is not permanent, so retry once the holder has ended; a working transaction that sees the lock held by another backend after the run took its own is `invariant-violation`, never this code; a caller's context that ends while the refusal reads the holder makes the same error `cancelled-by-caller` here, while `executor.OutcomeCode`, which the row security and partitioned verdicts use, reports it as `table-lock-held`, so an adapter that retries on the code checks `errors.Is(err, context.Canceled)` first — `slot-lag-exceeded` when a live run's slot crossed its lag ceiling (a `*decode.SlotLagExceededError`), with `cause` naming the measure that crossed it, the same token as the error's `Cause`: `stream-behind`, `wal-retained`, or `wal-retained-hard-limit`, and with `slot_lag` (`Verdict.SlotLag`) carrying the error's figures — `slot`, `retained_bytes`, `unconfirmed_bytes`, `ceiling_bytes` — with `suggested_ceiling_bytes`, the ceiling to resume under (twice the retained WAL, never below twice the ceiling, rounded up to a power of two and held at 2^62, so store it as a signed 64-bit integer), and `resumable`, which is `true` on every slot lag stop today since the stop always keeps the checkpoint row and the slot — `budget-lock-exceeded` when a reader or writer held the table through every cutover attempt's wait outside the lock queue, for the run's whole lock budget (`CutoverLockAttempts` and `LockTimeout`), so the swap never requested its lock and nothing was swapped: the error carries the `*executor.LingeringHolderError` naming the holder, inside a `*schemachange.LockRetriesExhaustedError` once the swap's attempts ran out, whose `Attempts` the verdict's `attempts` carries (absent on a live run that stopped in its wait before the cutover, which made no attempt; only a live run waits there, so a `--block-writes` run stopped at the cutover always spent its attempts, and an `attempts` absent from its verdict means a binary that predates the field), and `lock_holder` names that session: `pid`, `table`, `held_ns`, and, when the connected role can see the session, `state`, `application_name`, `transaction_age_ns`, and `query_age_ns` — and `execution-failed` for everything else — a divergence, an unsettled chunk, a rolled-back swap, a lost lock session, lock retries whose last attempt ended on the server's lock timeout or its deadlock refusal (which carry `attempts` too; a verdict whose code outranks the spent cutover, such as `slot-lag-exceeded`, does not), a step outside the cutover — the shadow build, the write fence, a copy, verification, or flush transaction, the old-table drop — that waited out `LockTimeout` (the server's `55P03` in the returned error). A consumer that meets a `code` it does not know treats the stop as one an operator reads by hand. The cancellation, the breach, the data fault, and a divergence each outrank a slot lag stop the same error carries alongside; `cause` is set only under `slot-lag-exceeded`. `slot-lag-exceeded` is not permanent, yet a `stream-behind` stop is refused at its resume (`resume-slot-backlog`) until the ceiling is raised, so route its retry on `cause` ([execution-model](execution-model.md#outcome-codes)) | `detail` says what the stop left and what to do with it. A data fault would stop the same way on every resume, so the Runner abandons the run itself before returning (`*schemachange.AbandonedError`): the shadow is dropped, the fence is taken off the source or the slot is dropped, and the checkpoint row is deleted — nothing is held; the verdict says so with `abandoned: true`; correct the data or the statement, then run it again without any acknowledgement, and the run starts from the beginning. Every other stop leaves the checkpoint row at its last save with the run's hold on the source — the fence or the slot: a divergence (`*checksum.DivergenceError`) is wedged in `verifying`, and a data fault whose abandon itself failed (the same `code: data-fault` with `abandoned` unset; the detail says the run "could not be abandoned") is held the same way; for both the detail says to correct the data or the statement and then start the run over with the restart acknowledgement (`--restart SCHEMA.TABLE`; `CopySwapOptions.Restart`), which drops the shadow, takes the fence off the source or drops the slot, deletes the row, and runs the change from the start, or to abandon the run with `pg-sprite discard SCHEMA.TABLE` (`Runner.Discard`), which drops the same things and does not run the change. A `stream-behind` slot lag stop names the same discard beside raising the ceiling. A run refused under `table-lock-held` says that it created and changed nothing and names the holder's backend to wait for. Any other stop says that running the same statement again resumes from the row. The detail is written for the CLI operator and names CLI flags (`--restart SCHEMA.TABLE`, `--slot-lag-ceiling SIZE`), so an adapter that shows its own users a remedy builds it from the returned error, such as `*decode.SlotLagExceededError` and its `Cause`, rather than relaying `detail`; a wrapper of the CLI's `--json`, which has no error to match, routes a slot lag stop on `code: slot-lag-exceeded` and its `cause`, and resumes it under `slot_lag.suggested_ceiling_bytes`. A slot lag stop's `detail` is several lines, the first saying what stopped the run; a host that renders verdicts as text lines the later lines up under the label with `verdict.IndentDetail`, as the CLI does, and a host that shows one line takes the first. The `Run` outcome table above is the finer map. Match the wrapped error with `errors.Is`/`errors.As` for the finer routing — the verdict's `code` is the coarse class | +A `copy-and-swap-refused` verdict whose refusal stopped a run, or refused its resume, with +its checkpoint row standing names what that run leaves in `standing_run`, the typed twin of +the leftovers `detail` names, so a wrapper of `--json` can warn that a replication slot +retains WAL, or that the source refuses writes, without parsing prose. Every verdict whose +cause is `cutover-schema-drift`, `cutover-fidelity-drift`, `copy-conversion-drift`, +`resume-source-changed`, `resume-slot-held`, or `resume-slot-backlog` carries it, and so does +a `resume-row-mismatch` whose row describes the shadow under the derived name: exactly the +refusals that wrap a `*schemachange.StandingRunError`, from which a Go adapter reads the same +facts with `errors.As`. Its keys are `shadow`, the shadow table schema-qualified with every +identifier quoted, as `DROP TABLE` takes it; `hold`, `slot` for a live run's replication slot +and publication or `write-fence` for the fence of a run that blocked writes; `slot`, the +slot's name as `pg_replication_slots` shows it, and `publication`, quoted as `DROP +PUBLICATION` takes it, both present only under `hold: slot`; and `phase`, the checkpoint row's +phase, spelled as `pg-sprite discard --json` spells its `row_phase` (for example `verifying`). Whether the fence is still +enabled in the catalog is `writes_blocked`, not `hold`. The `cause` says whether the run can +resume once it is acted on or must be started over (`--restart SCHEMA.TABLE`) or discarded +(`pg-sprite discard SCHEMA.TABLE`), which drop all of it. `standing_run` is absent on every +other verdict, including a `resume-row-mismatch` whose row is not this table's run, a +`resume-slot-foreign` slot, and `resume-shadow-gone`, whose shadow is gone though its row and +hold still stand, so read that refusal by its cause. The verdict has no format version of its +own: a pg-sprite build older than the field never writes it, so an adapter that must tell "no +run stands" from "not reported" records the binary's version beside the verdict. + The adapter supplies the route's policy on `migrate.Options.CopySwap`: `Enabled`, which opens the route for the run (the route is in preview; the zero value keeps it closed, so an adapter that has not decided to run copy-and-swap gets the `copy-and-swap-not-enabled` refusal for diff --git a/internal/cli/color_test.go b/internal/cli/color_test.go index 484415e66..c3988cf5e 100644 --- a/internal/cli/color_test.go +++ b/internal/cli/color_test.go @@ -212,6 +212,7 @@ func fullVerdict(t *testing.T) verdict.Verdict { IndexUsage: &verdict.IndexUsage{IdxScans: 7, Unique: true, TrackCounts: true}, LockHolder: &verdict.LockHolder{PID: 4123, Table: "public.t", Held: 3 * time.Second}, PartitionedIndexFault: &verdict.PartitionedIndexFault{Index: `"public"."t_uq_p16397"`, Partition: `"public"."t_2026_02"`, Resumable: true}, + StandingRun: &verdict.StandingRun{Shadow: `"public"."_pgsprite_0000000000000000_new"`, Hold: verdict.StandingHoldSlot, Slot: "pgsprite_x", Publication: `"pgsprite_x"`, Phase: "verifying"}, RefusedStatements: []verdict.RefusedStatement{ {Statement: 2, Line: 6, Column: 1, Detail: "statement kind not allowed in a desired schema: COMMENT ON TABLE t IS 'x'"}, {Statement: 3, Line: 8, Column: 3, Detail: "statement kind not allowed in a desired schema: CREATE FUNCTION f() ..."}, diff --git a/internal/cli/docs_test.go b/internal/cli/docs_test.go index 09acd3d2d..10c92aee5 100644 --- a/internal/cli/docs_test.go +++ b/internal/cli/docs_test.go @@ -77,7 +77,7 @@ func TestCLIOutputExamplesMatchPipelineOutput(t *testing.T) { raw, err := os.ReadFile(cliOutputExamplesDoc) require.NoError(t, err) blocks := regexp.MustCompile("(?s)```console\n\\$ pg-sprite [^\n]*--json\n(.*?)```").FindAllStringSubmatch(string(raw), -1) - require.Len(t, blocks, 25, "the doc publishes twenty-five captured --json outputs") + require.Len(t, blocks, 26, "the doc publishes twenty-six captured --json outputs") // A live plan proves the added column against the server; a nullable // column with no default is added in place, so the plan marks it @@ -169,6 +169,28 @@ func TestCLIOutputExamplesMatchPipelineOutput(t *testing.T) { Resumable: true, }, } + // The changed-source refusal is a live run's, stopped in verifying and + // then met by a column added by hand; its detail is the migrate + // package's rendering of what the run leaves, and standing_run the + // same leftovers typed, which TestMigrateJSONNamesTheSlotAStoppedLiveRunLeaves + // reads from a real run. + sourceChanged := verdict.Verdict{ + Statement: "ALTER TABLE public.orders ALTER COLUMN user_id TYPE bigint", + Table: "public.orders", + Detail: "public.orders changed since this run built its shadow (for example a column or index added by hand); " + + "the stopped run cannot resume, and it leaves shadow table public." + schemachange.ShadowName("public", "orders") + ", " + + "replication slot pgsprite_a725d037, which retains WAL on the server until it is dropped, publication pgsprite_a725d037, " + + "and the checkpoint row in phase verifying; " + + "start over by running the same pg-sprite migrate command with --restart public.orders, " + + "or abandon the run without running the change with pg-sprite discard public.orders", + StandingRun: &verdict.StandingRun{ + Shadow: `"public"."` + schemachange.ShadowName("public", "orders") + `"`, + Hold: verdict.StandingHoldSlot, + Slot: "pgsprite_a725d037", + Publication: `"pgsprite_a725d037"`, + Phase: "verifying", + }, + }.WithRefusal(verdict.Environmental(verdict.ReasonCopyAndSwapRefused).WithCause(verdict.Cause(schemachange.CauseResumeSourceChanged))) // The mode-mismatch verdict is captured from a run: a --block-writes // retype of orders stopped mid-copy, then run again without the flag. // Its detail is the migrate package's rendering of the refusal, which @@ -344,7 +366,7 @@ func TestCLIOutputExamplesMatchPipelineOutput(t *testing.T) { tunedRefused, ok := migrate.DesiredFileRefusal(tunedErr, accounts.Statements()[0].SQL()) require.True(t, ok, "a storage parameter difference is a desired-file refusal: %v", tunedErr) - want := []any{metadataOnly, saferIdiom, executed, acceptedBlocking, failedSequence, dataFault, partitionedDataFault, modeMismatch, cutoverHolder, rewriteRequired, + want := []any{metadataOnly, saferIdiom, executed, acceptedBlocking, failedSequence, dataFault, partitionedDataFault, sourceChanged, modeMismatch, cutoverHolder, rewriteRequired, copyAndSwapRouted, executedViaCopyAndSwap, executedKeepingOld, backendUnavailable, partitionedBuild, partitionedBuilt, partitioned, destructiveRefused, destructive, dropNote, lintReport, partitionsRefused, diff, typeFileRefused, tunedRefused} for i, w := range want { diff --git a/internal/cli/stopped_run_standing_integration_test.go b/internal/cli/stopped_run_standing_integration_test.go new file mode 100644 index 000000000..ac9c535bf --- /dev/null +++ b/internal/cli/stopped_run_standing_integration_test.go @@ -0,0 +1,92 @@ +package cli + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/block/pg-sprite/internal/testutil" + "github.com/block/pg-sprite/pkg/checkpoint" + "github.com/block/pg-sprite/pkg/schemachange" + "github.com/block/pg-sprite/pkg/verdict" +) + +// The tests here stop a copy-and-swap run of +// +// ALTER TABLE orders ALTER COLUMN qty TYPE bigint +// +// in verifying, add a column to orders by hand, +// +// ALTER TABLE orders ADD COLUMN gift_note text +// +// and run the same migrate --json again. The shadow was built before the +// column existed, so the resume is refused as resume-source-changed, and +// the verdict's standing_run names what the stopped run leaves for a +// wrapper of --json to warn on: the shadow, the hold on the source, and +// the row's phase, read against the row the run left. + +// refuseResumeOverAddedColumn adds gift_note to the fixture's orders by +// hand and runs the stopped retype again through migrate --json, returning +// the refused verdict. +func refuseResumeOverAddedColumn(t *testing.T, f discardFixture, blockWrites bool) verdict.Verdict { + t.Helper() + f.exec(t, ` + ALTER TABLE %s.orders + ADD COLUMN gift_note text`) + cmd := f.migrateCmd(blockWrites) + cmd.JSON = true + var out strings.Builder + require.ErrorIs(t, cmd.run(t.Context(), &out), verdict.ErrRefused, out.String()) + var v verdict.Verdict + require.NoError(t, json.Unmarshal([]byte(out.String()), &v), out.String()) + assert.Equal(t, verdict.OutcomeRefused, v.Outcome, v.Detail) + assert.Equal(t, verdict.ReasonCopyAndSwapRefused, v.Reason) + assert.Equal(t, verdict.Cause(schemachange.CauseResumeSourceChanged), v.Cause, v.Detail) + return v +} + +// A live run holds a replication slot, which retains WAL on the server +// until a restart or a discard drops it; standing_run names that slot and +// its publication, and the refusal left both standing. +func TestMigrateJSONNamesTheSlotAStoppedLiveRunLeaves(t *testing.T) { + f := newDiscardFixture(t, testutil.StartPostgresWithSettings(t, "wal_level=logical", "wal_sender_timeout=2s")) + stopped := f.stopRetypeAt(t, checkpoint.PhaseVerifying, false) + require.NotEmpty(t, stopped.SlotName, "a live run names its slot") + + v := refuseResumeOverAddedColumn(t, f, false) + assert.Equal(t, &verdict.StandingRun{ + Shadow: pgx.Identifier{f.schema, stopped.ShadowTable}.Sanitize(), + Hold: verdict.StandingHoldSlot, + Slot: stopped.SlotName, + Publication: pgx.Identifier{stopped.PublicationName}.Sanitize(), + Phase: "verifying", + }, v.StandingRun) + assert.False(t, v.WritesBlocked, "a live run places no write fence") + assert.True(t, slotPresent(t, f.pool, stopped.SlotName), "the refusal left the stopped run's slot") + assert.True(t, publicationPresent(t, f.pool, stopped.PublicationName), "the refusal left the stopped run's publication") +} + +// A run that blocked writes holds the write fence instead, which refuses +// every write to orders; standing_run names the fence and no slot, and +// writes_blocked says the catalog shows the fence still standing. +func TestMigrateJSONNamesTheWriteFenceAStoppedBlockedWritesRunLeaves(t *testing.T) { + f := newDiscardFixture(t, testutil.StartPostgres(t)) + stopped := f.stopRetypeAt(t, checkpoint.PhaseVerifying, true) + require.Empty(t, stopped.SlotName, "a run that blocked writes holds no slot") + + v := refuseResumeOverAddedColumn(t, f, true) + assert.Equal(t, &verdict.StandingRun{ + Shadow: pgx.Identifier{f.schema, stopped.ShadowTable}.Sanitize(), + Hold: verdict.StandingHoldWriteFence, + Phase: "verifying", + }, v.StandingRun) + assert.True(t, v.WritesBlocked, "the stopped run's fence still stands") + var fenced *pgconn.PgError + require.ErrorAs(t, f.insertOrder(t, 1001), &fenced, "the refusal left the write fence on orders") + assert.Equal(t, "55006", fenced.Code) +} diff --git a/pkg/migrate/copy_swap.go b/pkg/migrate/copy_swap.go index 5bccd71d7..574ce40ae 100644 --- a/pkg/migrate/copy_swap.go +++ b/pkg/migrate/copy_swap.go @@ -681,6 +681,13 @@ func copySwapRunVerdict(st statement.Statement, hold sourceHold, err error) (ver return modeMismatchVerdict(st, r, hold, true, 0), nil } v := refusedVerdict(st, r, err.Error()) + if standing, ok := errors.AsType[*schemachange.StandingRunError](err); ok { + field, fieldErr := standingRunField(standing) + if fieldErr != nil { + return verdict.Verdict{}, fieldErr + } + v.StandingRun = field + } switch cause { case schemachange.CauseResumeSlotBacklog: // The CLI operator acts on the flags, so the detail is built diff --git a/pkg/migrate/copy_swap_drift_live_integration_test.go b/pkg/migrate/copy_swap_drift_live_integration_test.go index fc670853a..5830c2c48 100644 --- a/pkg/migrate/copy_swap_drift_live_integration_test.go +++ b/pkg/migrate/copy_swap_drift_live_integration_test.go @@ -79,6 +79,13 @@ func TestRunCopySwapCutoverDriftNamesWhatTheLiveRunLeaves(t *testing.T) { assert.Contains(t, v.Detail, "--restart "+table) assert.Contains(t, v.Detail, "pg-sprite discard "+table) assert.NotContains(t, v.Detail, "RunOptions", "the detail names the CLI's commands, not the library's options") + assert.Equal(t, &verdict.StandingRun{ + Shadow: pgx.Identifier{f.table.Schema, schemachange.ShadowName(f.table.Schema, f.table.Table)}.Sanitize(), + Hold: verdict.StandingHoldSlot, + Slot: row.SlotName, + Publication: pgx.Identifier{row.PublicationName}.Sanitize(), + Phase: "verifying", + }, v.StandingRun, "the verdict names what the stopped run leaves, typed") assert.True(t, f.slotExists(t, row.SlotName), "the stopped run's slot stands") restart := f.options() diff --git a/pkg/migrate/copy_swap_standing.go b/pkg/migrate/copy_swap_standing.go index 926cfa383..6e0795d43 100644 --- a/pkg/migrate/copy_swap_standing.go +++ b/pkg/migrate/copy_swap_standing.go @@ -5,7 +5,11 @@ import ( "fmt" "strings" + "github.com/jackc/pgx/v5" + + "github.com/block/pg-sprite/pkg/executor" "github.com/block/pg-sprite/pkg/schemachange" + "github.com/block/pg-sprite/pkg/verdict" ) // This file is the CLI operator's account of a copy-and-swap run a refusal @@ -14,7 +18,33 @@ import ( // what stands on a *schemachange.StandingRunError beside its refusal, with // its own remedy in the library's option names; the verdict detail names // the CLI's commands instead, as copySwapStoppedRemedy's does, and a -// library host routes on the verdict's cause. +// library host routes on the verdict's cause. The verdict's StandingRun +// carries the same leftovers typed, for a host that reads --json. + +// standingRunField is the verdict's typed record of what a stopped run +// leaves, the same leftovers standing.Leftovers names in the detail. A hold +// of a kind this package does not know is a broken contract with the +// library, not a verdict. +func standingRunField(standing *schemachange.StandingRunError) (*verdict.StandingRun, error) { + field := &verdict.StandingRun{ + Shadow: pgx.Identifier{standing.Schema, standing.Shadow}.Sanitize(), + Phase: standing.Phase.String(), + } + switch standing.Hold { + case schemachange.HoldReplicationSlot: + field.Hold = verdict.StandingHoldSlot + field.Slot = standing.Slot + if standing.Publication != "" { + field.Publication = pgx.Identifier{standing.Publication}.Sanitize() + } + case schemachange.HoldWriteFence: + field.Hold = verdict.StandingHoldWriteFence + default: + return nil, fmt.Errorf("%w: stopped run on %s.%s names a hold of unknown kind %q", + executor.ErrInvariantViolation, standing.Schema, standing.Table, standing.Hold) + } + return field, nil +} // sourceChangedDetail is the detail of a resume refused as // resume-source-changed: the table was changed since the stopped run diff --git a/pkg/migrate/copy_swap_test.go b/pkg/migrate/copy_swap_test.go index d97d18cf0..0aac61c7a 100644 --- a/pkg/migrate/copy_swap_test.go +++ b/pkg/migrate/copy_swap_test.go @@ -672,6 +672,73 @@ func TestCopySwapRunVerdict(t *testing.T) { assert.Contains(t, v.Detail, refused.Error()+"; the stop also met: save checkpoint row: connection reset; the run stopped and leaves shadow table") }) + // What the stopped run leaves rides on the verdict typed as well as in + // the detail, so a host that reads --json can warn that a slot retains + // WAL without parsing prose. A live run's slot is named as + // pg_replication_slots names it and its publication quoted, as DROP + // PUBLICATION takes it. + liveStandingRun := &verdict.StandingRun{ + Shadow: `"public"."_pgsprite_c200_new"`, + Hold: verdict.StandingHoldSlot, + Slot: "pgsprite_c200", + Publication: `"pgsprite_c200"`, + Phase: "verifying", + } + t.Run("a resume refused on a held slot carries the slot and publication it leaves", func(t *testing.T) { + refused := &schemachange.RefusalError{Cause: schemachange.CauseResumeSlotHeld, Detail: "slot pgsprite_c200 is held by backend 4123"} + v, err := copySwapRunVerdict(st, holdSlot, fmt.Errorf("run: %w; %w", refused, liveStanding)) + require.NoError(t, err) + assert.Equal(t, verdict.Cause(schemachange.CauseResumeSlotHeld), v.Cause) + assert.Equal(t, liveStandingRun, v.StandingRun) + }) + + t.Run("a refusal of a run that blocked writes carries its write fence and no slot", func(t *testing.T) { + refused := &schemachange.RefusalError{Cause: schemachange.CauseFidelityDrift, Detail: "source public.c200 metadata changed since the shadow was built: grants"} + fenced := &schemachange.StandingRunError{Schema: "public", Table: "c200", Shadow: "_pgsprite_c200_new", Hold: schemachange.HoldWriteFence, Phase: checkpoint.PhaseCopying} + v, err := copySwapRunVerdict(st, holdFence, fmt.Errorf("run: %w; %w", refused, fenced)) + require.NoError(t, err) + assert.True(t, v.WritesBlocked) + assert.Equal(t, &verdict.StandingRun{ + Shadow: `"public"."_pgsprite_c200_new"`, + Hold: verdict.StandingHoldWriteFence, + Phase: "copying", + }, v.StandingRun) + }) + + // Every refusal the Runner names a stopped run beside carries the + // field, whichever account builds its detail: the changed source's, + // the slot backlog's figures, and the shared standing-run account. + t.Run("every refusal that names what the run leaves carries it typed", func(t *testing.T) { + backlog := &schemachange.SlotBacklogError{Slot: "pgsprite_c200", Unconfirmed: 200 << 20, Ceiling: 128 << 20} + for _, cause := range []schemachange.RefusalCause{ + schemachange.CauseResumeSourceChanged, schemachange.CauseSchemaDrift, schemachange.CauseFidelityDrift, + schemachange.CauseResumeRowMismatch, schemachange.CauseCopyConversionDrift, schemachange.CauseResumeSlotHeld, + schemachange.CauseResumeSlotBacklog, + } { + t.Run(string(cause), func(t *testing.T) { + refused := &schemachange.RefusalError{Cause: cause, Detail: "the library's account"} + v, err := copySwapRunVerdict(st, holdSlot, fmt.Errorf("run: %w; %w; %w", refused, backlog, liveStanding)) + require.NoError(t, err) + assert.Equal(t, verdict.Cause(cause), v.Cause) + assert.Equal(t, liveStandingRun, v.StandingRun) + }) + } + }) + + t.Run("a refusal that names nothing the run leaves carries no standing run", func(t *testing.T) { + refused := &schemachange.RefusalError{Cause: schemachange.CauseResumeRowMismatch, Detail: "checkpoint row names slot pgsprite_other"} + v, err := copySwapRunVerdict(st, holdSlot, fmt.Errorf("run: %w", refused)) + require.NoError(t, err) + assert.Nil(t, v.StandingRun) + }) + + t.Run("a stopped run naming a hold of unknown kind is an invariant violation", func(t *testing.T) { + refused := &schemachange.RefusalError{Cause: schemachange.CauseSchemaDrift, Detail: "source public.c200 changed shape since the shadow was built"} + unknown := &schemachange.StandingRunError{Schema: "public", Table: "c200", Shadow: "_pgsprite_c200_new", Hold: "lease", Phase: checkpoint.PhaseVerifying} + _, err := copySwapRunVerdict(st, holdSlot, fmt.Errorf("run: %w; %w", refused, unknown)) + assert.ErrorIs(t, err, executor.ErrInvariantViolation) + }) + t.Run("a cancelled run is coded as cancelled by the caller", func(t *testing.T) { v, _ := copySwapRunVerdict(st, holdSlot, fmt.Errorf("copy: %w", context.Canceled)) assert.Equal(t, string(executor.CodeCancelledByCaller), v.Code) diff --git a/pkg/verdict/standing_run.go b/pkg/verdict/standing_run.go new file mode 100644 index 000000000..0bb7b06ef --- /dev/null +++ b/pkg/verdict/standing_run.go @@ -0,0 +1,45 @@ +package verdict + +// StandingRun is what a copy-and-swap run a refusal stopped, or refused to +// resume, leaves standing with its checkpoint row: the shadow it built, its +// hold on the source, and the phase its row stands in. None of it is +// released by the refusal; it stands until the run is resumed, where acting +// on the refusal's cause lets it go on, started over (--restart), or +// discarded (pg-sprite discard). It is the machine-readable twin of the +// leftovers the verdict's detail names, so a host can warn that a +// replication slot retains WAL, or that the source refuses writes, without +// parsing prose; the verdict's cause says whether the run can resume. +type StandingRun struct { + // Shadow is the shadow table the run built, schema-qualified with every + // identifier quoted, as DROP TABLE takes it (for example + // "public"."_pgsprite_c74da4a21f58f903_new"). + Shadow string `json:"shadow"` + // Hold is what keeps the stopped run's place on the source. + Hold StandingHold `json:"hold"` + // Slot is a live run's replication slot, which retains the server's WAL + // until it is dropped, as pg_replication_slots names it. Absent when + // Hold is StandingHoldWriteFence. + Slot string `json:"slot,omitempty"` + // Publication is a live run's publication, with its identifier quoted, + // as DROP PUBLICATION takes it. Absent when Hold is + // StandingHoldWriteFence. + Publication string `json:"publication,omitempty"` + // Phase is the phase the checkpoint row stands in, such as "copying", + // "catching_up", or "verifying". + Phase string `json:"phase"` +} + +// StandingHold is the kind of hold a stopped copy-and-swap run keeps on its +// source. +type StandingHold string + +const ( + // StandingHoldSlot is a live run's replication slot and publication; + // the slot retains the server's WAL while it stands. + StandingHoldSlot StandingHold = "slot" + // StandingHoldWriteFence is the write fence of a run that blocked + // writes (--block-writes), which refuses every write to the source with + // SQLSTATE 55006 while it stands. Whether the catalog still shows it + // enabled is the verdict's WritesBlocked. + StandingHoldWriteFence StandingHold = "write-fence" +) diff --git a/pkg/verdict/standing_run_test.go b/pkg/verdict/standing_run_test.go new file mode 100644 index 000000000..75b20ac7e --- /dev/null +++ b/pkg/verdict/standing_run_test.go @@ -0,0 +1,66 @@ +package verdict + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// standing_run is part of the verdict contract a host warns on: its keys +// and hold tokens are pinned here, a live run's slot and publication +// present, and a run that blocked writes naming neither key rather than +// empty strings. +func TestStandingRunJSONKeys(t *testing.T) { + v := Verdict{ + Outcome: OutcomeRefused, + Reason: ReasonCopyAndSwapRefused, + Statement: "ALTER TABLE public.orders ALTER COLUMN qty TYPE bigint", + Table: "public.orders", + StandingRun: &StandingRun{ + Shadow: `"public"."_pgsprite_c74da4a21f58f903_new"`, + Hold: StandingHoldSlot, + Slot: "pgsprite_a725d037", + Publication: `"pgsprite_a725d037"`, + Phase: "verifying", + }, + } + js, err := v.JSON() + require.NoError(t, err) + var got map[string]any + require.NoError(t, json.Unmarshal([]byte(js), &got)) + assert.Equal(t, map[string]any{ + "shadow": `"public"."_pgsprite_c74da4a21f58f903_new"`, + "hold": "slot", + "slot": "pgsprite_a725d037", + "publication": `"pgsprite_a725d037"`, + "phase": "verifying", + }, got["standing_run"]) + + var decoded Verdict + require.NoError(t, json.Unmarshal([]byte(js), &decoded)) + assert.Equal(t, v.StandingRun, decoded.StandingRun, "the standing run round-trips") + + v.StandingRun = &StandingRun{ + Shadow: `"public"."_pgsprite_c74da4a21f58f903_new"`, + Hold: StandingHoldWriteFence, + Phase: "copying", + } + js, err = v.JSON() + require.NoError(t, err) + got = nil + require.NoError(t, json.Unmarshal([]byte(js), &got)) + assert.Equal(t, map[string]any{ + "shadow": `"public"."_pgsprite_c74da4a21f58f903_new"`, + "hold": "write-fence", + "phase": "copying", + }, got["standing_run"]) +} + +// A verdict that names no stopped run carries no standing_run key at all. +func TestStandingRunJSONOmittedWithoutAStoppedRun(t *testing.T) { + js, err := Verdict{Outcome: OutcomeRefused, Reason: ReasonCopyAndSwapRefused, Statement: "ALTER TABLE t ALTER COLUMN c TYPE bigint"}.JSON() + require.NoError(t, err) + assert.NotContains(t, js, "standing_run") +} diff --git a/pkg/verdict/verdict.go b/pkg/verdict/verdict.go index 026b79c21..8052ace88 100644 --- a/pkg/verdict/verdict.go +++ b/pkg/verdict/verdict.go @@ -884,6 +884,17 @@ type Verdict struct { // lock was never requested; nil for every verdict that did not end on // such a holder. LockHolder *LockHolder `json:"lock_holder,omitempty"` + // StandingRun is set on a copy-and-swap-refused verdict whose refusal + // stopped a run, or refused its resume, with its checkpoint row + // standing and names what that run leaves: the cutover's + // cutover-schema-drift and cutover-fidelity-drift, copy-conversion-drift, + // and the resume's resume-source-changed, resume-row-mismatch, + // resume-slot-held, and resume-slot-backlog. Detail names the same + // leftovers for a reader. Nil for every other verdict, including a + // refusal whose row names nothing this run can account for (a row that + // is not this table's run, a slot of the derived name that is not the + // route's) and resume-shadow-gone, whose shadow is gone. + StandingRun *StandingRun `json:"standing_run,omitempty"` } // RefusalCause is one of several causes behind a refusal: its typed cause, From ba204fc8cfbe4e12991e6c9befa83408e4a3a0f4 Mon Sep 17 00:00:00 2001 From: Kiran Muddukrishna Date: Fri, 4 Dec 2026 12:34:26 +0530 Subject: [PATCH 2/2] verdict: say standing_run is the row's record, and pin it unfenced A host reading only the field could warn that writes are refused on a table whose recorded fence was dropped by hand. The docs now lead with that, say how each kind of host reads the field and how it pairs with the discard report, and a unit test pins hold write-fence beside writes_blocked false. --- docs/cli-output-examples.md | 13 ++++++++++++- docs/invariants.md | 8 ++++++-- docs/schemabot-integration.md | 19 +++++++++++++------ pkg/migrate/copy_swap_test.go | 16 ++++++++++++++++ 4 files changed, 47 insertions(+), 9 deletions(-) diff --git a/docs/cli-output-examples.md b/docs/cli-output-examples.md index 6922d61bd..bf50eaa6f 100644 --- a/docs/cli-output-examples.md +++ b/docs/cli-output-examples.md @@ -546,7 +546,18 @@ it; `hold`, `slot` here, or `write-fence` for a run that blocked writes, which names no `slot` or `publication`; the slot as `pg_replication_slots` names it and the publication quoted; and the checkpoint row's `phase`. Every refusal that names what a stopped run leaves carries it, the cutover's drift refusals -included: +included. At a terminal the refusal reads: + +```console +$ pg-sprite migrate --alter 'ALTER TABLE orders ALTER COLUMN user_id TYPE bigint' --copy-and-swap --free-disk 10GiB +refused (copy-and-swap-refused) + table: public.orders + class: environmental + statement: ALTER TABLE public.orders ALTER COLUMN user_id TYPE bigint + detail: public.orders changed since this run built its shadow (for example a column or index added by hand); the stopped run cannot resume, and it leaves shadow table public._pgsprite_c74da4a21f58f903_new, replication slot pgsprite_a725d037, which retains WAL on the server until it is dropped, publication pgsprite_a725d037, and the checkpoint row in phase verifying; start over by running the same pg-sprite migrate command with --restart public.orders, or abandon the run without running the change with pg-sprite discard public.orders +``` + +and with `--json`: ```console $ pg-sprite migrate --alter 'ALTER TABLE orders ALTER COLUMN user_id TYPE bigint' --copy-and-swap --free-disk 10GiB --json diff --git a/docs/invariants.md b/docs/invariants.md index f7c324aa8..5f4cf317f 100644 --- a/docs/invariants.md +++ b/docs/invariants.md @@ -1345,7 +1345,10 @@ JSON-encoded proof the row carries (`resume-row-mismatch` otherwise, wrapping a is the derived one, as `copy-conversion-drift` for a proof that differs in its conversion fingerprint alone does, except that a row whose shadow fingerprint matches and whose source fingerprint, or source relation or source fidelity snapshot alone, differs is `resume-source-changed`: the source was changed under the stopped run, the environment's doing rather than the row's, and the refusal wraps a `StandingRunError` naming the shadow, -the fence or slot and publication, and the row the run leaves for a restart or `Runner.Discard`; +the fence or slot and publication, and the row the run leaves for a restart or `Runner.Discard`, +which `migrate` also carries on the verdict as `standing_run` +(`TestMigrateJSONNamesTheSlotAStoppedLiveRunLeaves`, +`TestMigrateJSONNamesTheWriteFenceAStoppedBlockedWritesRunLeaves`); `checkRowDescribes`, refuses-to-resume-a-stopped-run-whose-source-changed-by-hand test) — and refuses a relation under the shadow's name that no row records (`shadow-unrecorded`), since the row is the only record of which statement a shadow embodies, and a row whose swap has not committed and whose @@ -1660,7 +1663,8 @@ statement retyped, which the server re-derives for the new type; an operator cla written in the index still has to agree) and lists the sequences the swap must re-own. A `Runner` the gate stops on `cutover-schema-drift` or `cutover-fidelity-drift` cannot go on, so it returns the refusal with a `StandingRunError` beside it (`withStandingRun`) naming the shadow, the fence or slot and publication, and the checkpoint row it -leaves for a restart or `Runner.Discard` (cutover-drift-names-what-the-live-run-leaves test). Before that, +leaves for a restart or `Runner.Discard`, which `migrate` also carries on the verdict as `standing_run` +(cutover-drift-names-what-the-live-run-leaves test, `TestRunCopySwapCutoverDriftNamesWhatTheLiveRunLeaves`). Before that, `pkg/schemachange` refuses to build a shadow the source's owner does not own, and refuses to inspect or drop anything under the shadow's name that is not a plain table the source's owner owns (an inspected shadow must also still draw each identity default from the source's sequence). *Source:* diff --git a/docs/schemabot-integration.md b/docs/schemabot-integration.md index 4d905d5ae..7e8bc7572 100644 --- a/docs/schemabot-integration.md +++ b/docs/schemabot-integration.md @@ -652,19 +652,26 @@ backend ends in exactly one of four verdicts: A `copy-and-swap-refused` verdict whose refusal stopped a run, or refused its resume, with its checkpoint row standing names what that run leaves in `standing_run`, the typed twin of -the leftovers `detail` names, so a wrapper of `--json` can warn that a replication slot -retains WAL, or that the source refuses writes, without parsing prose. Every verdict whose +the leftovers `detail` names, so a wrapper of `--json` can warn that the run recorded a +replication slot, which retains WAL until it is dropped, or a write fence, without parsing +prose. The field is what the checkpoint row records, not a catalog reading: whether the fence +still stands is `writes_blocked`, and a slot or publication dropped by hand is still named. +Every verdict whose cause is `cutover-schema-drift`, `cutover-fidelity-drift`, `copy-conversion-drift`, `resume-source-changed`, `resume-slot-held`, or `resume-slot-backlog` carries it, and so does a `resume-row-mismatch` whose row describes the shadow under the derived name: exactly the -refusals that wrap a `*schemachange.StandingRunError`, from which a Go adapter reads the same -facts with `errors.As`. Its keys are `shadow`, the shadow table schema-qualified with every +refusals that wrap a `*schemachange.StandingRunError`. A `migrate.Run` host, whose refused +verdict comes with a nil error, reads `Verdict.StandingRun`; a `schemachange.Runner` host reads +the same facts with `errors.As` on the returned error. Its keys are `shadow`, the shadow table schema-qualified with every identifier quoted, as `DROP TABLE` takes it; `hold`, `slot` for a live run's replication slot and publication or `write-fence` for the fence of a run that blocked writes; `slot`, the slot's name as `pg_replication_slots` shows it, and `publication`, quoted as `DROP PUBLICATION` takes it, both present only under `hold: slot`; and `phase`, the checkpoint row's -phase, spelled as `pg-sprite discard --json` spells its `row_phase` (for example `verifying`). Whether the fence is still -enabled in the catalog is `writes_blocked`, not `hold`. The `cause` says whether the run can +phase, spelled as `pg-sprite discard --json` spells its `row_phase` (for example `verifying`). +Matched against the report of the `pg-sprite discard` that follows, `slot` and `phase` read the +same as its `slot` and `row_phase`; `shadow` and `publication` are quoted here and bare there, +the shadow schema-qualified here and in the table's schema there, so a wrapper that pairs the +two unquotes them first. The `cause` says whether the run can resume once it is acted on or must be started over (`--restart SCHEMA.TABLE`) or discarded (`pg-sprite discard SCHEMA.TABLE`), which drop all of it. `standing_run` is absent on every other verdict, including a `resume-row-mismatch` whose row is not this table's run, a diff --git a/pkg/migrate/copy_swap_test.go b/pkg/migrate/copy_swap_test.go index 0aac61c7a..92c005f1a 100644 --- a/pkg/migrate/copy_swap_test.go +++ b/pkg/migrate/copy_swap_test.go @@ -705,6 +705,22 @@ func TestCopySwapRunVerdict(t *testing.T) { }, v.StandingRun) }) + // The field is what the checkpoint row records, not a catalog reading: + // a run that blocked writes whose fence is gone from the table still + // names its write fence, and writes_blocked says that none stands. + t.Run("a refusal of a run whose recorded fence no longer stands carries the fence with writes not blocked", func(t *testing.T) { + refused := &schemachange.RefusalError{Cause: schemachange.CauseFidelityDrift, Detail: "source public.c200 metadata changed since the shadow was built: grants"} + fenced := &schemachange.StandingRunError{Schema: "public", Table: "c200", Shadow: "_pgsprite_c200_new", Hold: schemachange.HoldWriteFence, Phase: checkpoint.PhaseCopying} + v, err := copySwapRunVerdict(st, holdRowOnly, fmt.Errorf("run: %w; %w", refused, fenced)) + require.NoError(t, err) + assert.False(t, v.WritesBlocked) + assert.Equal(t, &verdict.StandingRun{ + Shadow: `"public"."_pgsprite_c200_new"`, + Hold: verdict.StandingHoldWriteFence, + Phase: "copying", + }, v.StandingRun) + }) + // Every refusal the Runner names a stopped run beside carries the // field, whichever account builds its detail: the changed source's, // the slot backlog's figures, and the shared standing-run account.