diff --git a/CHANGELOG.md b/CHANGELOG.md index e23c65a..0f251b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -165,6 +165,20 @@ Both mirrors run the command through one implementation, so it does not depend o event loop being able to spawn processes — a hook that works in production works on a developer's machine too. +### What a plan will lock + +Every operation now serializes its `capabilities` — the heaviest lock it takes and on +what, and whether it can run inside a transaction block — and `is_destructive` beside its +fields. They were on the object before and not in the dump, which meant a plan written to +a file lost the one thing a DBA reads before agreeing to a window. Both are computed on +the way out and ignored on the way in, so the round trip holds. `plan --locks` prints the +same for a person. + +There is deliberately no `--sql`. The DDL is built at execution time from decisions only +made then — a concurrent detach falling back to the blocking form, rows moved out of a +DEFAULT partition, an orphan marker cleared — and a rendering without them would be +read as a transcript in exactly the cases a review exists to catch. + ### Monitoring, for free `--output metrics` renders any command as Prometheus text exposition for a node_exporter diff --git a/docs/agents.md b/docs/agents.md index fe435e5..1a3cc1d 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -63,7 +63,8 @@ A configuration is a **scheme** — the shape of the tree, level by level — an nothing pending, 2 drift under `plan --check`, 3 findings or run issues, 4 configuration, 5 connection, 6 lock held, 1 unexpected. `--output json` is the model dump under a versioned envelope; `--output metrics` is Prometheus text exposition for a node_exporter - textfile, all gauges, prefixed `pg_partsmith_`. See `guide/cli.md`. + textfile, all gauges, prefixed `pg_partsmith_`; `plan --locks` prints the heaviest lock + each operation takes. There is deliberately no `--sql`. See `guide/cli.md`. * `CommandHooks` (both mirrors) runs a configured command per phase with the `PartitionEvent` as JSON on stdin; a non-zero exit refuses the operation. In a document it is the `hooks` section, honoured only under `apply --allow-hooks`. Hooks never fire @@ -278,6 +279,10 @@ On a `MaintenancePlan`: `.operations`, `.findings`, `.cursors`, `.generated_at`, `.only(*kinds)`, `.without(*kinds)`, `.describe()`. Filtering a plan and applying the rest is supported and is how you split creation from pruning across schedules. +Every operation dumps its `capabilities` (the heaviest lock it takes, and whether it can +run in a transaction block) and `is_destructive` beside its fields; both are computed on the +way out and ignored on the way in, so the round trip holds. + Serialize a plan with `model_dump_json(by_alias=True)` — the same vocabulary a configuration uses (`kind`, `method`, `schema`) — and read it back with `MaintenancePlan.model_validate_json`. `apply()` refuses a plan made for another table, or diff --git a/docs/guide/cli.md b/docs/guide/cli.md index 7ea1e35..b8cecca 100644 --- a/docs/guide/cli.md +++ b/docs/guide/cli.md @@ -102,6 +102,41 @@ versioned envelope, in the vocabulary a configuration file is written in: It is the dump, never a shape assembled by the CLI — a hand-rolled one drifts from the library the first time a field is added. Logs go to stderr, so stdout stays parseable. +## What will it lock + +```bash +pg-partsmith plan -c partitions.yaml --locks +``` + +``` +plan for public.events at 2026-09-01T02:15:00+00:00 + CREATE public.events__2026_10 (create_ahead) + DETACH public.events__2025_08 (retention_expired) size=1073741824 rows~4021553 + DROP public.events__2025_08 (follows_detach) +locks: + CREATE public.events__2026_10 + ACCESS SHARE on the template during CREATE; SHARE UPDATE EXCLUSIVE on the parent and ACCESS EXCLUSIVE on the new partition (and on a DEFAULT sibling) during ATTACH; SHARE ROW EXCLUSIVE on every table referencing the parent through a foreign key + DETACH public.events__2025_08 (outside a transaction block) + SHARE UPDATE EXCLUSIVE on the parent (CONCURRENTLY), ACCESS EXCLUSIVE on the partition and, in the second transaction, on every table referencing the parent through a foreign key; ... + DROP public.events__2025_08 + ACCESS EXCLUSIVE on the dropped table only +``` + +The heaviest lock each operation takes, and on what, as measured on PostgreSQL 15 and 17 +— the thing a DBA reads before agreeing to a window. An operation that cannot run inside a +transaction block is marked, because it is the one a crash leaves half-done and the next +run completes. The JSON carries the same under each operation's `capabilities`, and +`is_destructive` beside it, whether or not `--locks` was asked for; a saved plan is +therefore reviewable for its locks without the CLI. + +**Why there is no `--sql`.** Printing the statements would be the obvious next thing, and +it is deliberately not offered. The DDL is built at execution time from decisions that are +only made then — whether a `DETACH CONCURRENTLY` has to fall back to the blocking form +because a DEFAULT sibling exists, how rows a DEFAULT partition holds for a new window get +moved, which orphan marker gets cleared — and a rendering that left those out would be +read as a transcript in exactly the cases a review exists to catch. The plan is the +contract: what, why, how big, what it locks. + ## Monitoring, for free `--output metrics` renders the same run as Prometheus text exposition, for a node_exporter diff --git a/docs/guide/container.md b/docs/guide/container.md index b1e263d..7618a69 100644 --- a/docs/guide/container.md +++ b/docs/guide/container.md @@ -101,8 +101,8 @@ Two things worth knowing before you point it at production: while planning. It is read-only, but it is your statement running with these credentials. - **`apply` takes locks.** Every operation in a plan reports the heaviest lock it takes; - `plan --output json` carries that per operation, which is the thing to read before - scheduling a window. + `plan --locks` prints it and `plan --output json` carries it per operation under + `capabilities`, which is the thing to read before scheduling a window. ## Tags diff --git a/pg_partsmith/cli/commands.py b/pg_partsmith/cli/commands.py index e447e5d..7654104 100644 --- a/pg_partsmith/cli/commands.py +++ b/pg_partsmith/cli/commands.py @@ -19,7 +19,7 @@ from .exit_codes import ExitCode from .loader import ConfigError from .metrics import render_metrics -from .render import describe_tree, envelope, plan_entry, to_json, tree_entry +from .render import describe_locks, describe_tree, envelope, plan_entry, to_json, tree_entry if TYPE_CHECKING: from collections.abc import Sequence @@ -80,12 +80,18 @@ async def run_inspect(kit: PartitionToolkit, configs: Sequence[TablePartitionCon return CommandResult(code=code, lines=blocks, payload=envelope("inspect", entries)) -async def run_plan(kit: PartitionToolkit, configs: Sequence[TablePartitionConfig], *, check: bool) -> CommandResult: +async def run_plan( + kit: PartitionToolkit, configs: Sequence[TablePartitionConfig], *, check: bool, locks: bool = False +) -> CommandResult: """Plan every selected table, and issue no DDL doing it. With ``check``, pending operations are drift and are exited on, which is what lets an alert say "maintenance has not been running". A finding outranks that: drift is what a run fixes, a finding is what it cannot. + + With ``locks``, each operation is followed by the heaviest lock it takes + and on what -- the thing a DBA reads before agreeing to a window. The JSON + carries the same under ``capabilities`` whether or not it was asked for. """ blocks: list[str] = [] entries: list[dict[str, Any]] = [] @@ -94,7 +100,7 @@ async def run_plan(kit: PartitionToolkit, configs: Sequence[TablePartitionConfig for config in configs: plan = await kit.service.plan(config) entries.append(plan_entry(plan)) - blocks.append(plan.describe()) + blocks.append(plan.describe() + ("\n" + describe_locks(plan) if locks else "")) drift = drift or not plan.is_noop findings = findings or bool(plan.actionable_findings) diff --git a/pg_partsmith/cli/main.py b/pg_partsmith/cli/main.py index ada4f98..c7f5a99 100644 --- a/pg_partsmith/cli/main.py +++ b/pg_partsmith/cli/main.py @@ -82,6 +82,11 @@ def build_parser() -> argparse.ArgumentParser: default=None, help="write the plan to FILE, for review and for `apply --plan FILE`", ) + sub.add_argument( + "--locks", + action="store_true", + help="after each operation, the heaviest lock it takes and on what", + ) if name == "apply": _add_apply_arguments(sub) @@ -138,7 +143,7 @@ async def _run(args: argparse.Namespace) -> CommandResult: if args.command == "inspect": return await run_inspect(kit, configs) if args.command == "plan": - result = await run_plan(kit, configs, check=args.check) + result = await run_plan(kit, configs, check=args.check, locks=args.locks) if args.save: _save_plan(Path(args.save), result) return result diff --git a/pg_partsmith/cli/render.py b/pg_partsmith/cli/render.py index e19207c..48c85e3 100644 --- a/pg_partsmith/cli/render.py +++ b/pg_partsmith/cli/render.py @@ -17,7 +17,7 @@ from pg_partsmith.plan import MaintenancePlan from pg_partsmith.topology import ActualTree, PartitionNode -__all__ = ["OUTPUT_VERSION", "describe_tree", "envelope", "plan_entry", "to_json", "tree_entry"] +__all__ = ["OUTPUT_VERSION", "describe_locks", "describe_tree", "envelope", "plan_entry", "to_json", "tree_entry"] OUTPUT_VERSION = 1 """Schema version of the JSON envelope, so a reader can tell what it is holding.""" @@ -59,6 +59,24 @@ def tree_entry(table_name: str, tree: ActualTree | None) -> dict[str, Any]: } +def describe_locks(plan: MaintenancePlan) -> str: + """What each operation will lock, which is what a window is scheduled around. + + One line per top-level operation. A subtree is built detached and attached + once, so its children take nothing the parent's line does not already say. + An operation that cannot run in a transaction block says so: it is the one + a crash leaves half-done, and the next run completes. + """ + if plan.is_noop: + return "locks: none, nothing to do" + lines = ["locks:"] + for op in plan.operations: + transactional = "" if op.capabilities.transactional else " (outside a transaction block)" + lines.append(f" {op.kind.value.upper()} {op.target}{transactional}") + lines.append(f" {op.capabilities.lock}") + return "\n".join(lines) + + def describe_tree(tree: ActualTree) -> str: """Render a tree the way a person reads one: indented, bounds on each line.""" lines = [f"{tree.root.name} — {tree.root.describe_topology()}"] diff --git a/pg_partsmith/plan.py b/pg_partsmith/plan.py index 3306219..44be1ff 100644 --- a/pg_partsmith/plan.py +++ b/pg_partsmith/plan.py @@ -18,7 +18,7 @@ from enum import StrEnum from typing import TYPE_CHECKING, Annotated, Literal -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, computed_field from .exceptions import PlanConfigMismatchError from .lifecycle import DetachMode @@ -294,11 +294,17 @@ def kind(self) -> OperationKind: """The DDL family.""" raise NotImplementedError + # Serialized, not only computed: the lock an operation takes is what an + # operator reads before scheduling a window, and a plan written to a file + # is exactly the plan they read it off. Each subclass overrides the + # property; the dump takes the override. + @computed_field # type: ignore[prop-decorator] @property def capabilities(self) -> OperationCapabilities: """How the operation may be executed.""" raise NotImplementedError + @computed_field # type: ignore[prop-decorator] @property def is_destructive(self) -> bool: """True for operations that remove a partition from service.""" diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index c7ef2ae..cf4e85f 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -24,13 +24,15 @@ select_configs, ) from pg_partsmith.cli.main import _hooks as _cli_hooks -from pg_partsmith.cli.render import envelope, plan_entry +from pg_partsmith.cli.render import describe_locks, envelope, plan_entry from pg_partsmith.document import PartitionsDocument from pg_partsmith.entities import MaintenanceIssue, MaintenanceIssueStep, MaintenanceResult from pg_partsmith.events import HookPhase from pg_partsmith.exceptions import InvalidPartitionConfigError +from pg_partsmith.lifecycle import DetachMode from pg_partsmith.plan import ( CreatePartition, + DetachPartition, DropPartition, Finding, FindingReason, @@ -501,3 +503,59 @@ def test__hooks__allowed__are_built_from_the_document(tmp_path: Path) -> None: # Assert assert hooks is not None assert hooks[0].phases == (HookPhase.BEFORE_DROP,) + + +# ── What a plan will lock ─────────────────────────────────────────────────────── + + +def test__describe_locks__names_the_heaviest_lock_of_every_top_level_operation() -> None: + # Arrange + plan = _destructive_plan() + + # Act + lines = describe_locks(plan).splitlines() + + # Assert: one header line per operation, its lock on the next + assert lines[0] == "locks:" + assert lines[1].startswith(" CREATE public.events__2026_09") + assert "SHARE UPDATE EXCLUSIVE on the parent" in lines[2] + assert lines[3].startswith(" DROP public.events__2025_08") + assert "ACCESS EXCLUSIVE on the dropped table only" in lines[4] + + +def test__describe_locks__an_operation_that_cannot_run_in_a_transaction__says_so() -> None: + # The one a crash leaves half-done, which is worth knowing before a window. + plan = MaintenancePlan( + table_name="public.events", + generated_at=NOW, + operations=( + DetachPartition( + target="public.events__2025_08", + parent_name="public.events", + reason=Reason.RETENTION_EXPIRED, + mode=DetachMode.CONCURRENT, + ), + ), + ) + + # Act / Assert + assert "(outside a transaction block)" in describe_locks(plan).splitlines()[1] + + +def test__describe_locks__a_converged_table__has_nothing_to_lock() -> None: + # Arrange / Act / Assert + assert describe_locks(_plan(noop=True)) == "locks: none, nothing to do" + + +async def test__plan__locks__are_printed_after_the_operations_only_when_asked() -> None: + # Arrange + kit = _kit(_plan()) + + # Act + without = (await run_plan(kit, _configs(), check=False)).render(output="human") + with_locks = (await run_plan(kit, _configs(), check=False, locks=True)).render(output="human") + + # Assert + assert "locks:" not in without + assert "locks:" in with_locks + assert "SHARE UPDATE EXCLUSIVE" in with_locks diff --git a/tests/unit/test_plan.py b/tests/unit/test_plan.py index bfe68d5..e57e513 100644 --- a/tests/unit/test_plan.py +++ b/tests/unit/test_plan.py @@ -699,3 +699,23 @@ def test__validate_plan_for_config__plan_without_a_fingerprint__is_checked_for_i validate_plan_for_config(_config(), plan) with pytest.raises(PlanConfigMismatchError): validate_plan_for_config(_config(schema="archive"), plan) + + +def test__model_dump__carries_the_lock_each_operation_takes() -> None: + # A plan written to a file is what an operator reads before agreeing to a + # window, so what each operation locks is in the dump, not only on the object. + dumped = json.loads(FULL_PLAN.model_dump_json(by_alias=True)) + + # Assert + by_kind = {op["kind"]: op for op in dumped["operations"]} + assert "ACCESS EXCLUSIVE on the dropped table only" in by_kind["drop"]["capabilities"]["lock"] + assert by_kind["detach"]["capabilities"]["transactional"] is False + assert by_kind["drop"]["is_destructive"] is True + assert by_kind["create"]["is_destructive"] is False + # and a subtree member says so as well + assert "capabilities" in by_kind["create"]["children"][0] + + +def test__model_validate__a_dump_carrying_capabilities__reads_back_as_the_same_plan() -> None: + # Computed on the way out, ignored on the way in: the round trip holds. + assert MaintenancePlan.model_validate_json(FULL_PLAN.model_dump_json(by_alias=True)) == FULL_PLAN