diff --git a/CHANGELOG.md b/CHANGELOG.md index 9880f29..5f16e50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -145,6 +145,26 @@ reads it back. Both guards from earlier in this release apply to it: a plan made another table, or under a configuration that has since been edited, is refused with exit `4` unless `--allow-config-drift` is passed. +### Commands around the lifecycle + +`CommandHooks` runs a configured command at each lifecycle phase, handing it the +`PartitionEvent` as JSON on stdin and treating a non-zero exit exactly as a raised +exception. It needed no new context: the event has been one pydantic model for every phase +since earlier in this release, so the payload is a dump of the object a Python hook already +receives. In a document it is a `hooks` section, and it is what makes the destructive half +usable by a team that does not write Python — they own the archiver already, they only +need it invoked at the right moment. + +The commands run only when the run is told to run them (`apply --allow-hooks`), and a +document declaring hooks is refused rather than quietly stripped when it is not: silently +skipping a configured `before_drop` would let an operator read the file, believe their +archiver ran, and be wrong. No sandbox is provided and none is claimed; the container +boundary is the answer if isolation is wanted. + +Both mirrors run the command through one implementation, so it does not depend on the +event loop being able to spawn processes — a hook that works in production works on a +developer's machine too. + ### A container image `ghcr.io/bedrock-python/pg-partsmith:`, published from the release workflow, so a diff --git a/README.md b/README.md index 2ffe007..8e73a24 100644 --- a/README.md +++ b/README.md @@ -49,8 +49,8 @@ serialize, filter and apply. No extension, no superuser, no scheduler of its own a CronJob and a CI step can read - **A container image** — `ghcr.io/bedrock-python/pg-partsmith`, for stacks with no Python in them -- **Hooks, locks, schemas** — six lifecycle hooks; PostgreSQL advisory or Redis locks; - schema-qualified everything +- **Hooks, locks, schemas** — eight lifecycle hooks, in Python or as commands named in a + config file; PostgreSQL advisory or Redis locks; schema-qualified everything - **Type-safe, tested** — Pydantic models, full mypy, real PostgreSQL 15, 16 and 17 via testcontainers ## Installation diff --git a/docs/agents.md b/docs/agents.md index c83bbb0..043b50b 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -63,6 +63,10 @@ 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. 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 + during `plan`. See `guide/hooks-in-config.md`. * The same CLI ships as `ghcr.io/bedrock-python/pg-partsmith:` with the command as its entrypoint; tags are the exact version and a moving minor, never `latest`. See `guide/container.md`. diff --git a/docs/guide/cli.md b/docs/guide/cli.md index 6224150..dd5d933 100644 --- a/docs/guide/cli.md +++ b/docs/guide/cli.md @@ -156,6 +156,12 @@ fingerprint asks whether the plan is still the same intent: a plan made under `retention_count: 12` names exactly the right partitions to expire, for a reason that stopped being true the moment someone wrote `120`. +## Commands around the lifecycle + +A document can name a command to run before a drop, after a create, and at six other +moments. They fire during `apply` only, and only with `--allow-hooks` — see +[Commands around the lifecycle](hooks-in-config.md). + ## In a container The same commands, with nothing installed: diff --git a/docs/guide/hooks-in-config.md b/docs/guide/hooks-in-config.md new file mode 100644 index 0000000..cd22ce8 --- /dev/null +++ b/docs/guide/hooks-in-config.md @@ -0,0 +1,115 @@ +# Commands around the lifecycle + +Hooks are where the destructive half of this becomes usable: an operator who cannot run +anything before a `DROP` will not point a scheduled job at production. From +[a document](../reference/document.md), a hook is a command: + +```yaml +hooks: + timeout_seconds: 600 + before_drop: ["/usr/local/bin/archive-partition"] + after_create: ["/usr/local/bin/notify", "--channel", "#dba"] +``` + +```bash +pg-partsmith apply -c partitions.yaml --allow-destructive --allow-hooks +``` + +This is deliberately language-neutral. A Go or Ruby team already owns an archiver; what +they need is for it to be invoked at the right moment with the right metadata, not a +Python snippet. + +## What the command is handed + +The whole event, as JSON, on stdin — the same object a Python hook is given: + +```json +{ + "phase": "before_drop", + "config": { "schema": "public", "table_name": "events" }, + "partition": { "name": "public.events__2025_08", "oid": 40321, "bounds": { "kind": "range" } }, + "window": { "start": "2025-08-01T00:00:00+00:00", "end": "2025-09-01T00:00:00+00:00" }, + "operation": { "kind": "drop", "reason": "grace_elapsed", "size_bytes": 1073741824 } +} +``` + +Plus, for shell scripts that would rather not parse it: `PG_PARTSMITH_PHASE`, +`PG_PARTSMITH_TABLE`, `PG_PARTSMITH_PARTITION`, and `PG_PARTSMITH_WINDOW_START` / +`PG_PARTSMITH_WINDOW_END` when the partition covers a period. The rest of the environment +is inherited, because a hook needs its own credentials and its `PATH`. + +`before_drop` is told the window and the size even though `DETACH` has already cleared the +catalog's record of the bounds: what it gets is the window the planner decided the drop on. + +## The phases + +`before_create`, `after_create`, `before_attach`, `after_attach`, `before_detach`, +`after_detach`, `before_drop`, `after_drop`. Each takes one command. + +Hooks fire once per **lifecycle unit** — the partition directly under the root — never +once per leaf. For a `RANGE → HASH` table, `before_drop` runs once for the week, not once +per bucket. + +## A non-zero exit is a refusal + +Exactly as a raised exception is for a Python hook: the operation is abandoned and planned +again on the next run. A `before_drop` that exits non-zero leaves the partition detached +and undropped, which is what an archiver saying "not yet" should mean. + +By default one refusal aborts the whole run. `--continue-on-error` isolates it to its own +partition and lets the rest of the table be maintained; the failure comes back in the +run's issues, and the command exits `3`. + +A command that outlives `timeout_seconds` (default 300) is killed, and that counts as a +refusal. There is no "wait forever": a hook that hangs is holding the table's maintenance +lock. + +## Hooks never fire during `plan` + +`plan` issues no DDL and runs no hook. That is what makes a plan safe to compute anywhere, +and it is why the plan/apply split is worth having. + +One honest caveat in the other direction: **`plan` does run SQL you configured.** A +`SqlPredicate` in a retention rule is executed while planning. It is read-only, but it is +your statement, running with the credentials the run holds. + +## Why `--allow-hooks` exists + +Running a document's commands is arbitrary code execution in a process holding DDL +credentials. The honest framing: + +- The document **already** authorises dropping tables. A command in the same file is not a + new privilege boundary, as long as the document comes from the same trust domain as the + DSN. +- That stops being true the moment the document is assembled from somewhere less trusted — + a ConfigMap another team can edit, a templated file, anything user-supplied. + +So commands run only when the run is told to run them, and a document declaring hooks is +**refused** rather than quietly stripped when it is not: silently skipping a configured +`before_drop` would let an operator read the file, believe their archiver ran, and be +wrong. A hardened deployment can leave `--allow-hooks` off and prove nothing was executed. + +There is **no sandbox**, and none is claimed. If you need real isolation, the command is +the answer rather than a restricted namespace: put it in a sidecar or a mounted binary +with its own credentials, and let the container boundary be the boundary. + +## From Python + +The same class, without a document: + +```python +from pg_partsmith import HookPhase +from pg_partsmith.aio import CommandHooks, PartitionToolkit + +kit = PartitionToolkit.from_engine( + engine, + hooks=[CommandHooks({HookPhase.BEFORE_DROP: ["/usr/local/bin/archive-partition"]})], +) +``` + +`pg_partsmith.sync.CommandHooks` is the same thing on a sync engine. Both run the command +the same way, which does not depend on the event loop being able to spawn processes — so a +hook that works in production works on a developer's machine too. + +For anything that wants to stay inside Python, write an ordinary hook class instead — see +[Extend the library](extending.md). diff --git a/docs/reference/document.md b/docs/reference/document.md index b55edab..4b970c0 100644 --- a/docs/reference/document.md +++ b/docs/reference/document.md @@ -64,6 +64,7 @@ runtime: | `defaults` | mapping | `{}` | fields every table starts from | | `tables` | list | required, at least one | the tables to maintain | | `runtime` | mapping | library defaults | how the collaborators are wired | +| `hooks` | mapping | — | commands to run around the lifecycle; `apply --allow-hooks` only | A table entry takes the same fields as [`PartitionTableSettings`](settings.md) — the environment and the file are one field list, @@ -100,6 +101,12 @@ tables: - { table_name: audit, partition_column: at, granularity: day, retention_count: 400 } ``` +## Hooks + +`hooks` names a command to run at each lifecycle moment — see +[Commands around the lifecycle](../guide/hooks-in-config.md). They fire during `apply` +only, and the CLI refuses a document declaring them unless `--allow-hooks` is passed. + ## Building the wiring from it `PartitionToolkit.from_options(engine, document.runtime, hooks=[...])` is diff --git a/pg_partsmith/__init__.py b/pg_partsmith/__init__.py index fdf7ba0..77fdd55 100644 --- a/pg_partsmith/__init__.py +++ b/pg_partsmith/__init__.py @@ -13,7 +13,7 @@ UUIDv7BoundaryCodec, Window, ) -from .document import PartitionsDocument, PartitionTableSpec, ToolkitOptions +from .document import HookOptions, PartitionsDocument, PartitionTableSpec, ToolkitOptions from .entities import ( DefaultBounds, HashBounds, @@ -151,6 +151,7 @@ "ForeignLeaves", "HashBounds", "HashPartitioning", + "HookOptions", "HookPhase", "HourPeriodCalculator", "IntegerSequence", diff --git a/pg_partsmith/aio/__init__.py b/pg_partsmith/aio/__init__.py index 73b34f8..046e6cd 100644 --- a/pg_partsmith/aio/__init__.py +++ b/pg_partsmith/aio/__init__.py @@ -1,5 +1,6 @@ """Async implementations for partition management.""" +from .command_hooks import CommandHookError, CommandHooks from .hooks import BasePartitionLifecycleHooks, PartitionLifecycleHooks from .lock import PostgresAdvisoryLockManager, RedisDistributedLockManager from .maintainer import PartitionMaintainer, maintain_partitions @@ -17,6 +18,8 @@ __all__ = [ "BasePartitionLifecycleHooks", + "CommandHookError", + "CommandHooks", "LockManager", "PartitionInspector", "PartitionLifecycle", diff --git a/pg_partsmith/aio/command_hooks.py b/pg_partsmith/aio/command_hooks.py new file mode 100644 index 0000000..f723220 --- /dev/null +++ b/pg_partsmith/aio/command_hooks.py @@ -0,0 +1,116 @@ +"""Lifecycle hooks that run a command, for the stacks this library is not written in. + +A Go or Ruby team already owns an archiver; what they need is for it to be +invoked at the right moment with the right metadata. That is all this is: one +hook object that runs a configured command per phase, hands it the +:class:`~pg_partsmith.events.PartitionEvent` as JSON on stdin, and treats a +non-zero exit exactly as a raised exception -- the operation is aborted and +left for the next run. + +Nothing here needs a new context: the event is already a pydantic model, so the +payload the command reads is the same object a Python hook is handed, dumped +with ``by_alias=True``. + +Usage:: + + hooks = CommandHooks({HookPhase.BEFORE_DROP: ["/usr/local/bin/archive"]}) + service = PartitionLifecycleService(repo=repo, metadata=metadata, locks=locks, hooks=[hooks]) + +The command's stdout is logged. Its stderr is carried in the error when it +fails, which is the only place an operator will look at 03:00. +""" + +from __future__ import annotations + +import asyncio +import logging +from typing import TYPE_CHECKING + +from pg_partsmith.constants import DEFAULT_HOOK_TIMEOUT_SECONDS +from pg_partsmith.events import HookPhase, hook_environment +from pg_partsmith.hook_commands import CommandHookError, run_hook_command, tail + +from .hooks import BasePartitionLifecycleHooks + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + from pg_partsmith.events import PartitionEvent + +logger = logging.getLogger(__name__) + +__all__ = ["CommandHookError", "CommandHooks"] + + +class CommandHooks(BasePartitionLifecycleHooks): + """Runs one configured command per phase, with the event as JSON on stdin. + + Overrides :meth:`on_event` alone rather than one method per phase: the + phase is in the event, and a dispatch table reads better than eight + delegating methods that would each have to be added to again. The + per-phase methods come from the no-op base, which the executor calls after + this one. + """ + + def __init__( + self, + commands: Mapping[HookPhase, Sequence[str]], + *, + timeout_seconds: float = DEFAULT_HOOK_TIMEOUT_SECONDS, + ) -> None: + """Wire the commands. + + Args: + commands: The command to run at each phase, as an argument vector. + A vector rather than a string: nothing is passed through a + shell, so a partition name can never be read as syntax. + timeout_seconds: How long a command may take before it is killed and + the operation abandoned. A hook that hangs holds the table's + maintenance lock, so there is no "wait forever" option. + + Raises: + ValueError: If a command is empty, or its phase is not a hook phase. + """ + for phase, command in commands.items(): + if phase not in set(HookPhase): + msg = f"{phase!r} is not a hook phase; expected one of: {', '.join(p.value for p in HookPhase)}" + raise ValueError(msg) + if not command or not all(isinstance(part, str) for part in command): + msg = f"The {phase.value} command must be a non-empty list of strings" + raise ValueError(msg) + self._commands = {phase: tuple(command) for phase, command in commands.items()} + self._timeout = timeout_seconds + + @property + def phases(self) -> tuple[HookPhase, ...]: + """The phases a command is configured for, in declaration order.""" + return tuple(self._commands) + + async def on_event(self, event: PartitionEvent) -> None: + """Run the command configured for this event's phase, if there is one. + + Raises: + CommandHookError: If the command exits non-zero, cannot be run, or + outlives its timeout. A ``before_*`` hook failing this way + abandons the operation; an ``after_*`` one abandons what is left + of it, and the next run plans it again. + """ + command = self._commands.get(event.phase) + if command is None: + return + stdout = await asyncio.to_thread( + run_hook_command, + command, + event.model_dump_json(by_alias=True).encode(), + phase=event.phase, + partition_name=event.partition.name, + environment=hook_environment(event), + timeout_seconds=self._timeout, + ) + if stdout: + logger.info( + "%s hook said: %s", + event.phase.value, + tail(stdout), + extra={"partition_name": event.partition.name, "table_name": event.table_name}, + ) diff --git a/pg_partsmith/cli/main.py b/pg_partsmith/cli/main.py index 635f3d8..3b3f4b5 100644 --- a/pg_partsmith/cli/main.py +++ b/pg_partsmith/cli/main.py @@ -22,7 +22,7 @@ from sqlalchemy.ext.asyncio import create_async_engine from pg_partsmith.__version__ import __version__ -from pg_partsmith.aio import PartitionToolkit +from pg_partsmith.aio import CommandHooks, PartitionToolkit from pg_partsmith.exceptions import InvalidPartitionConfigError, LockAcquisitionError, PlanConfigMismatchError from .commands import CommandResult, run_apply, run_inspect, run_plan, run_validate @@ -41,6 +41,9 @@ if TYPE_CHECKING: from collections.abc import Sequence + from pg_partsmith.aio import PartitionLifecycleHooks + from pg_partsmith.document import PartitionsDocument + logger = logging.getLogger("pg_partsmith.cli") __all__ = ["build_parser", "main"] @@ -131,7 +134,7 @@ async def _run(args: argparse.Namespace) -> CommandResult: engine = create_async_engine(url) try: - kit = PartitionToolkit.from_options(engine, document.runtime) + kit = PartitionToolkit.from_options(engine, document.runtime, hooks=_hooks(document, args)) if args.command == "inspect": return await run_inspect(kit, configs) if args.command == "plan": @@ -153,6 +156,35 @@ async def _run(args: argparse.Namespace) -> CommandResult: await engine.dispose() +def _hooks(document: PartitionsDocument, args: argparse.Namespace) -> list[PartitionLifecycleHooks] | None: + """The hooks this run honours, and a refusal when it was not told to honour any. + + Hooks fire during ``apply`` alone, so nothing else has to decide. Ignoring a + configured ``before_drop`` silently would be the worst outcome available: an + operator would read the file, believe their archiver ran, and be wrong. So a + document declaring hooks is refused rather than quietly stripped. + + Raises: + ConfigError: If the document names hooks and ``--allow-hooks`` was not given. + """ + hooks = document.hooks + if hooks is None or hooks.is_empty: + return None + if args.command != "apply": + return None + if not getattr(args, "allow_hooks", False): + named = ", ".join(phase.value for phase in hooks.commands()) + msg = ( + f"This document runs commands ({named}). They execute in a process holding DDL credentials, " + "so they run only when asked for: pass --allow-hooks, or remove the hooks section." + ) + raise ConfigError(msg) + # Annotated as the protocol, not the class: a list is invariant, and the + # toolkit takes any hook implementation. + configured: list[PartitionLifecycleHooks] = [CommandHooks(hooks.commands(), timeout_seconds=hooks.timeout_seconds)] + return configured + + def _add_apply_arguments(parser: argparse.ArgumentParser) -> None: """What only ``apply`` takes, including the two that decide how much it may do.""" parser.add_argument( @@ -176,6 +208,11 @@ def _add_apply_arguments(parser: argparse.ArgumentParser) -> None: action="store_true", help="apply a saved plan whose configuration has changed since it was made", ) + parser.add_argument( + "--allow-hooks", + action="store_true", + help="run the commands the document's hooks section names; without it, a document declaring any is refused", + ) def _save_plan(path: Path, result: CommandResult) -> None: diff --git a/pg_partsmith/constants.py b/pg_partsmith/constants.py index cf1f3a3..7539313 100644 --- a/pg_partsmith/constants.py +++ b/pg_partsmith/constants.py @@ -30,6 +30,9 @@ # Hashed into advisory lock IDs / Redis keys; changing it breaks cross-version # mutual exclusion between deployments. +DEFAULT_HOOK_TIMEOUT_SECONDS = 300.0 +"""How long a configured command hook may run before it is killed: it holds the table's lock.""" + DEFAULT_LOCK_PREFIX = "partitioner" # PostgreSQL SQLSTATEs. diff --git a/pg_partsmith/document.py b/pg_partsmith/document.py index b47172d..8501a4a 100644 --- a/pg_partsmith/document.py +++ b/pg_partsmith/document.py @@ -36,13 +36,15 @@ DEFAULT_DROP_MAX_BACKOFF, DEFAULT_DROP_MAX_RETRIES, DEFAULT_DROP_RETRY_DELAY, + DEFAULT_HOOK_TIMEOUT_SECONDS, DEFAULT_LOCK_PREFIX, DEFAULT_RETENTION_COUNT, ) from .entities import PartitionGranularity, PartitionStrategy, PartitionType, TablePartitionConfig +from .events import HookPhase from .strategies import BasePeriodCalculator, get_period_calculator -__all__ = ["PartitionTableSpec", "PartitionsDocument", "ToolkitOptions"] +__all__ = ["HookOptions", "PartitionTableSpec", "PartitionsDocument", "ToolkitOptions"] class PartitionTableSpec(BaseModel): @@ -206,6 +208,47 @@ def to_kwargs(self) -> dict[str, Any]: return {**self.model_dump(), "boundary_codec": resolve_codec(self.boundary_codec)} +class HookOptions(BaseModel): + """A command to run at each lifecycle moment, as a file writes them. + + One field per phase, spelled out rather than a free mapping, so a + misspelled ``befor_drop`` is refused where it is written instead of + silently never running -- which, for the phase that exports data before a + ``DROP``, is the difference between an archive and no archive. + + Each command is an argument vector. Nothing is passed through a shell, so a + partition name can never be read as syntax. + + Hooks fire during ``apply`` only. ``plan`` issues no DDL and runs no hook, + which is what makes a plan safe to compute anywhere. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + timeout_seconds: float = Field( + default=DEFAULT_HOOK_TIMEOUT_SECONDS, + gt=0, + description="How long a command may run before it is killed; it holds the table's lock", + ) + before_create: tuple[str, ...] | None = Field(default=None, description="Before a partition exists") + after_create: tuple[str, ...] | None = Field(default=None, description="After it is created and attached") + before_attach: tuple[str, ...] | None = Field(default=None, description="Before a detached partition returns") + after_attach: tuple[str, ...] | None = Field(default=None, description="After it is taking rows again") + before_detach: tuple[str, ...] | None = Field(default=None, description="While its rows are still reachable") + after_detach: tuple[str, ...] | None = Field(default=None, description="After it stands alone") + before_drop: tuple[str, ...] | None = Field(default=None, description="The last moment its rows exist") + after_drop: tuple[str, ...] | None = Field(default=None, description="After the table is gone") + + def commands(self) -> dict[HookPhase, tuple[str, ...]]: + """The phases a command was given for, in lifecycle order.""" + return {phase: command for phase in HookPhase if (command := getattr(self, phase.value)) is not None} + + @property + def is_empty(self) -> bool: + """True when the section names no command at all.""" + return not self.commands() + + class PartitionsDocument(BaseModel): """Every table a deployment maintains, and the wiring it maintains them through. @@ -217,6 +260,14 @@ class PartitionsDocument(BaseModel): ``dsn`` is for whoever connects; the library opens no connection of its own, and a deployment is free to keep the DSN out of the file entirely. + + ``hooks`` names commands to run around the lifecycle. They are code this + file causes to run in a process holding DDL credentials -- which is not a + new privilege boundary, since the same file already authorises dropping + tables, but it stops being true the moment the document is assembled from + somewhere less trusted than the DSN. Whoever runs the document decides + whether they are honoured; the CLI refuses to apply a document declaring + hooks unless it is told to. """ model_config = ConfigDict(frozen=True, extra="forbid") @@ -226,6 +277,9 @@ class PartitionsDocument(BaseModel): defaults: dict[str, Any] = Field(default_factory=dict, description="Fields every table starts from") tables: tuple[PartitionTableSpec, ...] = Field(..., min_length=1, description="The tables to maintain") runtime: ToolkitOptions = Field(default_factory=ToolkitOptions, description="How the collaborators are wired") + hooks: HookOptions | None = Field( + default=None, description="Commands to run around the lifecycle; they fire during apply only" + ) @model_validator(mode="before") @classmethod diff --git a/pg_partsmith/events.py b/pg_partsmith/events.py index 2dbfaff..d89c00c 100644 --- a/pg_partsmith/events.py +++ b/pg_partsmith/events.py @@ -11,6 +11,7 @@ from __future__ import annotations import inspect +import os from collections.abc import Iterable from enum import StrEnum from typing import TYPE_CHECKING @@ -169,3 +170,26 @@ def validate_hook_signatures(hooks: Iterable[object]) -> None: f"event.table_name, event.window, event.operation.reason." ) raise ValueError(msg) from None + + +def hook_environment(event: PartitionEvent) -> dict[str, str]: + """The process environment a command hook is run with. + + The whole event arrives on stdin; these are the three facts a shell script + reaches for often enough that parsing JSON to get them would be silly. The + parent environment is inherited, because a hook needs its own credentials, + its ``PATH`` and its proxy settings, and stripping those would leave it + unable to do the one thing it exists for. + """ + environment = dict(os.environ) + environment.update( + PG_PARTSMITH_PHASE=event.phase.value, + PG_PARTSMITH_TABLE=event.table_name, + PG_PARTSMITH_PARTITION=event.partition.name, + ) + if event.window is not None: + environment.update( + PG_PARTSMITH_WINDOW_START=event.window.start.isoformat(), + PG_PARTSMITH_WINDOW_END=event.window.end.isoformat(), + ) + return environment diff --git a/pg_partsmith/hook_commands.py b/pg_partsmith/hook_commands.py new file mode 100644 index 0000000..bdad84b --- /dev/null +++ b/pg_partsmith/hook_commands.py @@ -0,0 +1,97 @@ +"""Running somebody else's program as a lifecycle hook, once, for both mirrors. + +The command, its payload and everything that can go wrong with it are the same +question in the aio and the sync worlds; only the waiting differs. So the +running lives here, as an ordinary blocking call, and the aio mirror hands it to +a thread. + +That is also what makes it work everywhere. ``asyncio.create_subprocess_exec`` +needs a loop that can spawn processes -- on Windows a selector loop, which is +what an asyncpg or psycopg deployment often installs, raises +``NotImplementedError`` instead -- and a hook that runs on Linux but not on a +developer's machine is a hook nobody trusts. +""" + +from __future__ import annotations + +import subprocess +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + from .events import HookPhase + +__all__ = ["CommandHookError", "run_hook_command"] + +_OUTPUT_TAIL = 2000 + + +class CommandHookError(RuntimeError): + """A configured command refused the operation, or could not be run. + + Raised so the executor treats it like any other hook failure: the operation + is abandoned and planned again next run, and under ``continue_on_error`` the + rest of the table is still maintained. + """ + + def __init__(self, phase: HookPhase, partition_name: str, detail: str) -> None: + super().__init__(f"{phase.value} hook for {partition_name!r} failed: {detail}") + self.phase = phase + self.partition_name = partition_name + self.detail = detail + + +def run_hook_command( + command: Sequence[str], + payload: bytes, + *, + phase: HookPhase, + partition_name: str, + environment: Mapping[str, str], + timeout_seconds: float, +) -> bytes: + """Run one command with ``payload`` on its stdin, and answer with its stdout. + + Args: + command: The argument vector. Never a shell string, so a partition name + cannot be read as syntax. + payload: The event, as JSON. + phase: Which moment this is, for the error. + partition_name: What the operation is about, for the error. + environment: The process environment. + timeout_seconds: How long it may take. A hook that hangs holds the + table's maintenance lock, so there is no "wait forever". + + Returns: + Whatever the command wrote to stdout. + + Raises: + CommandHookError: If it exits non-zero, cannot be run, or outlives the + timeout -- each of which abandons the operation. + """ + try: + completed = subprocess.run( # noqa: S603 - an argument vector, never a shell + list(command), + input=payload, + capture_output=True, + timeout=timeout_seconds, + check=False, + env=dict(environment), + ) + except OSError as exc: + raise CommandHookError(phase, partition_name, f"{command[0]}: {exc}") from exc + except subprocess.TimeoutExpired: + detail = f"{command[0]} did not finish within {timeout_seconds}s and was killed" + raise CommandHookError(phase, partition_name, detail) from None + + if completed.returncode != 0: + detail = f"{command[0]} exited {completed.returncode}: {tail(completed.stderr)}" + raise CommandHookError(phase, partition_name, detail) + return completed.stdout + + +def tail(stream: bytes, limit: int = _OUTPUT_TAIL) -> str: + """The end of a command's output, which is where it says what went wrong.""" + text = stream.decode(errors="replace").strip() + return text if len(text) <= limit else f"…{text[-limit:]}" diff --git a/pg_partsmith/sync/__init__.py b/pg_partsmith/sync/__init__.py index 55272b7..8b22496 100644 --- a/pg_partsmith/sync/__init__.py +++ b/pg_partsmith/sync/__init__.py @@ -1,5 +1,6 @@ """Sync implementations for partition management.""" +from .command_hooks import CommandHookError, CommandHooks from .hooks import BasePartitionLifecycleHooks, PartitionLifecycleHooks from .lock import PostgresAdvisoryLockManager, RedisDistributedLockManager from .maintainer import PartitionMaintainer, maintain_partitions @@ -17,6 +18,8 @@ __all__ = [ "BasePartitionLifecycleHooks", + "CommandHookError", + "CommandHooks", "LockManager", "PartitionInspector", "PartitionLifecycle", diff --git a/pg_partsmith/sync/command_hooks.py b/pg_partsmith/sync/command_hooks.py new file mode 100644 index 0000000..cca2974 --- /dev/null +++ b/pg_partsmith/sync/command_hooks.py @@ -0,0 +1,114 @@ +"""Lifecycle hooks that run a command, for the stacks this library is not written in. + +A Go or Ruby team already owns an archiver; what they need is for it to be +invoked at the right moment with the right metadata. That is all this is: one +hook object that runs a configured command per phase, hands it the +:class:`~pg_partsmith.events.PartitionEvent` as JSON on stdin, and treats a +non-zero exit exactly as a raised exception -- the operation is aborted and +left for the next run. + +Nothing here needs a new context: the event is already a pydantic model, so the +payload the command reads is the same object a Python hook is handed, dumped +with ``by_alias=True``. + +Usage:: + + hooks = CommandHooks({HookPhase.BEFORE_DROP: ["/usr/local/bin/archive"]}) + service = PartitionLifecycleService(repo=repo, metadata=metadata, locks=locks, hooks=[hooks]) + +The command's stdout is logged. Its stderr is carried in the error when it +fails, which is the only place an operator will look at 03:00. +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING + +from pg_partsmith.constants import DEFAULT_HOOK_TIMEOUT_SECONDS +from pg_partsmith.events import HookPhase, hook_environment +from pg_partsmith.hook_commands import CommandHookError, run_hook_command, tail + +from .hooks import BasePartitionLifecycleHooks + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + from pg_partsmith.events import PartitionEvent + +logger = logging.getLogger(__name__) + +__all__ = ["CommandHookError", "CommandHooks"] + + +class CommandHooks(BasePartitionLifecycleHooks): + """Runs one configured command per phase, with the event as JSON on stdin. + + Overrides :meth:`on_event` alone rather than one method per phase: the + phase is in the event, and a dispatch table reads better than eight + delegating methods that would each have to be added to again. The + per-phase methods come from the no-op base, which the executor calls after + this one. + """ + + def __init__( + self, + commands: Mapping[HookPhase, Sequence[str]], + *, + timeout_seconds: float = DEFAULT_HOOK_TIMEOUT_SECONDS, + ) -> None: + """Wire the commands. + + Args: + commands: The command to run at each phase, as an argument vector. + A vector rather than a string: nothing is passed through a + shell, so a partition name can never be read as syntax. + timeout_seconds: How long a command may take before it is killed and + the operation abandoned. A hook that hangs holds the table's + maintenance lock, so there is no "wait forever" option. + + Raises: + ValueError: If a command is empty, or its phase is not a hook phase. + """ + for phase, command in commands.items(): + if phase not in set(HookPhase): + msg = f"{phase!r} is not a hook phase; expected one of: {', '.join(p.value for p in HookPhase)}" + raise ValueError(msg) + if not command or not all(isinstance(part, str) for part in command): + msg = f"The {phase.value} command must be a non-empty list of strings" + raise ValueError(msg) + self._commands = {phase: tuple(command) for phase, command in commands.items()} + self._timeout = timeout_seconds + + @property + def phases(self) -> tuple[HookPhase, ...]: + """The phases a command is configured for, in declaration order.""" + return tuple(self._commands) + + def on_event(self, event: PartitionEvent) -> None: + """Run the command configured for this event's phase, if there is one. + + Raises: + CommandHookError: If the command exits non-zero, cannot be run, or + outlives its timeout. A ``before_*`` hook failing this way + abandons the operation; an ``after_*`` one abandons what is left + of it, and the next run plans it again. + """ + command = self._commands.get(event.phase) + if command is None: + return + stdout = run_hook_command( + command, + event.model_dump_json(by_alias=True).encode(), + phase=event.phase, + partition_name=event.partition.name, + environment=hook_environment(event), + timeout_seconds=self._timeout, + ) + if stdout: + logger.info( + "%s hook said: %s", + event.phase.value, + tail(stdout), + extra={"partition_name": event.partition.name, "table_name": event.table_name}, + ) diff --git a/tests/integration/aio/test_cli.py b/tests/integration/aio/test_cli.py index 1473c31..040beeb 100644 --- a/tests/integration/aio/test_cli.py +++ b/tests/integration/aio/test_cli.py @@ -4,6 +4,7 @@ import asyncio import json +import sys from typing import TYPE_CHECKING import pytest @@ -34,7 +35,9 @@ async def _run_cli(*args: str) -> int: return await asyncio.to_thread(main, list(args)) -def _document(tmp_path: Path, table: str, dsn: str, *, retention: int = 12) -> str: +def _document( + tmp_path: Path, table: str, dsn: str, *, retention: int = 12, hooks: dict[str, list[str]] | None = None +) -> str: """A document describing that one table, written where the CLI will read it.""" schema, _, relname = table.rpartition(".") payload = { @@ -50,6 +53,8 @@ def _document(tmp_path: Path, table: str, dsn: str, *, retention: int = 12) -> s } ], } + if hooks is not None: + payload["hooks"] = hooks tmp_path.mkdir(parents=True, exist_ok=True) path = tmp_path / "partitions.json" path.write_text(json.dumps(payload), encoding="utf-8") @@ -237,3 +242,62 @@ async def test__apply__a_plan_made_under_another_configuration__is_refused( # that stopped being true assert await _run_cli("apply", "-c", edited, "--plan", str(saved)) == ExitCode.CONFIG assert await _run_cli("apply", "-c", edited, "--plan", str(saved), "--allow-config-drift") == ExitCode.OK + + +async def test__apply__a_command_hook__runs_around_the_real_drop( + db_engine: AsyncEngine, table: str, tmp_path: Path +) -> None: + # Arrange: the export-before-destroy case, as a non-Python team would write it + await _with_an_expired_partition(db_engine, table) + marker = tmp_path / "archived.json" + body = f"import sys, pathlib; pathlib.Path({str(marker)!r}).write_text(sys.stdin.read(), encoding='utf-8')" + config = _document( + tmp_path, + table, + _dsn(db_engine), + retention=1, + hooks={"before_drop": [sys.executable, "-c", body]}, + ) + + # Act + code = await _run_cli("apply", "-c", config, "--allow-destructive", "--allow-hooks") + + # Assert: it ran, and it was told which partition and why + assert code == ExitCode.OK + payload = json.loads(marker.read_text(encoding="utf-8")) + assert payload["phase"] == "before_drop" + assert payload["partition"]["name"].endswith(f"{table}__2020_01") + assert payload["operation"]["reason"] in {"grace_elapsed", "follows_detach"} + + +async def test__apply__a_hook_that_refuses__leaves_the_partition_alone( + db_engine: AsyncEngine, table: str, tmp_path: Path +) -> None: + # Arrange: an archiver that says "not yet" + await _with_an_expired_partition(db_engine, table) + config = _document( + tmp_path, + table, + _dsn(db_engine), + retention=1, + hooks={"before_drop": [sys.executable, "-c", "import sys; sys.exit(1)"]}, + ) + + # Act + code = await _run_cli("apply", "-c", config, "--allow-destructive", "--allow-hooks", "--continue-on-error") + + # Assert: detached, and still there to be dropped once the archiver agrees + assert code == ExitCode.FINDINGS + async with db_engine.begin() as conn: + exists = await conn.execute(text("SELECT to_regclass(:name) IS NOT NULL"), {"name": f"{table}__2020_01"}) + assert exists.scalar_one() is True + + +async def test__apply__hooks_declared_but_not_allowed__refuses_before_connecting( + db_engine: AsyncEngine, table: str, tmp_path: Path +) -> None: + # Arrange + config = _document(tmp_path, table, _dsn(db_engine), hooks={"before_drop": [sys.executable, "-c", "pass"]}) + + # Act / Assert + assert await _run_cli("apply", "-c", config) == ExitCode.CONFIG diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index d5e6d1a..7e3e211 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -12,7 +12,7 @@ import pytest from pg_partsmith.__version__ import __version__ -from pg_partsmith.cli import ExitCode, main +from pg_partsmith.cli import ExitCode, build_parser, main from pg_partsmith.cli.commands import run_apply, run_plan, run_validate from pg_partsmith.cli.loader import ( DSN_ENV_VAR, @@ -23,9 +23,11 @@ resolve_dsn, select_configs, ) +from pg_partsmith.cli.main import _hooks as _cli_hooks from pg_partsmith.cli.render import 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.plan import ( CreatePartition, @@ -457,3 +459,45 @@ def test__load_plans__something_that_is_not_a_saved_plan__is_refused(tmp_path: P # Act / Assert with pytest.raises(ConfigError, match="no 'tables'"): load_plans(path) + + +# ── Hooks are code, and run only when asked for ───────────────────────────────── + + +def _hooks_document(tmp_path: Path) -> str: + payload = {**DOCUMENT, "dsn": "postgresql://app@localhost/app", "hooks": {"before_drop": ["/bin/archive"]}} + return str(_write(tmp_path, "partitions.json", json.dumps(payload))) + + +def test__apply__a_document_that_runs_commands__is_refused_unless_asked_for(tmp_path: Path) -> None: + # Arrange: ignoring a configured before_drop silently would be the worst + # outcome available -- an operator reads the file and believes it ran. + config = _hooks_document(tmp_path) + + # Act + code = main(["apply", "-c", config]) + + # Assert: refused as configuration, before any connection is made + assert code == ExitCode.CONFIG + + +def test__plan__a_document_that_runs_commands__needs_no_permission(tmp_path: Path) -> None: + # Hooks fire during apply alone, so planning one is not running one. This + # gets as far as connecting, which is a different failure entirely. + config = _hooks_document(tmp_path) + + # Act / Assert + assert main(["plan", "-c", config]) == ExitCode.CONNECTION + + +def test__hooks__allowed__are_built_from_the_document(tmp_path: Path) -> None: + # Arrange + document = load_document(Path(_hooks_document(tmp_path))) + args = build_parser().parse_args(["apply", "-c", "x", "--allow-hooks"]) + + # Act + hooks = _cli_hooks(document, args) + + # Assert + assert hooks is not None + assert hooks[0].phases == (HookPhase.BEFORE_DROP,) diff --git a/tests/unit/test_command_hooks.py b/tests/unit/test_command_hooks.py new file mode 100644 index 0000000..0c9e9ff --- /dev/null +++ b/tests/unit/test_command_hooks.py @@ -0,0 +1,171 @@ +"""``CommandHooks``: a lifecycle hook that runs somebody else's program.""" + +from __future__ import annotations + +import json +import sys +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import pytest + +from pg_partsmith.aio.command_hooks import CommandHookError, CommandHooks +from pg_partsmith.entities import PartitionGranularity, PartitionInfo, TablePartitionConfig +from pg_partsmith.events import HookPhase, PartitionEvent +from pg_partsmith.plan import DropPartition, Reason +from pg_partsmith.sync.command_hooks import CommandHooks as SyncCommandHooks +from pg_partsmith.topology import RangeBounds + +CONFIG = TablePartitionConfig( + schema="public", + table_name="events", + partition_column="created_at", + granularity=PartitionGranularity.MONTH, +) + + +def _event(phase: HookPhase = HookPhase.BEFORE_DROP) -> PartitionEvent: + info = PartitionInfo( + name="events__2025_08", + schema_name="public", + partition_type="range", + is_attached=False, + bounds=RangeBounds(from_value="2025-08-01", to_value="2025-09-01"), + ) + operation = DropPartition(target="public.events__2025_08", reason=Reason.GRACE_ELAPSED, oid=42) + return PartitionEvent.build(phase, CONFIG, info, operation) + + +def _script(body: str) -> list[str]: + """A command that is a Python one-liner, so the test runs anywhere pytest does.""" + return [sys.executable, "-c", body] + + +READ_STDIN = "import sys, json; d = json.load(sys.stdin); open(sys.argv[1] if len(sys.argv) > 1 else 'x', 'w')" + + +async def test__on_event__the_phase_it_was_configured_for__runs_the_command(tmp_path: Path) -> None: + # Arrange + marker = tmp_path / "ran.json" + body = f"import sys, pathlib; pathlib.Path({str(marker)!r}).write_text(sys.stdin.read(), encoding='utf-8')" + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script(body)}) + + # Act + await hooks.on_event(_event()) + + # Assert: the whole event, in the vocabulary a document is written in + payload: dict[str, Any] = json.loads(marker.read_text(encoding="utf-8")) + assert payload["phase"] == "before_drop" + assert payload["partition"]["name"] == "events__2025_08" + assert payload["operation"]["kind"] == "drop" + assert payload["operation"]["reason"] == "grace_elapsed" + assert payload["window"]["start"].startswith("2025-08-01") + + +async def test__on_event__another_phase__runs_nothing(tmp_path: Path) -> None: + # Arrange + marker = tmp_path / "ran" + body = f"import pathlib; pathlib.Path({str(marker)!r}).write_text('ran', encoding='utf-8')" + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script(body)}) + + # Act + await hooks.on_event(_event(HookPhase.AFTER_CREATE)) + + # Assert + assert not marker.exists() + + +async def test__on_event__a_command_that_refuses__aborts_the_operation() -> None: + # Arrange: a non-zero exit is a refusal, exactly as a raised exception is + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script("import sys; sys.stderr.write('still needed'); sys.exit(3)")}) + + # Act / Assert + with pytest.raises(CommandHookError, match="still needed") as exc: + await hooks.on_event(_event()) + assert exc.value.phase is HookPhase.BEFORE_DROP + assert exc.value.partition_name == "events__2025_08" + + +async def test__on_event__a_command_that_hangs__is_killed_and_the_operation_abandoned() -> None: + # A hook that never returns holds the table's maintenance lock, so there is + # no "wait forever" option. + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script("import time; time.sleep(30)")}, timeout_seconds=0.5) + + # Act / Assert + with pytest.raises(CommandHookError, match="did not finish"): + await hooks.on_event(_event()) + + +async def test__on_event__a_command_that_is_not_there__says_so_by_name() -> None: + # Arrange + hooks = CommandHooks({HookPhase.BEFORE_DROP: ["/nonexistent/archive-partition"]}) + + # Act / Assert + with pytest.raises(CommandHookError, match="archive-partition"): + await hooks.on_event(_event()) + + +async def test__on_event__the_environment__names_the_phase_the_table_and_the_partition(tmp_path: Path) -> None: + # Arrange: the three facts a shell script reaches for, without parsing JSON + marker = tmp_path / "env.json" + body = ( + "import os, json, pathlib; " + f"pathlib.Path({str(marker)!r}).write_text(json.dumps(" + "{k: v for k, v in os.environ.items() if k.startswith('PG_PARTSMITH_')}), encoding='utf-8')" + ) + hooks = CommandHooks({HookPhase.BEFORE_DROP: _script(body)}) + + # Act + await hooks.on_event(_event()) + + # Assert + environment = json.loads(marker.read_text(encoding="utf-8")) + assert environment["PG_PARTSMITH_PHASE"] == "before_drop" + assert environment["PG_PARTSMITH_TABLE"] == "public.events" + assert environment["PG_PARTSMITH_PARTITION"] == "events__2025_08" + assert environment["PG_PARTSMITH_WINDOW_START"].startswith("2025-08-01") + + +def test__command_hooks__an_empty_command__is_refused() -> None: + # Arrange / Act / Assert + with pytest.raises(ValueError, match="before_drop"): + CommandHooks({HookPhase.BEFORE_DROP: []}) + + +def test__command_hooks__implements_every_phase_method_the_executor_calls() -> None: + # The executor calls the method named for the phase after on_event, so a + # hook missing one would abort the operation with an AttributeError. + hooks = CommandHooks({HookPhase.BEFORE_DROP: ["/bin/true"]}) + + # Act / Assert + assert all(callable(getattr(hooks, phase.value, None)) for phase in HookPhase) + assert hooks.phases == (HookPhase.BEFORE_DROP,) + + +def test__sync_command_hooks__runs_the_same_way(tmp_path: Path) -> None: + # Arrange: the mirrors differ in how they wait, not in what they do + marker = tmp_path / "ran.json" + body = f"import sys, pathlib; pathlib.Path({str(marker)!r}).write_text(sys.stdin.read(), encoding='utf-8')" + hooks = SyncCommandHooks({HookPhase.BEFORE_DROP: _script(body)}) + + # Act + hooks.on_event(_event()) + + # Assert + assert json.loads(marker.read_text(encoding="utf-8"))["phase"] == "before_drop" + + +def test__sync_command_hooks__a_command_that_refuses__aborts_the_operation() -> None: + # Arrange + hooks = SyncCommandHooks({HookPhase.BEFORE_DROP: _script("import sys; sys.exit(2)")}) + + # Act / Assert + with pytest.raises(CommandHookError, match="exited 2"): + hooks.on_event(_event()) + + +def test__hook_event__is_built_at_the_moment_the_test_says_it_is() -> None: + # Guards the fixture rather than the code: a stale clock here would make + # the window assertions above pass for the wrong reason. + assert datetime.now(UTC).year >= 2024 diff --git a/tests/unit/test_document.py b/tests/unit/test_document.py index 88d9d1c..9b671ba 100644 --- a/tests/unit/test_document.py +++ b/tests/unit/test_document.py @@ -11,6 +11,7 @@ from pg_partsmith.boundaries import UUIDv7BoundaryCodec from pg_partsmith.document import PartitionsDocument, PartitionTableSpec, ToolkitOptions from pg_partsmith.entities import PartitionGranularity +from pg_partsmith.events import HookPhase def _document(**overrides: Any) -> dict[str, Any]: @@ -175,3 +176,43 @@ def test__document__round_trips_through_its_own_dump() -> None: # Act / Assert assert PartitionsDocument.model_validate_json(document.model_dump_json(by_alias=True)) == document + + +# ── Hooks ─────────────────────────────────────────────────────────────────────── + + +def test__hooks__commands__come_back_in_lifecycle_order() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate( + _document(hooks={"after_create": ["/bin/notify"], "before_drop": ["/bin/archive", "--to", "s3"]}) + ) + + # Assert: declaration order in the file does not decide when they run + assert document.hooks is not None + assert [phase.value for phase in document.hooks.commands()] == ["after_create", "before_drop"] + assert document.hooks.commands()[HookPhase.BEFORE_DROP] == ("/bin/archive", "--to", "s3") + + +def test__hooks__a_misspelled_phase__is_refused_where_it_is_written() -> None: + # Silently never running the command that exports data before a DROP is the + # difference between an archive and no archive. + with pytest.raises(ValidationError): + PartitionsDocument.model_validate(_document(hooks={"befor_drop": ["/bin/archive"]})) + + +def test__hooks__omitted__is_no_hooks_at_all() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate(_document()) + + # Assert + assert document.hooks is None + + +def test__hooks__a_section_naming_no_command__knows_it_is_empty() -> None: + # Arrange / Act + document = PartitionsDocument.model_validate(_document(hooks={"timeout_seconds": 30})) + + # Assert + assert document.hooks is not None + assert document.hooks.is_empty + assert document.hooks.timeout_seconds == 30 diff --git a/zensical.toml b/zensical.toml index e72ffdb..75f1893 100644 --- a/zensical.toml +++ b/zensical.toml @@ -36,6 +36,7 @@ nav = [ { "Schedule maintenance" = "guide/scheduling.md" }, { "The command line" = "guide/cli.md" }, { "The container image" = "guide/container.md" }, + { "Commands around the lifecycle" = "guide/hooks-in-config.md" }, { "Monitor and alert" = "guide/monitoring.md" }, { "Query a partitioned table" = "guide/querying.md" }, { "Backfill partitions for existing data" = "guide/backfill.md" },