Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<version>`, published from the release workflow, so a
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<version>` with the command
as its entrypoint; tags are the exact version and a moving minor, never `latest`. See
`guide/container.md`.
Expand Down
6 changes: 6 additions & 0 deletions docs/guide/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
115 changes: 115 additions & 0 deletions docs/guide/hooks-in-config.md
Original file line number Diff line number Diff line change
@@ -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).
7 changes: 7 additions & 0 deletions docs/reference/document.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion pg_partsmith/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
UUIDv7BoundaryCodec,
Window,
)
from .document import PartitionsDocument, PartitionTableSpec, ToolkitOptions
from .document import HookOptions, PartitionsDocument, PartitionTableSpec, ToolkitOptions
from .entities import (
DefaultBounds,
HashBounds,
Expand Down Expand Up @@ -151,6 +151,7 @@
"ForeignLeaves",
"HashBounds",
"HashPartitioning",
"HookOptions",
"HookPhase",
"HourPeriodCalculator",
"IntegerSequence",
Expand Down
3 changes: 3 additions & 0 deletions pg_partsmith/aio/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -17,6 +18,8 @@

__all__ = [
"BasePartitionLifecycleHooks",
"CommandHookError",
"CommandHooks",
"LockManager",
"PartitionInspector",
"PartitionLifecycle",
Expand Down
116 changes: 116 additions & 0 deletions pg_partsmith/aio/command_hooks.py
Original file line number Diff line number Diff line change
@@ -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},
)
Loading