From ff4ffd37e5dbb2deb667905acf86db6e4e844eb6 Mon Sep 17 00:00:00 2001 From: Kiran Muddukrishna Date: Thu, 3 Dec 2026 05:58:04 +0530 Subject: [PATCH 1/2] migrate: name the index rebuild when refusing a partitioned parent retype The closed copy-and-swap gate told the operator to pass --copy-and-swap, which only reaches the partitioned-parent refusal. --- docs/binary-coercible-type-changes.md | 8 +- docs/capabilities.md | 2 +- docs/cli-output-examples.md | 2 +- docs/limitations.md | 2 +- docs/refusal-classes.md | 7 +- docs/schemabot-integration.md | 2 +- ...dryrun_copy_swap_route_integration_test.go | 45 +++++++++ pkg/capabilities/capabilities.yaml | 2 +- pkg/migrate/copy_swap_refusal.go | 14 +++ pkg/migrate/desired_copy_swap.go | 9 +- pkg/migrate/dry_run_admission.go | 9 +- pkg/migrate/dry_run_copy_swap.go | 2 +- pkg/migrate/migrate.go | 2 +- pkg/migrate/partitioned_index_rebuild.go | 96 +++++++++++++++++++ ...titioned_parent_retype_integration_test.go | 72 +++++++++++++- pkg/migrate/refusal_registry.go | 1 + pkg/planner/planner.go | 27 ++++++ pkg/planner/planner_test.go | 22 +++-- pkg/verdict/verdict.go | 10 ++ pkg/verdict/verdict_test.go | 1 + 20 files changed, 307 insertions(+), 28 deletions(-) create mode 100644 pkg/migrate/partitioned_index_rebuild.go diff --git a/docs/binary-coercible-type-changes.md b/docs/binary-coercible-type-changes.md index 5b5e88e12..27339b9f7 100644 --- a/docs/binary-coercible-type-changes.md +++ b/docs/binary-coercible-type-changes.md @@ -492,9 +492,11 @@ relabels only a column that no partitioned index reads, as a key, in an expressi predicate, whether the index stands alone or backs a constraint. It reads those indexes off the live parent, takes the rewrite route for a column one of them reads, and takes it marked unverified when they were not read. The change is refused with `copy-and-swap-refused` and -nothing executed: cause `copy-and-swap-not-enabled` while the run has not opened the -copy-and-swap route, the default, and `copy-and-swap-partitioned` once it has, since that -route refuses a partitioned parent. A foreign key on the column does not change the decision: it is +nothing executed: cause `partitioned-index-rebuild` while the run has not opened the +copy-and-swap route, the default, whose detail names the path that runs the change (drop the +index in a run of its own, then retype the column and recreate the index), and +`copy-and-swap-partitioned` once it has, since that route refuses a partitioned parent. A +parent whose partitioned indexes were not read keeps `copy-and-swap-not-enabled`. A foreign key on the column does not change the decision: it is re-created without a scan, on a parent as on a plain table. The `timestamp ↔ timestamptz` rule reads two facts off the live database: the session diff --git a/docs/capabilities.md b/docs/capabilities.md index 6b352e54a..15751b3a6 100644 --- a/docs/capabilities.md +++ b/docs/capabilities.md @@ -239,7 +239,7 @@ or the only online form is a direct statement the operator runs). | `ALTER COLUMN ... SET EXPRESSION` (changed stored generated expression) | 🟡 | copy-and-swap | Yes | Planned but not executed. `diff` shows a changed stored generated expression as one `SET EXPRESSION` statement of kind `set-generated-expression`, refused with `unsupported-statement`, rather than a drop and re-add that would also drop the column's indexes. It recomputes every row under `ACCESS EXCLUSIVE`, and the statement needs PostgreSQL 17 or later. An expression whose text the file keeps is not a change, even when the file retypes a column it reads: see the retyping row in [limitations.md](limitations.md#current-limitations) | | `ADD COLUMN` with inline `UNIQUE`/`PRIMARY KEY`/`REFERENCES`/`CHECK` | 🟡 | native, planned flow | Yes | The inline constraint does its index build or validation scan under the `ADD COLUMN`'s `ACCESS EXCLUSIVE` lock; refused with guidance to add the column first, then build the constraint online | | `DROP COLUMN` | ✅ | native, as-is | Yes | Metadata-only; flagged **destructive** in the plan report. `migrate` refuses it with `destructive-change` unless `--allow-destructive` names the table (`migrate --desired` refuses a destructive plan whole unless `--expect-fingerprint` pins the reviewed plan and `--allow-destructive` names the table); dropping a column and adding it back in one statement is refused with the `alter-column-type-in-place` guidance. Refused with `replica-identity` when a replica identity index the drop reaches keys on the column: the table's own, or one on a partition or inheritance child below it unless the statement says `ONLY`. Refused with `dependent-view`, naming the views, when a view or materialized view reads the column, on a table the drop reaches. Refused with `dependent-policy`, naming the policies, when a row-level security policy reads the column, on a table the drop reaches or on another table through a subquery. Refused with `dependent-trigger`, `dependent-rule`, `dependent-publication`, `dependent-generated-column`, or `partition-key`, naming the objects, when a trigger's `UPDATE OF` list or `WHEN` condition names the column, a rewrite rule reads it, a publication's column list or row filter names it, a generated column reads it, or it is in a partition key, on a table the drop reaches. Refused with `cascading-drop` when the statement says `CASCADE`, which would also drop the views and policies that read the column. A trigger whose PL/pgSQL function reads the column, which PostgreSQL records no dependency for and lets the drop break, is named in the decision's `trigger_reads` with the line that reads it, and a trigger whose function cannot be checked in `unchecked_triggers`; neither changes the route. A `migrate --desired` drop reads the object again under the table's lock and refuses with `dropped-object-drift`, dropping nothing, if its definition is not the one the reviewed plan carried. On a partitioned table it drops the column from the parent and every partition, sub-partitions included, after locking the whole tree: it refuses with `dropped-column-partition-key` when the column is in the partition key of the parent or of a sub-partitioned partition, and with `dropped-column-partition-dependent`, naming each object, when a partition carries an index, CHECK or foreign key, statistics object, sequence, or other object of its own on the column, which the parent's plan did not review; copies of the parent's indexes and constraints go with the parent's. On a table with inheritance children it refuses with `dropped-object-has-descendants`. `migrate --alter` makes no such partition check beyond the planner's `partition-key` refusal: the statement the operator wrote drops a partition's own objects on the column, as it drops the table's own. | -| `ALTER COLUMN TYPE`, binary-coercible (proven against live column facts) | ✅ | native, as-is | Yes | Catalog relabel, e.g. `varchar(50)` → `varchar(100)`, `varchar` → `text`, `timestamp(3)` → `timestamp(6)`, `varbit(8)` → `varbit(16)`, `cidr` → `inet`, and `timestamp` → `timestamptz` in a UTC session for a column no index or foreign key reads, refused with `time-zone-drift` when the session that runs it is no longer in UTC. On a partitioned parent a relabel is planned only for a column no partitioned index reads: PostgreSQL rebuilds every partition's index attached to one that reads it under `ACCESS EXCLUSIVE` on the whole tree, so that change takes the rewrite route, which refuses it with `copy-and-swap-refused`, nothing executed: cause `copy-and-swap-not-enabled` while the run has not opened the route (the default), and `copy-and-swap-partitioned` once it has. Refused with `dependent-view`, naming the views, when a view or materialized view reads the column, and with `dependent-policy`, naming the policies, when a row-level security policy reads it; refused likewise with `dependent-trigger`, `dependent-rule`, `dependent-publication`, `dependent-generated-column`, or `partition-key` when a trigger's `UPDATE OF` list or `WHEN` condition names it, a rewrite rule reads it, a publication's column list or row filter names it, a generated column reads it, or it is in a partition key; see [binary-coercible-type-changes.md](binary-coercible-type-changes.md#no-rewrite-is-not-no-cost) A trigger whose PL/pgSQL function reads the column, which PostgreSQL records no dependency for, is named in the decision's `trigger_reads` with the line that reads it, and a trigger whose function cannot be checked in `unchecked_triggers`; neither changes the route. | +| `ALTER COLUMN TYPE`, binary-coercible (proven against live column facts) | ✅ | native, as-is | Yes | Catalog relabel, e.g. `varchar(50)` → `varchar(100)`, `varchar` → `text`, `timestamp(3)` → `timestamp(6)`, `varbit(8)` → `varbit(16)`, `cidr` → `inet`, and `timestamp` → `timestamptz` in a UTC session for a column no index or foreign key reads, refused with `time-zone-drift` when the session that runs it is no longer in UTC. On a partitioned parent a relabel is planned only for a column no partitioned index reads: PostgreSQL rebuilds every partition's index attached to one that reads it under `ACCESS EXCLUSIVE` on the whole tree, so that change takes the rewrite route, which refuses it with `copy-and-swap-refused`, nothing executed: cause `partitioned-index-rebuild` while the run has not opened the route (the default), whose detail names the path that runs it (drop the index in a run of its own, then retype the column and recreate the index), and `copy-and-swap-partitioned` once it has. Refused with `dependent-view`, naming the views, when a view or materialized view reads the column, and with `dependent-policy`, naming the policies, when a row-level security policy reads it; refused likewise with `dependent-trigger`, `dependent-rule`, `dependent-publication`, `dependent-generated-column`, or `partition-key` when a trigger's `UPDATE OF` list or `WHEN` condition names it, a rewrite rule reads it, a publication's column list or row filter names it, a generated column reads it, or it is in a partition key; see [binary-coercible-type-changes.md](binary-coercible-type-changes.md#no-rewrite-is-not-no-cost) A trigger whose PL/pgSQL function reads the column, which PostgreSQL records no dependency for, is named in the decision's `trigger_reads` with the line that reads it, and a trigger whose function cannot be checked in `unchecked_triggers`; neither changes the route. | | `ALTER COLUMN TYPE`, general (or with `USING`) | ✅ preview | copy-and-swap | Yes | Table rewrite; runs through copy-and-swap: the changed shape is built as a shadow table, filled in chunks (a `USING` expression is applied per row), verified, and swapped in under the source's name. The route is in preview and runs only when the run opens it with `--copy-and-swap` (`CopySwapOptions.Enabled`); without it the statement is refused with `copy-and-swap-refused`, cause `copy-and-swap-not-enabled`, before the route's preflight runs or anything is written, and `migrate --dry-run` and `migrate --desired --dry-run`, which take `--copy-and-swap` as the run does, end in that same refusal without it. Refused with `dependent-view`, naming the views, when a view or materialized view reads the column, and with `dependent-policy`, naming the policies, when a row-level security policy reads it, and likewise with `dependent-trigger`, `dependent-rule`, `dependent-publication`, `dependent-generated-column`, or `partition-key` when a trigger's `UPDATE OF` list or `WHEN` condition names it, a rewrite rule reads it, a publication's column list or row filter names it, a generated column reads it, or it is in a partition key, before the route runs. The route's preflight still refuses table shapes and environments it cannot run against (`copy-and-swap-refused`); with the route opened, `migrate --alter --dry-run` runs that preflight under the run's own copy-and-swap flags, writing nothing, and ends in the same refusal, and `migrate --desired --dry-run` runs it the way the run's admission does, once against the live table under the run's flags, and ends in the run's whole-plan refusal. A `USING` expression is admitted only when the copy can reproduce it: immutable, naming only the retyped column, not the primary key (`shadow-statement-conversion`). A statement that also drops a column and adds one of the same name is refused when the copy cannot fill the new column — the primary key, a source identity column, or a column that refuses NULL with no default of its own or its domain's (`shadow-statement-readd`); a statement that also declares a new identity or `serial` column, re-added or kept, is refused with `shadow-statement-new-sequence` — see [limitations.md](limitations.md) A trigger whose PL/pgSQL function reads the column, which PostgreSQL records no dependency for, is named in the decision's `trigger_reads` with the line that reads it, and a trigger whose function cannot be checked in `unchecked_triggers`; neither changes the route. | | `SET DEFAULT` / `DROP DEFAULT` / `DROP NOT NULL` | ✅ | native, as-is | Yes | Metadata-only. `DROP NOT NULL` is flagged **destructive**: `migrate` refuses it with `destructive-change` unless `--allow-destructive` names the table, and `migrate --desired` runs it only when `--expect-fingerprint` also pins the reviewed plan. A `migrate --desired` drop reads the object again under the table's lock and refuses with `dropped-object-drift`, dropping nothing, if its definition is not the one the reviewed plan carried. A `migrate --desired` `DROP NOT NULL` on a partitioned table with partitions, or on a table with inheritance children, refuses with `dropped-object-has-descendants`: a partition can hold a `NOT NULL` of its own on the column, which the plan did not review. | | `SET NOT NULL` | ✅ | native, safer sequence | Yes | Executed as the native four-step pattern: `ADD CONSTRAINT ... CHECK (col IS NOT NULL) NOT VALID` → online `VALIDATE` → `SET NOT NULL` (catalog flip, PG 12+) → drop the scaffold check. A scaffold check an earlier run left is picked up where it stopped: the sequence starts at its `VALIDATE` and still drops it. `migrate --alter` on a column already `NOT NULL` on the table and every partition or inheritance child, with no scaffold check left, runs nothing and reports `executed-natively` with `already_not_null: true` and no `executed_sql`, after the same privilege check; the dry run classifies it `metadata-only` with no safer sequence | diff --git a/docs/cli-output-examples.md b/docs/cli-output-examples.md index 2c40c39ac..a4d699f00 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`), the closed route was reached only by retyping a column a partitioned parent's partitioned index reads, which the route would refuse as a partitioned parent once opened (cause `partitioned-index-rebuild`, class `capability-boundary` — drop the index in a run of its own, then retype the column and recreate the index, as the `detail` says; [limitations](limitations.md)), 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). | | `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 diff --git a/docs/limitations.md b/docs/limitations.md index 89596c791..19e25e867 100644 --- a/docs/limitations.md +++ b/docs/limitations.md @@ -27,7 +27,7 @@ not escape hatches: | Retyping or dropping a column a view reads | PostgreSQL refuses `ALTER COLUMN TYPE` and `DROP COLUMN` on a column a view or materialized view reads, even for a type change it would relabel in place. Without `ONLY`, a type change reaches the column on every partition and inheritance child too, and a drop reaches every partition and each inheritance child that does not declare the column and inherits it only from tables the drop also reaches; a child that declares the column or also inherits it from a table outside the drop keeps its copy, while one that inherits it along two paths from the dropped table loses it. The planner reads the views on every copy the change reaches from the catalog and refuses the change with `dependent-view`, naming each view in the plan and in the verdict's `dependent_views`, instead of letting the statement fail at the server. `DROP COLUMN … CASCADE`, which would drop the views with the column, is refused with `cascading-drop`. pg-sprite does not drop and recreate the views for you. The refusal names a materialized view by its kind, and its help gives the manual path the change takes: change the views so they no longer read the column before a drop, recreate them around an in-place type change in one transaction (a materialized view runs its query again to fill itself, while the transaction blocks the table), or point them at a new column for a type change that rewrites the table. The help also names the views that read those views, deepest first, to drop first and recreate last, and says to recreate the grants and materialized-view indexes a dropped view loses. | | Retyping or dropping a column a policy reads | PostgreSQL refuses `ALTER COLUMN TYPE` (`cannot alter type of a column used in a policy definition`) and `DROP COLUMN` on a column a row-level security policy reads in its `USING` or `WITH CHECK` expression, even for a type change it would relabel in place, such as widening a `varchar`. The policy counts wherever it is defined: on the table, on a partition or inheritance child the change reaches (the same reach as for a view), or on another table whose policy reads the column through a subquery. The planner reads those policies from the catalog and refuses the change with `dependent-policy`, naming each as `"policy" ON "schema"."table"` in the plan and in the verdict's `dependent_policies`, instead of letting the statement fail at the server. pg-sprite does not drop and recreate the policies for you. The refusal's help gives the manual path: before a drop, change the policies so they no longer read the column; around an in-place type change, drop and recreate them in the same transaction, so no session sees the table without them; for a type change that rewrites the table, add a column of the new type, backfill it, and point the policies at it, since copy-and-swap rebuilds the policies before it retypes and meets the same refusal. A row-security file that retypes the column and keeps the policy's text gets this refusal, not a row security difference: PostgreSQL prints the same policy on the new type with a cast, such as `(owner_name)::text`, so the live policies are created again on the file's table definition in the rolled-back scratch transaction and compared as printed there. | | Retyping or dropping a column a trigger, a rewrite rule, a generated column, or a partition key depends on | PostgreSQL refuses `ALTER COLUMN TYPE` and `DROP COLUMN` on a column that a trigger's `UPDATE OF` list or `WHEN` condition names (`cannot alter type of a column used in a trigger definition`), that a rewrite rule reads (`cannot alter type of a column used by a view or rule`), or that a generated column's expression reads (`cannot alter type of a column used by a generated column`), even for a type change it would relabel in place (PostgreSQL 14 instead drops the generated column along with a dropped column, without saying so), and never retypes or drops a partition key column (`42P16`). The planner reads these dependents from the catalog, with the same reach as for a view, and refuses the change with `dependent-trigger`, `dependent-rule`, `dependent-generated-column`, or `partition-key`, naming the objects in the plan and in the verdict's `dependent_triggers`, `dependent_rules`, `dependent_generated_columns`, or `partition_key_tables`. pg-sprite does not drop and recreate them for you. The refusal's help gives the manual path: for triggers and rules, the same three paths as for policies; for generated columns, drop them first, knowing that adding a `STORED` one back rewrites the table; for a partition key, a new partitioned table with the new column definition that the rows move into. A trigger whose function body reads the column does not block the change, and is not refused; a PL/pgSQL body that reads it is named in the decision's `trigger_reads`, and a body pg-sprite cannot check in `unchecked_triggers`. A read through SQL is named in neither: a query in the body, or in a function it calls, that reads the table by name or through a transition table. A desired file that retypes a column a stored generated column reads, and keeps the generated column's expression text, gets this refusal alone, with no `SET EXPRESSION` beside it: PostgreSQL prints the live expression with a cast for the old type, such as `lower((email)::text)` for a `varchar` column, so the live expression is built again on the file's table definition in the rolled-back scratch transaction and compared as printed there. Dropping the generated column and planning again adds it back with the file's expression on the column's new type, so an expression whose result depends on the type takes the new type's: `a / 2` divides as integers while `a` is `integer`, and keeps fractions once it is `numeric`. | -| Retyping a column a partitioned parent's index reads | A type change PostgreSQL relabels in place, such as `varchar(10)` → `varchar(20)`, still rebuilds, on a partitioned parent, every partition's index attached to a partitioned index that reads the column, under `ACCESS EXCLUSIVE` on the whole tree; a plain table keeps such an index. The planner relabels a parent's column only when no partitioned index reads it (a partition's own index does not count), and otherwise takes the rewrite route, refuses it with `copy-and-swap-refused`, nothing executed, in `--dry-run` and `migrate --desired` too: cause `copy-and-swap-not-enabled` while the run has not opened that route, the default, and `copy-and-swap-partitioned` once it has, since the route refuses a partitioned parent. To run the change, drop the index in its own desired-state run, since `migrate --alter` refuses a partitioned index's drop and the planner reads the index off the live table, so one file that both removes it and retypes the column is still refused: remove it from the desired file, which runs a brief blocking `DROP INDEX` (PostgreSQL has no concurrent drop for it) under that run's acknowledgements; then retype the column, and rebuild the index online (`CREATE INDEX` on the parent, which pg-sprite runs partition by partition). Or run the statement with `--force SCHEMA.TABLE`, which takes the tree-wide lock for as long as the rebuilds last ([binary-coercible-type-changes.md](binary-coercible-type-changes.md#how-pg-sprite-classifies-type-changes)). | +| Retyping a column a partitioned parent's index reads | A type change PostgreSQL relabels in place, such as `varchar(10)` → `varchar(20)`, still rebuilds, on a partitioned parent, every partition's index attached to a partitioned index that reads the column, under `ACCESS EXCLUSIVE` on the whole tree; a plain table keeps such an index. The planner relabels a parent's column only when no partitioned index reads it (a partition's own index does not count), and otherwise takes the rewrite route, refuses it with `copy-and-swap-refused`, nothing executed, in `--dry-run` and `migrate --desired` too: cause `partitioned-index-rebuild` while the run has not opened that route, the default, since opening it would not run the change, and `copy-and-swap-partitioned` once it has, since the route refuses a partitioned parent; the `partitioned-index-rebuild` detail names the index rebuild and the path below instead of `--copy-and-swap` (a parent whose partitioned indexes were not read keeps `copy-and-swap-not-enabled`). To run the change, drop the index in its own desired-state run, since `migrate --alter` refuses a partitioned index's drop and the planner reads the index off the live table, so one file that both removes it and retypes the column is still refused: remove it from the desired file, which runs a brief blocking `DROP INDEX` (PostgreSQL has no concurrent drop for it) under that run's acknowledgements (`--accept-blocking` and `--allow-destructive` naming the table, with `--expect-fingerprint`); then retype the column, and rebuild the index online (`CREATE INDEX` on the parent, which pg-sprite runs partition by partition). Or run the statement with `--force SCHEMA.TABLE`, which takes the tree-wide lock for as long as the rebuilds last ([binary-coercible-type-changes.md](binary-coercible-type-changes.md#how-pg-sprite-classifies-type-changes)). | | Retyping or dropping a column a publication names | PostgreSQL refuses `ALTER COLUMN TYPE` and `DROP COLUMN` on a column that a publication's column list or row filter for the table names (`cannot alter type of a column used by a publication WHERE clause`, said for a column list too). The planner reads these publications from the catalog, with the same reach as for a view, and refuses the change with `dependent-publication`, naming them in the plan and in the verdict's `dependent_publications`. pg-sprite does not change a publication for you, since what a subscriber receives is the publication owner's decision. The refusal's help gives the manual path: remove the column from the publications with `ALTER PUBLICATION ... SET TABLE`, and for a type change add it back afterwards. A publication without a column list or row filter does not block the change. A publication that starts naming the column after planning, for a reviewed plan or a drop submitted with `--alter`, stops the run with `dropped-object-drift`, read under the table's lock, before anything is dropped. The error and the verdict's `detail` name the publication. | | Changing a table a logical replication subscription writes | A subscriber applies each change its publisher sends as the publisher shaped it, and PostgreSQL does not check a subscriber's table change against what the publisher still sends. Dropping, renaming, or retyping a column the publisher sends, renaming the table or moving it to another schema, dropping the replica identity index the subscriber finds rows by, or making a column `NOT NULL` that the publisher may send `NULL` in or not send at all, lets the change run, and the subscription's apply worker then fails on the next change and retries it in a loop while the publisher's slot keeps WAL. A new primary key, unique, `CHECK`, or exclusion constraint, or a unique index, does the same at the first row the publisher sends that breaks it. The planner reads the subscriptions that write the table, a table below it, or a partitioned table above it, from `pg_subscription_rel` and names them on the decision: `stops_subscriptions` for the first kind of change, with a warning and the publisher-first fix in the text output, and `may_stall_subscriptions` for the second, with a note. Both are advisory and leave the route unchanged, since a subscriber cannot see whether its publisher has already made the change that makes it safe. | | Adding a `NOT NULL` column with no default to a table that holds rows | PostgreSQL refuses it (SQLSTATE `23502`), because every existing row would hold `NULL` in the new column. The `NOT NULL` can come from the statement, the column's domain, or an inline `PRIMARY KEY`. The planner adds the column to a one-row temporary table to see whether PostgreSQL leaves it `NULL` or something fills it, such as its domain's `DEFAULT`, and only then reads whether the table holds rows, skipping foreign tables, whose rows PostgreSQL does not check, reading at most one row and never waiting for a lock, and refuses the change with `not-null-without-default` instead of letting it fail at the server under the table's exclusive lock. Give the column a constant default, or add it without `NOT NULL`, backfill it, and set `NOT NULL` afterwards. When the `NOT NULL` comes from the column's domain, neither path exists, since a domain with a constraint rewrites the table whatever the default, so the refusal names the domain and says to add the column with the type its domain chain ends in, carrying the domain's constraints on the column instead. A read another session's lock blocks fails the plan with an error; retry once the lock is released. Rows a row-level security policy hides from the role do not count, so for such a role the server's refusal remains the backstop. | diff --git a/docs/refusal-classes.md b/docs/refusal-classes.md index 9eea7b032..ad0ebbf27 100644 --- a/docs/refusal-classes.md +++ b/docs/refusal-classes.md @@ -132,6 +132,7 @@ A file the parser cannot read is not a refusal: it is `statement.ErrParseDesired | `backend-unavailable` | The plan routes to copy-and-swap for an operation the engine does not carry yet | `capability-boundary` | — | | `backend-unavailable` | Cause `add-column-probe-locked`: every operation the statement routes off the native path, from `migrate --alter` or a desired-state plan, is an `ADD COLUMN` whose catalog-only proof met a lock another session held, which the probe does not wait for. An add whose proof never ran, such as an `ADD COLUMN IF NOT EXISTS` of a column the table already has, does not count, since planning again changes nothing for it. Nothing executed; the same statement planned again once the lock is released can prove the add runs in place, so retrying may succeed and the engine has no capability to gain. A statement with any other off-native operation keeps the `capability-boundary` row above, and so does a desired-state plan with any later refused statement that is not such an add, since a retry would meet it again (`addColumnProbeLockedRefusal`) | `environmental` | — | | `copy-and-swap-refused` | Cause `copy-and-swap-not-enabled`: the statement routes to copy-and-swap and the run did not open the route (`--copy-and-swap`, `CopySwapOptions.Enabled`); either front door refuses before the route's preflight runs or anything is written, after its own target resolution and planning have read the catalog (`copySwapNotEnabledRefusal`) | `capability-boundary` | — | +| `copy-and-swap-refused` | Cause `partitioned-index-rebuild`: in place of `copy-and-swap-not-enabled`, when every operation the statement or plan routes to the closed copy-and-swap route is a type change PostgreSQL relabels in place on a plain table, routed there only because a partitioned parent's partitioned index reads the column, so it would rebuild every partition's attached index under `ACCESS EXCLUSIVE` on the whole tree (`planner.Decision.RebuildsPartitionedIndexes`, in-process only). Opening the route would end in `copy-and-swap-partitioned`, so the detail names the two-run path instead: drop the index in a run of its own, then retype the column and recreate the index ([limitations](limitations.md)). Minted where the closed route's refusal is, by both front doors and their dry runs, before anything is written; a resumed stopped run keeps `copy-and-swap-not-enabled` (`partitionedIndexRebuildRefusal`) | `capability-boundary` | No route runs the change online today; the manual path does. | | `copy-and-swap-refused` | Cause `copy-and-swap-run-stopped`: the table has a copy-and-swap run stopped short of done (a non-terminal checkpoint row), and `migrate --alter` was given a statement other than the one the row records, compared as parsed, with no `--restart` naming the table, an index rename or blocking index statement under `--accept-blocking` included; or desired-state execution derived an empty plan for the table while the row stands, reached a reviewed plan's index drop, was given a row security file whose change runs in one transaction on the table, or derived a plan that creates the table while the row of a run on a dropped table of that name stands. A dry run, imperative or desired-state, ends in the same refusal where its apply would. `ALTER TYPE ... ADD VALUE` is exempt: it locks no table and changes nothing in a table's shape. A row this engine cannot judge (another format or phase, a store an older engine created, a store the role cannot read) holds the table the same way while the run's shadow or retained source stands in the catalog; `--restart` lifts that only for a statement that routes to copy-and-swap, whose route judges the row itself. Running anything else would change the table under the stopped run, so nothing executes; the detail names the stopped statement and its phase. Finish the run by running its statement again, which resumes it through copy-and-swap whatever it would route to against the table's shape by then; before the swap, a statement that itself routes to copy-and-swap can instead start over under `--restart`, which discards the stopped run first; or, before cutover, abandon it with `pg-sprite discard SCHEMA.TABLE`, the one way out when the table was dropped since, which the create's detail names (a `cutover` row on a dropped table is removed by hand, keeping the retained source, which may be the only copy of the rows) (`copySwapRunStoppedRefusal`) | `environmental` | The server's state has to change — the stopped run finished or discarded — not the statement or the engine. | | `destructive-change` | Neither front door infers permission to discard live data or structure: desired-state admission refuses a destructive plan whole unless the run pins the reviewed plan's fingerprint and names the table in its own destructive acknowledgement, and `migrate --alter` refuses a statement that drops a column, constraint, or `NOT NULL` — and a `DROP INDEX` under `--accept-blocking` — until `--allow-destructive` names the table (RF-10) | `by-design` | — | | `plan-fingerprint-mismatch` | The recomputed plan is not the reviewed plan. Cause `pinned-refused-preview`: the pin is a dry run's refused preview of the plan, so nothing changed and the plan's own fingerprint is the one to pin | `environmental` | — | @@ -157,9 +158,11 @@ conversion. ### `copy-and-swap-refused`, keyed on `CopySwapRefusalCause` -Two causes under this reason are not preflight causes: `copy-and-swap-not-enabled` is minted by +Three causes under this reason are not preflight causes: `copy-and-swap-not-enabled` is minted by the front doors themselves (the site-keyed row above) when the run has not opened the route, -and is raised before the preflight is reached, and `copy-and-swap-run-stopped` is minted by +and is raised before the preflight is reached, `partitioned-index-rebuild` is minted in its +place for a retype the route takes only because a partitioned index reads the column, and +`copy-and-swap-run-stopped` is minted by the front doors when a stopped run's checkpoint row keeps another statement from running. The preflight causes follow. diff --git a/docs/schemabot-integration.md b/docs/schemabot-integration.md index e6474f433..6f7719b08 100644 --- a/docs/schemabot-integration.md +++ b/docs/schemabot-integration.md @@ -647,7 +647,7 @@ 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; `cause: partitioned-index-rebuild`, also `class: capability-boundary`, in its place when every operation routed there retypes a column a partitioned parent's partitioned index reads, which the opened route would refuse as a partitioned parent, so enabling the route does not run it), 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. `partitioned-index-rebuild` touched nothing either; route it to the operator rather than retry with `CopySwap.Enabled`: the change runs once the partitioned index is dropped in a run of its own, and the index is recreated after the retype ([limitations](limitations.md)). 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: 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 | The adapter supplies the route's policy on `migrate.Options.CopySwap`: `Enabled`, which opens diff --git a/internal/cli/dryrun_copy_swap_route_integration_test.go b/internal/cli/dryrun_copy_swap_route_integration_test.go index 2f7e4fd59..8c8221308 100644 --- a/internal/cli/dryrun_copy_swap_route_integration_test.go +++ b/internal/cli/dryrun_copy_swap_route_integration_test.go @@ -83,6 +83,51 @@ func TestMigrateDryRunRefusesAClosedCopySwapRetypeLikeApply(t *testing.T) { assert.Equal(t, "integer", qtyType(t, pool, schema), "neither the dry run nor the refused run changed the column") } +// Widening a varchar a partitioned index reads, on a partitioned parent, +// routes to copy-and-swap only because the change would rebuild every +// partition's index, and the route does not take a partitioned parent, so +// the closed route's refusal carries cause partitioned-index-rebuild instead +// of naming --copy-and-swap. The dry run ends in the run's same verdict. +func TestMigrateDryRunRefusesAPartitionedIndexRebuildLikeApply(t *testing.T) { + url := testutil.StartPostgres(t) + pool, err := dbconn.NewPool(t.Context(), dbconn.Config{URL: url}) + require.NoError(t, err) + t.Cleanup(pool.Close) + schema := testutil.NewSchema(t, pool) + _, err = pool.Exec(t.Context(), fmt.Sprintf(` + CREATE TABLE %[1]s.events ( + id bigint NOT NULL, + created date NOT NULL, + note varchar(10), + PRIMARY KEY (id, created) + ) PARTITION BY RANGE (created); + CREATE TABLE %[1]s.events_2026 PARTITION OF %[1]s.events + FOR VALUES FROM ('2026-01-01') TO ('2027-01-01'); + CREATE INDEX events_note_idx ON %[1]s.events (note)`, schema)) + require.NoError(t, err) + alter := fmt.Sprintf("ALTER TABLE %s.events ALTER COLUMN note TYPE varchar(20)", schema) + + run := func(cmd *MigrateCmd) verdict.Verdict { + cmd.JSON = true + var out strings.Builder + require.ErrorIs(t, cmd.run(t.Context(), &out), verdict.ErrRefused, + "the refusal exit code must not depend on --dry-run") + var v verdict.Verdict + require.NoError(t, json.Unmarshal([]byte(out.String()), &v)) + return v + } + dry := newMigrateCmd(url, alter) + dry.DryRun = true + dryRun := run(dry) + applied := run(newMigrateCmd(url, alter)) + + assert.Equal(t, verdict.OutcomeRefused, dryRun.Outcome) + assert.Equal(t, verdict.ReasonCopyAndSwapRefused, dryRun.Reason) + assert.Equal(t, verdict.ClassCapabilityBoundary, dryRun.Class) + assert.Equal(t, verdict.CausePartitionedIndexRebuild, dryRun.Cause) + assert.Equal(t, applied, dryRun, "the dry run must report the refusal the run reports") +} + // The same retype with --copy-and-swap and the flags its run takes: the dry // run reports the plan the opened route runs, executable on the // copy-and-swap backend with exit 0, and the run with the flags (offline, diff --git a/pkg/capabilities/capabilities.yaml b/pkg/capabilities/capabilities.yaml index 3ba27d457..0f7e53010 100644 --- a/pkg/capabilities/capabilities.yaml +++ b/pkg/capabilities/capabilities.yaml @@ -94,7 +94,7 @@ rows: front_doors: migrate: supported diff: supported - reason_notes: "Catalog relabel, e.g. `varchar(50)` → `varchar(100)`, `varchar` → `text`, `timestamp(3)` → `timestamp(6)`, `varbit(8)` → `varbit(16)`, `cidr` → `inet`, and `timestamp` → `timestamptz` in a UTC session for a column no index or foreign key reads, refused with `time-zone-drift` when the session that runs it is no longer in UTC. On a partitioned parent a relabel is planned only for a column no partitioned index reads: PostgreSQL rebuilds every partition's index attached to one that reads it under `ACCESS EXCLUSIVE` on the whole tree, so that change takes the rewrite route, which refuses it with `copy-and-swap-refused`, nothing executed: cause `copy-and-swap-not-enabled` while the run has not opened the route (the default), and `copy-and-swap-partitioned` once it has. Refused with `dependent-view`, naming the views, when a view or materialized view reads the column, and with `dependent-policy`, naming the policies, when a row-level security policy reads it; refused likewise with `dependent-trigger`, `dependent-rule`, `dependent-publication`, `dependent-generated-column`, or `partition-key` when a trigger's `UPDATE OF` list or `WHEN` condition names it, a rewrite rule reads it, a publication's column list or row filter names it, a generated column reads it, or it is in a partition key; see [binary-coercible-type-changes.md](binary-coercible-type-changes.md#no-rewrite-is-not-no-cost) A trigger whose PL/pgSQL function reads the column, which PostgreSQL records no dependency for, is named in the decision's `trigger_reads` with the line that reads it, and a trigger whose function cannot be checked in `unchecked_triggers`; neither changes the route." + reason_notes: "Catalog relabel, e.g. `varchar(50)` → `varchar(100)`, `varchar` → `text`, `timestamp(3)` → `timestamp(6)`, `varbit(8)` → `varbit(16)`, `cidr` → `inet`, and `timestamp` → `timestamptz` in a UTC session for a column no index or foreign key reads, refused with `time-zone-drift` when the session that runs it is no longer in UTC. On a partitioned parent a relabel is planned only for a column no partitioned index reads: PostgreSQL rebuilds every partition's index attached to one that reads it under `ACCESS EXCLUSIVE` on the whole tree, so that change takes the rewrite route, which refuses it with `copy-and-swap-refused`, nothing executed: cause `partitioned-index-rebuild` while the run has not opened the route (the default), whose detail names the path that runs it (drop the index in a run of its own, then retype the column and recreate the index), and `copy-and-swap-partitioned` once it has. Refused with `dependent-view`, naming the views, when a view or materialized view reads the column, and with `dependent-policy`, naming the policies, when a row-level security policy reads it; refused likewise with `dependent-trigger`, `dependent-rule`, `dependent-publication`, `dependent-generated-column`, or `partition-key` when a trigger's `UPDATE OF` list or `WHEN` condition names it, a rewrite rule reads it, a publication's column list or row filter names it, a generated column reads it, or it is in a partition key; see [binary-coercible-type-changes.md](binary-coercible-type-changes.md#no-rewrite-is-not-no-cost) A trigger whose PL/pgSQL function reads the column, which PostgreSQL records no dependency for, is named in the decision's `trigger_reads` with the line that reads it, and a trigger whose function cannot be checked in `unchecked_triggers`; neither changes the route." - id: alter-column-type-general-or-with-using area: "column_changes" operation: "`ALTER COLUMN TYPE`, general (or with `USING`)" diff --git a/pkg/migrate/copy_swap_refusal.go b/pkg/migrate/copy_swap_refusal.go index 48d609176..a8421cf5a 100644 --- a/pkg/migrate/copy_swap_refusal.go +++ b/pkg/migrate/copy_swap_refusal.go @@ -29,6 +29,20 @@ func copySwapNotEnabledRefusal() verdict.Refusal { WithCause(verdict.CauseCopyAndSwapNotEnabled) } +// partitionedIndexRebuildRefusal: the statement routes to a closed +// copy-and-swap only because it retypes a column of a partitioned parent +// that a partitioned index reads (planner.Decision.RebuildsPartitionedIndexes). +// Opening the route would end in its partitioned-parent refusal, so the +// cause names the change's own boundary instead of the route's flag. The +// engine has no route that runs the change online, so the class is a +// capability boundary, as for the closed route it narrows; the change runs +// once the index is dropped in a run of its own. Minted where +// copySwapNotEnabledRefusal is, before anything is written. +func partitionedIndexRebuildRefusal() verdict.Refusal { + return verdict.CapabilityBoundary(verdict.ReasonCopyAndSwapRefused). + WithCause(verdict.CausePartitionedIndexRebuild) +} + // copySwapRunStoppedRefusal: the table has a copy-and-swap run stopped // short of done, and the statement is not the one it records, or (on the // desired-state door) the plan is empty and has none to run. Running diff --git a/pkg/migrate/desired_copy_swap.go b/pkg/migrate/desired_copy_swap.go index f55b8f877..f0f09a70d 100644 --- a/pkg/migrate/desired_copy_swap.go +++ b/pkg/migrate/desired_copy_swap.go @@ -182,7 +182,10 @@ func preflightCopySwapPlan(ctx context.Context, pool *pgxpool.Pool, report plan. // the route closed (CopySwapOptions.Enabled unset), the plan is refused // whole, native statements included, with reason copy-and-swap-refused and // cause copy-and-swap-not-enabled, naming the first routed statement, -// before anything is read or runs. [RunDesired] asks it before the route's +// before anything is read or runs. A plan that routes there only retypes +// of columns a partitioned parent's partitioned index reads is refused +// with cause partitioned-index-rebuild instead, since opening the route +// would not run it. [RunDesired] asks it before the route's // preflight; a desired-state dry run asks it with the options the run would // take, so its preview cannot report as executable a plan that routes a // statement to copy-and-swap and that the run refuses for it. It keys on @@ -199,9 +202,7 @@ func AdmitPlanCopySwapRoute(report plan.Report, opts Options) (DesiredResult, bo if opts.CopySwap.Enabled { return DesiredResult{}, true } - return DesiredResult{Plan: report}.refused(copySwapNotEnabledRefusal(), fmt.Sprintf( - "planned statement %d (%s) routes to copy-and-swap, which is not enabled for this run: %s", - first+1, report.Statements[first].SQL, copySwapNotEnabledDetail)), false + return closedCopySwapPlanRefusal(report, first), false } // refuseCopySwapPlan is the whole-plan refusal for a table the route's diff --git a/pkg/migrate/dry_run_admission.go b/pkg/migrate/dry_run_admission.go index 3eff93362..baf8d4889 100644 --- a/pkg/migrate/dry_run_admission.go +++ b/pkg/migrate/dry_run_admission.go @@ -193,7 +193,9 @@ func partitionedForeignKeyCatalogRefusal(err error) (verdict.Refusal, bool) { // statement, would run through copy-and-swap under opts — the router sends // it there, or st resumes a copy-and-swap run stopped on schema.table — and // opts keep the route closed, it returns the verdict [Run] ends in: reason -// copy-and-swap-refused, cause copy-and-swap-not-enabled. It asks the +// copy-and-swap-refused, cause copy-and-swap-not-enabled, or +// partitioned-index-rebuild for a retype the route takes only because a +// partitioned parent's partitioned index reads the column. It asks the // predicate Run asks, so a dry run handed the options the run would take // cannot report as executable a statement the run refuses, and one handed // the opened route reports the plan as before. Run asks it once the @@ -212,7 +214,8 @@ func AdmitCopySwapRoute(ctx context.Context, pool *pgxpool.Pool, st statement.St if err != nil { return verdict.Verdict{}, false, err } - if !refusesClosedCopySwap(rs, stopped.resumedBy(st), opts) { + resumes := stopped.resumedBy(st) + if !refusesClosedCopySwap(rs, resumes, opts) { return verdict.Verdict{}, false, nil } target := st @@ -221,7 +224,7 @@ func AdmitCopySwapRoute(ctx context.Context, pool *pgxpool.Pool, st statement.St return verdict.Verdict{}, false, err } } - return copySwapNotEnabledVerdict(target), true, nil + return closedCopySwapVerdict(target, rs, resumes, opts), true, nil } // AdmitCopySwapPartitioning is the dry run's reading of the copy-and-swap diff --git a/pkg/migrate/dry_run_copy_swap.go b/pkg/migrate/dry_run_copy_swap.go index ec5241504..e60a4055b 100644 --- a/pkg/migrate/dry_run_copy_swap.go +++ b/pkg/migrate/dry_run_copy_swap.go @@ -93,7 +93,7 @@ func AdmitCopySwapPreflight(ctx context.Context, pool *pgxpool.Pool, st statemen return verdict.Verdict{}, false, err } if !opts.CopySwap.Enabled { - return copySwapNotEnabledVerdict(target), true, nil + return closedCopySwapVerdict(target, rs, resumes, opts), true, nil } if resumes { if v, refused, err := refuseOtherModeRun(target, stopped, opts); refused || err != nil { diff --git a/pkg/migrate/migrate.go b/pkg/migrate/migrate.go index 0944bdc7c..acdcd2fcc 100644 --- a/pkg/migrate/migrate.go +++ b/pkg/migrate/migrate.go @@ -450,7 +450,7 @@ func runStatement(ctx context.Context, pool *pgxpool.Pool, st statement.Statemen // it, and the closed route acts on nothing. copyAndSwap keeps its own // gate for callers that reach it directly. if refusesClosedCopySwap(rs, resumes, opts) { - return copySwapNotEnabledVerdict(st), nil + return closedCopySwapVerdict(st, rs, resumes, opts), nil } if resumes { if v, refused, err := refuseOtherModeRun(st, stopped, opts); refused || err != nil { diff --git a/pkg/migrate/partitioned_index_rebuild.go b/pkg/migrate/partitioned_index_rebuild.go new file mode 100644 index 000000000..9b1f97dc6 --- /dev/null +++ b/pkg/migrate/partitioned_index_rebuild.go @@ -0,0 +1,96 @@ +package migrate + +import ( + "fmt" + + "github.com/block/pg-sprite/pkg/plan" + "github.com/block/pg-sprite/pkg/planner" + "github.com/block/pg-sprite/pkg/router" + "github.com/block/pg-sprite/pkg/statement" + "github.com/block/pg-sprite/pkg/verdict" +) + +// This file narrows the closed copy-and-swap gate's refusal for a retype of +// a column a partitioned parent's partitioned index reads. The planner +// routes such a change to copy-and-swap only because of the index +// (planner.Decision.RebuildsPartitionedIndexes), and the route refuses a +// partitioned parent, so naming --copy-and-swap as the way forward would +// lead the operator to a second refusal. The gate refuses it with cause +// partitioned-index-rebuild instead, and its detail names the index rebuild +// and the path that runs the change (docs/limitations.md). + +// partitionedIndexRebuildDetail is the prose behind the narrowed refusal, +// shared by both front doors and their dry runs. +const partitionedIndexRebuildDetail = "the change retypes a column a partitioned index reads: PostgreSQL relabels the column in place, " + + "but on a partitioned parent it rebuilds every partition's index attached to that partitioned index under ACCESS EXCLUSIVE on the whole partition tree, " + + "so the change routes to copy-and-swap, which does not take a partitioned parent, and --copy-and-swap does not run it; " + + "run it in two runs instead: first drop the partitioned index in a run of its own " + + "(remove it from the desired file; the drop is a brief blocking DROP INDEX, since PostgreSQL has no concurrent drop for it, " + + "which runs only under --accept-blocking and --allow-destructive naming the table, with --expect-fingerprint), " + + "then retype the column, which relabels in place once no partitioned index reads it, and recreate the index " + + "(CREATE INDEX on the parent, which pg-sprite builds partition by partition); " + + "or run the statement under --force SCHEMA.TABLE, which holds the tree-wide lock while the indexes rebuild; nothing was executed" + +// rebuildsPartitionedIndexesOnly reports whether decisions route to +// copy-and-swap only through retypes the planner marked +// RebuildsPartitionedIndexes: at least one decision routes there, and every +// one that does is such a retype. A decision that rewrites the table for +// another reason keeps the closed route's own refusal, since dropping an +// index would not run it. +func rebuildsPartitionedIndexesOnly(decisions []planner.Decision) bool { + routed := false + for _, d := range decisions { + if d.Route != planner.RouteCopyAndSwap { + continue + } + if !d.RebuildsPartitionedIndexes { + return false + } + routed = true + } + return routed +} + +// closedCopySwapVerdict is the refusal for a statement [refusesClosedCopySwap] +// refuses: cause partitioned-index-rebuild when the router sends it to +// copy-and-swap only for retypes that rebuild a partitioned index, and the +// closed route's own refusal otherwise, including for a statement that +// resumes a stopped run, which only the route finishes. +func closedCopySwapVerdict(st statement.Statement, rs router.Statement, resumes bool, opts Options) verdict.Verdict { + if !resumes && routesToClosedCopySwap(rs, opts) && rebuildsPartitionedIndexesOnly(rs.Decisions) { + return refusedVerdict(st, partitionedIndexRebuildRefusal(), partitionedIndexRebuildDetail) + } + return copySwapNotEnabledVerdict(st) +} + +// planRebuildsPartitionedIndexesOnly reports whether every planned +// statement the router assigned to copy-and-swap goes there only for +// retypes that rebuild a partitioned index, and at least one does. +func planRebuildsPartitionedIndexesOnly(report plan.Report) bool { + routed := false + for _, ps := range report.Statements { + if ps.Backend != router.BackendCopyAndSwap { + continue + } + if !rebuildsPartitionedIndexesOnly(ps.Decisions) { + return false + } + routed = true + } + return routed +} + +// closedCopySwapPlanRefusal is the whole-plan refusal [AdmitPlanCopySwapRoute] +// returns for a plan whose first copy-and-swap statement is at first: cause +// partitioned-index-rebuild when planRebuildsPartitionedIndexesOnly holds, +// and the closed route's own refusal otherwise. +func closedCopySwapPlanRefusal(report plan.Report, first int) DesiredResult { + if planRebuildsPartitionedIndexesOnly(report) { + return DesiredResult{Plan: report}.refused(partitionedIndexRebuildRefusal(), fmt.Sprintf( + "planned statement %d (%s) routes to copy-and-swap: %s", + first+1, report.Statements[first].SQL, partitionedIndexRebuildDetail)) + } + return DesiredResult{Plan: report}.refused(copySwapNotEnabledRefusal(), fmt.Sprintf( + "planned statement %d (%s) routes to copy-and-swap, which is not enabled for this run: %s", + first+1, report.Statements[first].SQL, copySwapNotEnabledDetail)) +} diff --git a/pkg/migrate/partitioned_parent_retype_integration_test.go b/pkg/migrate/partitioned_parent_retype_integration_test.go index 4aa9fc81a..b42f0868d 100644 --- a/pkg/migrate/partitioned_parent_retype_integration_test.go +++ b/pkg/migrate/partitioned_parent_retype_integration_test.go @@ -13,6 +13,7 @@ import ( "github.com/block/pg-sprite/pkg/migrate" "github.com/block/pg-sprite/pkg/plan" "github.com/block/pg-sprite/pkg/planner" + "github.com/block/pg-sprite/pkg/preflight" "github.com/block/pg-sprite/pkg/schemadiff" "github.com/block/pg-sprite/pkg/verdict" ) @@ -84,8 +85,11 @@ func TestRunRelabelsAParentColumnNoPartitionedIndexReads(t *testing.T) { // Widening a column a partitioned index reads would rebuild every // partition's index under ACCESS EXCLUSIVE on the whole tree, so it is not a // relabel: the planner routes it to copy-and-swap, which the run does not -// open, and Run refuses it with nothing executed. The partitions' indexes -// keep their filenodes and the column keeps its type. +// open, and Run refuses it with nothing executed. Opening the route would +// not run it, since copy-and-swap does not take a partitioned parent, so +// the refusal's cause is partitioned-index-rebuild, not the closed route's +// copy-and-swap-not-enabled. The partitions' indexes keep their filenodes +// and the column keeps its type. func TestRunRefusesAParentRetypeThatWouldRebuildEveryPartitionIndex(t *testing.T) { pool, schema := retypeOrders(t) before := indexFilenode(t, pool, schema, "orders_2026_note_idx") @@ -95,11 +99,72 @@ func TestRunRefusesAParentRetypeThatWouldRebuildEveryPartitionIndex(t *testing.T require.NoError(t, err, "a refusal returns no error") assert.Equal(t, verdict.OutcomeRefused, v.Outcome) assert.Equal(t, verdict.ReasonCopyAndSwapRefused, v.Reason) - assert.Equal(t, verdict.CauseCopyAndSwapNotEnabled, v.Cause, "a run that has not opened copy-and-swap stops at its gate") + assert.Equal(t, verdict.ClassCapabilityBoundary, v.Class) + assert.Equal(t, verdict.CausePartitionedIndexRebuild, v.Cause, "the partitioned index, not the closed route, is what stops the change") assert.Equal(t, before, indexFilenode(t, pool, schema, "orders_2026_note_idx"), "no partition index was rebuilt") assert.Equal(t, "character varying(10)", columnTypeOf(t, pool, schema, "orders_2026", "note")) } +// With the route opened, the same widening reaches copy-and-swap's +// preflight, which refuses the partitioned parent before it builds +// anything: the refusal the narrowed cause above tells the operator not to +// walk into. Nothing is rebuilt. +func TestRunRefusesAParentRetypeThatWouldRebuildEveryPartitionIndexWithCopySwapOpened(t *testing.T) { + pool, schema := retypeOrders(t) + before := indexFilenode(t, pool, schema, "orders_2026_note_idx") + st := parseOne(t, fmt.Sprintf(`ALTER TABLE %s.orders ALTER COLUMN note TYPE varchar(20)`, schema)) + + v, err := migrate.Run(t.Context(), pool, st, copySwapRunOptions(pool.Config().ConnString(), schema+".orders")) + require.NoError(t, err, "a refusal returns no error") + assert.Equal(t, verdict.OutcomeRefused, v.Outcome) + assert.Equal(t, verdict.ReasonCopyAndSwapRefused, v.Reason) + assert.Equal(t, verdict.Cause(preflight.CopySwapCausePartitioned), v.Cause) + assert.Equal(t, before, indexFilenode(t, pool, schema, "orders_2026_note_idx"), "no partition index was rebuilt") + assert.Equal(t, "character varying(10)", columnTypeOf(t, pool, schema, "orders_2026", "note")) +} + +// A retype that rewrites the column on any table routes to copy-and-swap +// whether or not an index reads it, and dropping an index would not run it, +// so the closed route keeps its own cause: integer to bigint on a plain +// table's indexed column, and bigint to numeric on the partitioned parent's +// id, which its partitioned primary key reads. +func TestRunKeepsTheClosedRouteCauseForARetypeThatRewrites(t *testing.T) { + t.Run("plain table", func(t *testing.T) { + url := testutil.NewDatabase(t, testutil.StartPostgres(t)) + pool, err := dbconn.NewPool(t.Context(), dbconn.Config{URL: url}) + require.NoError(t, err) + t.Cleanup(pool.Close) + schema := testutil.NewSchema(t, pool) + _, err = pool.Exec(t.Context(), fmt.Sprintf(` + CREATE TABLE %[1]s.items ( + id bigint PRIMARY KEY, + qty integer NOT NULL + ); + CREATE INDEX items_qty_idx ON %[1]s.items (qty)`, schema)) + require.NoError(t, err) + st := parseOne(t, fmt.Sprintf(`ALTER TABLE %s.items ALTER COLUMN qty TYPE bigint`, schema)) + + v, err := migrate.Run(t.Context(), pool, st, runOptions()) + require.NoError(t, err) + assert.Equal(t, verdict.OutcomeRefused, v.Outcome) + assert.Equal(t, verdict.ReasonCopyAndSwapRefused, v.Reason) + assert.Equal(t, verdict.CauseCopyAndSwapNotEnabled, v.Cause) + assert.Equal(t, "integer", columnTypeOf(t, pool, schema, "items", "qty")) + }) + + t.Run("partitioned parent", func(t *testing.T) { + pool, schema := retypeOrders(t) + st := parseOne(t, fmt.Sprintf(`ALTER TABLE %s.orders ALTER COLUMN id TYPE numeric`, schema)) + + v, err := migrate.Run(t.Context(), pool, st, runOptions()) + require.NoError(t, err) + assert.Equal(t, verdict.OutcomeRefused, v.Outcome) + assert.Equal(t, verdict.ReasonCopyAndSwapRefused, v.Reason) + assert.Equal(t, verdict.CauseCopyAndSwapNotEnabled, v.Cause) + assert.Equal(t, "bigint", columnTypeOf(t, pool, schema, "orders_2026", "id")) + }) +} + // The desired-state door reads the same fact: a desired file that widens the // unindexed column converges natively, and one that widens the indexed // column is refused with nothing executed. @@ -136,6 +201,7 @@ CREATE INDEX orders_note_idx ON orders USING btree (note);`, label, note) }, runOptions()) require.NoError(t, err) assert.Equal(t, verdict.OutcomeRefused, res.Outcome) + assert.Equal(t, verdict.CausePartitionedIndexRebuild, res.Cause) assert.Equal(t, before, indexFilenode(t, pool, schema, "orders_2027_note_idx"), "no partition index was rebuilt") assert.Equal(t, "character varying(10)", columnTypeOf(t, pool, schema, "orders_2027", "note")) }) diff --git a/pkg/migrate/refusal_registry.go b/pkg/migrate/refusal_registry.go index 17e39b3a7..065ad461e 100644 --- a/pkg/migrate/refusal_registry.go +++ b/pkg/migrate/refusal_registry.go @@ -150,6 +150,7 @@ func siteRefusals() []siteRefusal { {"declarative-foreign-key/undeclarable", plan.UndeclarableForeignKeyRefusal()}, {"plan-incoherent", planIncoherentRefusal()}, {"copy-and-swap-not-enabled", copySwapNotEnabledRefusal()}, + {"partitioned-index-rebuild", partitionedIndexRebuildRefusal()}, {"copy-and-swap-run-stopped", copySwapRunStoppedRefusal()}, {"row-security-unsupported", rowSecurityUnsupportedRefusal()}, {"row-security-missing-table", plan.RowSecurityMissingTableRefusal()}, diff --git a/pkg/planner/planner.go b/pkg/planner/planner.go index bcecc4e9a..3400cc211 100644 --- a/pkg/planner/planner.go +++ b/pkg/planner/planner.go @@ -537,6 +537,16 @@ type Decision struct { // only for alter-column-type decisions. statement.StepTypeFit reads it to // list the live values the new type cannot hold. LiveType string `json:"live_type,omitempty"` + // RebuildsPartitionedIndexes marks an ALTER COLUMN TYPE on a + // partitioned parent that PostgreSQL would relabel in place on a plain + // table and that the planner routes to the rewrite only because a + // partitioned index reads the column, so the change would rebuild every + // partition's attached index under ACCESS EXCLUSIVE on the whole tree. + // The change runs once no partitioned index reads the column, so a + // front door's refusal can name dropping the index first. It is + // in-process only and not part of the plan-report contract: a decoded + // plan reads false, and its refusal names the route instead. + RebuildsPartitionedIndexes bool `json:"-"` // ReplicatingPublications names the publications that send the change // on to logical replication, each rendered "publication" with its // identifier quoted, when the operation adds a column they send or @@ -1947,6 +1957,7 @@ func classifyOp(op statement.Op, st statement.Statement, facts Facts, sql string case statement.OpAlterColumnType: d.Route, d.Reason, d.Unverified = classifyTypeChange(op, facts) d.LiveType = facts.ColumnTypes[op.Column] + d.RebuildsPartitionedIndexes = rebuildsPartitionedIndexes(op, facts) if swapsTimeZone(op, facts) { d.ReadsInTimeZone = facts.SessionTimeZone } @@ -2251,6 +2262,22 @@ func classifyRelabel(op statement.Op, facts Facts) (Route, Reason, bool) { return RouteNative, ReasonBinaryCoercible, false } +// rebuildsPartitionedIndexes reports whether op is a type change on a +// partitioned parent that a partitioned index reads and that, classified +// against the same facts as a plain table's, would relabel in place: the +// partitioned index is then the one thing that routes it to the rewrite +// (classifyRelabel). A change that rewrites the column on a plain table too, +// or one a fact was missing to prove, is not one. +func rebuildsPartitionedIndexes(op statement.Op, facts Facts) bool { + if facts.Storage != StoragePartitionedParent || !facts.PartitionedIndexColumns[op.Column] { + return false + } + plain := facts + plain.Storage = StorageHeap + route, _, unverified := classifyTypeChange(op, plain) + return route == RouteNative && !unverified +} + // classifyTimeZoneSwap classifies a change between timestamp and // timestamptz. PostgreSQL reads each stored value in the session time // zone, and keeps the stored bytes only when that zone is UTC: in any diff --git a/pkg/planner/planner_test.go b/pkg/planner/planner_test.go index a2253b046..004925da2 100644 --- a/pkg/planner/planner_test.go +++ b/pkg/planner/planner_test.go @@ -144,7 +144,10 @@ func TestClassifySetTablespaceOnAPartitionedParentRefusesATablespaceItCannotName // index that reads the column, so only a parent whose partitioned indexes // were read and do not read the column keeps the native route. A parent // whose partitioned indexes were not read fails closed, marked unverified, -// and a heap table never consults the fact. +// and a heap table never consults the fact. Only the first case, a relabel +// the partitioned index alone sends to the rewrite, is marked +// RebuildsPartitionedIndexes; a change that rewrites the column anyway, from +// text to a bounded varchar, is not. func TestClassifyRelabelOnAPartitionedParent(t *testing.T) { const alter = "ALTER TABLE orders ALTER COLUMN note TYPE varchar(20)" types := map[string]string{"note": "character varying(10)"} @@ -153,30 +156,36 @@ func TestClassifyRelabelOnAPartitionedParent(t *testing.T) { route planner.Route reason planner.Reason unverified bool + rebuilds bool }{ "a partitioned index reads the column": { planner.Facts{ColumnTypes: types, Storage: planner.StoragePartitionedParent, PartitionedIndexColumns: map[string]bool{"note": true}}, - planner.RouteCopyAndSwap, planner.ReasonTypeRewrite, false, + planner.RouteCopyAndSwap, planner.ReasonTypeRewrite, false, true, + }, + "a partitioned index reads a column the change rewrites anyway": { + planner.Facts{ColumnTypes: map[string]string{"note": "text"}, Storage: planner.StoragePartitionedParent, + PartitionedIndexColumns: map[string]bool{"note": true}}, + planner.RouteCopyAndSwap, planner.ReasonTypeRewrite, false, false, }, "a partitioned index reads another column": { planner.Facts{ColumnTypes: types, Storage: planner.StoragePartitionedParent, PartitionedIndexColumns: map[string]bool{"id": true}}, - planner.RouteNative, planner.ReasonBinaryCoercible, false, + planner.RouteNative, planner.ReasonBinaryCoercible, false, false, }, "no partitioned index": { planner.Facts{ColumnTypes: types, Storage: planner.StoragePartitionedParent, PartitionedIndexColumns: map[string]bool{}}, - planner.RouteNative, planner.ReasonBinaryCoercible, false, + planner.RouteNative, planner.ReasonBinaryCoercible, false, false, }, "the partitioned indexes were not read": { planner.Facts{ColumnTypes: types, Storage: planner.StoragePartitionedParent}, - planner.RouteCopyAndSwap, planner.ReasonTypeRewrite, true, + planner.RouteCopyAndSwap, planner.ReasonTypeRewrite, true, false, }, "a heap table ignores the partitioned fact": { planner.Facts{ColumnTypes: types, Storage: planner.StorageHeap, PartitionedIndexColumns: map[string]bool{"note": true}}, - planner.RouteNative, planner.ReasonBinaryCoercible, false, + planner.RouteNative, planner.ReasonBinaryCoercible, false, false, }, } { t.Run(name, func(t *testing.T) { @@ -187,6 +196,7 @@ func TestClassifyRelabelOnAPartitionedParent(t *testing.T) { assert.Equal(t, tc.route, d.Route) assert.Equal(t, tc.reason, d.Reason) assert.Equal(t, tc.unverified, d.Unverified) + assert.Equal(t, tc.rebuilds, d.RebuildsPartitionedIndexes) }) } } diff --git a/pkg/verdict/verdict.go b/pkg/verdict/verdict.go index 026b79c21..c8f38ab7c 100644 --- a/pkg/verdict/verdict.go +++ b/pkg/verdict/verdict.go @@ -512,6 +512,16 @@ const ( // statement again, or discarded by a copy-and-swap run started over // under the restart acknowledgement. CauseCopyAndSwapRunStopped Cause = "copy-and-swap-run-stopped" + // CausePartitionedIndexRebuild: under ReasonCopyAndSwapRefused, the + // statement retypes a column of a partitioned parent that a + // partitioned index reads, a change PostgreSQL relabels in place on a + // plain table but that here rebuilds every partition's attached index + // under ACCESS EXCLUSIVE on the whole tree, so it routes to + // copy-and-swap, which the run has not opened and which does not take + // a partitioned parent either; nothing was executed. Opening the route + // does not run it: dropping the index in a run of its own, retyping the + // column, and recreating the index does. + CausePartitionedIndexRebuild Cause = "partitioned-index-rebuild" // CauseSlotLagStreamBehind narrows a failed slot-lag-exceeded verdict: // the WAL the run's stream had yet to confirm was over the ceiling, so // the stream fell behind the source's writes. The slot keeps that WAL, diff --git a/pkg/verdict/verdict_test.go b/pkg/verdict/verdict_test.go index c607ae074..061ca33da 100644 --- a/pkg/verdict/verdict_test.go +++ b/pkg/verdict/verdict_test.go @@ -378,6 +378,7 @@ func TestReasonAndCauseTokensAreFlat(t *testing.T) { string(CauseParentIndexAdoption), string(CauseParentNotValidForeignKey), string(CauseParentConcurrentIndexDrop), string(CauseCopyAndSwapNotEnabled), string(CauseCopyAndSwapRunStopped), + string(CausePartitionedIndexRebuild), string(CauseSlotLagStreamBehind), string(CauseSlotLagWALRetained), string(CauseSlotLagWALRetainedHardLimit), string(CauseChangedForeignKey), string(CauseColumnFirstForeignKey), string(CauseUndeclarableForeignKey), From 44f93742dcbe949d63d11ac22cb7a4d72fc070d1 Mon Sep 17 00:00:00 2001 From: Kiran Muddukrishna Date: Thu, 3 Dec 2026 07:52:49 +0530 Subject: [PATCH 2/2] test(migrate): size the retype fixture's pool for copy-and-swap The test that opens the copy-and-swap route reached its pool-size check on CI runners whose default pool holds 4 connections, not the 6 it needs. --- pkg/migrate/partitioned_parent_retype_integration_test.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pkg/migrate/partitioned_parent_retype_integration_test.go b/pkg/migrate/partitioned_parent_retype_integration_test.go index b42f0868d..6da37e4f2 100644 --- a/pkg/migrate/partitioned_parent_retype_integration_test.go +++ b/pkg/migrate/partitioned_parent_retype_integration_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/block/pg-sprite/internal/testutil" + "github.com/block/pg-sprite/pkg/copier" "github.com/block/pg-sprite/pkg/dbconn" "github.com/block/pg-sprite/pkg/migrate" "github.com/block/pg-sprite/pkg/plan" @@ -24,7 +25,10 @@ import ( func retypeOrders(t *testing.T) (*pgxpool.Pool, string) { t.Helper() url := testutil.NewDatabase(t, testutil.StartPostgres(t)) - pool, err := dbconn.NewPool(t.Context(), dbconn.Config{URL: url}) + // The pool holds every session copy-and-swap needs, so a run with the + // route opened reaches its preflight on a runner with few CPUs, where + // the default pool is smaller. + pool, err := dbconn.NewPool(t.Context(), dbconn.Config{URL: url, MaxConnsFloor: migrate.CopySwapMinConns(copier.Options{})}) require.NoError(t, err) t.Cleanup(pool.Close) schema := testutil.NewSchema(t, pool)