Skip to content
Merged
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
39 changes: 39 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,45 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## 1.11.0 — expired partitions can be emptied in place

A retention policy could only take an expired partition out of the tree: detach it, then
drop it or keep it. A project that empties expired partitions in place, as data-rentgen's
`cleanup_partitions truncate` does, could not switch without changing what its operators
see ([#130](https://github.com/bedrock-python/pg-partsmith/issues/130)).

**What is new:** `LifecyclePolicy(expire=ExpireAction.TRUNCATE)`, `expire: truncate` in a
document, empties an expired partition with `TRUNCATE` and leaves it attached. The plan
carries a `TruncatePartition` (kind `truncate`), the result a `truncated_count`, and hooks
get `before_truncate` / `after_truncate`, which a document's `hooks` section takes too. The
truncate locks the partition and the relations below it and never the parent, so writers to
the other partitions do not wait for it, where a blocking detach holds the whole parent. A
partition that is empty already gets no operation, and one `expired_empty` finding per
parent counts them. One that a foreign key reaches, which PostgreSQL refuses to truncate
whether or not a row is referenced, is reported as `truncate_blocked` rather than failing
the run, and so is one whose subtree holds a foreign table, whose remote table `TRUNCATE`
would empty, including a key or a foreign table that appears after the plan was made.
`apply` without
`--allow-destructive` and `maintain(skip_detach=True)` leave truncates out.

**What stays:** the default is `ExpireAction.DETACH`, and a policy that names no `expire`
plans exactly as before.

**What to check:** a repository of your own has to implement
`PartitionRepository.truncate_partition`, a metadata provider of your own has to answer
`FactKind.EMPTY` and `FactKind.REFERENCING_TABLES` in `measure` (or every expired partition
is truncated on every run), and a hook class that implements the protocol without
subclassing `BasePartitionLifecycleHooks` needs `before_truncate` and `after_truncate`
before it runs under `expire=truncate`. The policy serializes one more field, so
`apply --plan` refuses a plan saved by 1.10 as made under another configuration: plan
again, or pass `--allow-config-drift`. Before switching a table to `expire=truncate`, check
three things: the role needs the `TRUNCATE` privilege on its partitions, which owning the
parent does not give on partitions another role created; its publications, since logical
replication carries a `TRUNCATE`, which it never did for a detach or a drop, so a subscriber
keeping more history needs `truncate` left out of `publish`; and its readers, since a query
pruned only when it runs, a `now()`-relative one say, waits for a truncate queued behind a
reader of the expired partition, up to `ddl_lock_timeout_ms`.

## [1.10.0](https://github.com/bedrock-python/pg-partsmith/compare/pg-partsmith-v1.9.0...pg-partsmith-v1.10.0) (2026-10-17)


Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ Something else is probably the better fit when:
integers, your own codec); fixed-width integer windows for id-partitioned queues
- **Lifecycle policies** — create ahead by count, until a horizon or when the newest
partition says so; expire by count, age or distance, or by a predicate (size, rows,
foreign-key references, SQL); detach now, drop after a grace period
foreign-key references, SQL); detach now, drop after a grace period, or empty in place
and leave the partition attached
- **Leaf backends** — local tables with a tablespace, storage parameters and the parent's
grants, or foreign tables on an FDW server (`postgres_fdw`, ClickHouse)
- **Batched data movement** — drain a DEFAULT partition into lifecycle partitions
Expand All @@ -86,7 +87,7 @@ Something else is probably the better fit when:
CronJob / init container, CI and systemd
- **Examples that are tested** — every document under `examples/` validates in CI, the hook
scripts parse, and `pg-partsmith schema` gives an editor the JSON Schema
- **Hooks, locks, schemas** — eight lifecycle hooks, in Python or as commands named in a
- **Hooks, locks, schemas** — ten 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 through 18 via testcontainers

Expand Down Expand Up @@ -294,6 +295,7 @@ planned and the size the policy measured, when it asked for one.
| `before_create` / `after_create` | around the creation of a partition directly under the root (its subtree included) |
| `before_attach` / `after_attach` | around bringing a detached partition back into the tree |
| `before_detach` / `after_detach` | around a detach |
| `before_truncate` / `after_truncate` | around emptying an expired partition in place (`expire=truncate`) |
| `before_drop` / `after_drop` | around a drop — `before_drop` is the last chance to read the data |
| `on_event` | every one of the above, for an audit trail or metrics in one method |

Expand Down
38 changes: 23 additions & 15 deletions docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ a method that sounds plausible.
## Scope

**It does** keep the partitions of a partitioned table in the shape you declare: create
ahead of the cursor, fill gaps in a set, detach what expired, drop after a grace period.
ahead of the cursor, fill gaps in a set, detach what expired (or empty it in place), drop
after a grace period.
It reads the tree from the catalog, produces a plan you can inspect before applying it,
and moves rows in batches into partitions (`partition_data`) or back out into one table
(`unpartition`).
Expand All @@ -56,8 +57,8 @@ A configuration is a **scheme** — the shape of the tree, level by level — an
the locks, the service and the maintainer around one engine, giving each setting that
belongs to two of them (`marker_prefix`, `ddl_timezone`, `boundary_codec`) exactly once.
* `pg-partsmith` (extra `cli`) runs `inspect` / `plan` / `validate` / `apply` / `backfill`
over a document and a DSN. The first three issue no DDL; `apply` withholds detaches and
drops unless `--allow-destructive`. `backfill` is `partition_data` from the command line —
over a document and a DSN. The first three issue no DDL; `apply` withholds detaches,
truncates and drops unless `--allow-destructive`. `backfill` is `partition_data` from the command line —
the one-off migration of a DEFAULT partition's rows into the partitions they belong in,
`--batch-rows` / `--max-batches`, exiting 2 while anything is left to move. `plan --save FILE` writes the artifact `apply --plan FILE`
reads back, and applying it is refused if it was made for another table or under a
Expand Down Expand Up @@ -212,9 +213,10 @@ TablePartitionConfig(
```

`LifecyclePolicy()` with no arguments is `CreateAhead(6)`, `KeepNewest(12)`,
`DetachMode.AUTO`, `DropAfter(grace=timedelta(days=7))`: **an expired partition stays
detached for a week, then is dropped** (rule 8). `DropAfter()` with no grace drops in the
same run as the detach; pass `drop=DropNever()` if detached tables should be kept.
`ExpireAction.DETACH`, `DetachMode.AUTO`, `DropAfter(grace=timedelta(days=7))`: **an
expired partition stays detached for a week, then is dropped** (rule 8). `DropAfter()` with
no grace drops in the same run as the detach; pass `drop=DropNever()` if detached tables
should be kept.

### Levels

Expand Down Expand Up @@ -242,6 +244,7 @@ Nesting is `child=`, up to five levels including the root.
|---|---|
| `creation` | `CreateAhead(count)`, `CreateUntil(position)`, `CreateNextIf(when)` |
| `retention` | `KeepNewest(count)`, `KeepFor(age)`, `KeepBehind(distance)`, `ExpireIf(when)` |
| `expire` | `ExpireAction.DETACH` (default), `.TRUNCATE`: empty the expired partition in place and leave it attached; locks the partition only, never the parent; `expire: truncate` in a document |
| `detach` | `DetachMode.AUTO` (concurrent where PostgreSQL allows), `.CONCURRENT`, `.BLOCKING` |
| `drop` | `DropAfter(grace, when=None)`, `DropNever()` |
| predicates | `SizeAbove(bytes)`, `RowsAbove(rows)`, `WindowAgeAbove(age)`, `Unreferenced()`, `SqlPredicate(sql)`, `Callback(fn, facts, label)` |
Expand Down Expand Up @@ -293,8 +296,8 @@ error (`LockLostError`).
`EXPLICIT` (only the windows named in `windows=`).

On a `MaintenancePlan`: `.operations`, `.findings`, `.cursors`, `.generated_at`,
`.config_fingerprint`, `.creates` / `.attaches` / `.detaches` / `.drops`, `.is_noop`,
`.only(*kinds)`, `.without(*kinds)`, `.describe()`. Filtering a plan and applying the rest
`.config_fingerprint`, `.creates` / `.attaches` / `.detaches` / `.truncates` / `.drops`,
`.is_noop`, `.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
Expand All @@ -312,11 +315,11 @@ still the same intent.
Results:

* `MaintenanceResult` — `created_count`, `repaired_count`, `attached_count`,
`detached_count`, `dropped_count`, `duration_ms`, `error`, `issues`, `.success`,
`.maintenance_plan`.
`detached_count`, `truncated_count`, `dropped_count`, `duration_ms`, `error`, `issues`,
`.success`, `.maintenance_plan`.
* `MigrationResult` — `rows_moved`, `batches`, `partitions`, `complete`, `issues`. Call
again while `complete` is `False`.
* `MaintenanceIssue` — `step` (`create` `reconcile` `attach` `detach` `drop` `move`),
* `MaintenanceIssue` — `step` (`create` `reconcile` `attach` `detach` `truncate` `drop` `move`),
`error` (`"TypeName: message"`), `partition_name`.

## Hooks
Expand All @@ -327,10 +330,11 @@ class ColdStorageHooks(BasePartitionLifecycleHooks):
await export(event.partition.name) # raising aborts this drop; it is retried next tick
```

Nine methods, each taking one `PartitionEvent(phase, config, partition, window, operation)`:
Eleven methods, each taking one `PartitionEvent(phase, config, partition, window, operation)`:
`before_create` / `after_create`, `before_attach` / `after_attach` (a detached partition
coming back), `before_detach` / `after_detach`, `before_drop` / `after_drop`, and
`on_event`, which fires for every phase in addition to the named method.
coming back), `before_detach` / `after_detach`, `before_truncate` / `after_truncate` (an
expired partition emptied in place), `before_drop` / `after_drop`, and `on_event`, which
fires for every phase in addition to the named method.
`event.table_name` is the root; `event.operation.reason` says why the operation is in the
plan; `event.window` is the period, or None for a member of a root HASH or LIST.
`before_*` exceptions abort that operation; `after_*` exceptions are logged. Hooks fire for
Expand Down Expand Up @@ -383,7 +387,11 @@ lifecycle units — partitions directly under the root — never once per leaf o
shadowing Pydantic's own `schema()`.
13. **Names must fit 63 bytes with the suffix**, and the scheme may be five levels deep at
most, root included.
14. **Two maintainers are safe.** `apply`, `maintain`, `partition_data` and `unpartition`
14. **`ExpireAction.TRUNCATE` cannot empty a partition a foreign key reaches.** PostgreSQL
refuses `TRUNCATE` of it whether or not a row is referenced, and a key on the parent is
cloned onto every partition. Such partitions are reported `truncate_blocked` and kept;
expire a referenced table with `ExpireAction.DETACH` and `Unreferenced()`.
15. **Two maintainers are safe.** `apply`, `maintain`, `partition_data` and `unpartition`
take the table's lock; the granular methods do not, and lost races are recognised and
reported rather than retried into a failure.

Expand Down
9 changes: 6 additions & 3 deletions docs/concepts/execution.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,11 @@ repository).

## Waiting for a lock

An attach, a row move and a blocking detach each run under `lock_timeout`
An attach, a row move, a blocking detach and a truncate each run under `lock_timeout`
(`ddl_lock_timeout_ms` on the repository, 3000 by default). A statement waiting for a lock
keeps its place in PostgreSQL's queue, and every session that asks for a conflicting lock
after it waits behind it; for the locks these steps take, that is every writer of the table.
after it waits behind it; for the locks the first three take, that is every writer of the
table, and for a truncate every query that has to lock the partition it empties.
The move-and-attach holds `EXCLUSIVE` on the parent while it waits for the DEFAULT
partition, so a reader holding the table for a minute would otherwise stop writes for that
minute.
Expand All @@ -154,6 +155,7 @@ writers and runs without one.
| the move-and-attach ([DEFAULT reconciliation](#default-reconciliation), step 2) | `EXCLUSIVE` on the parent (one level above `ATTACH`'s own, so no writer is mid-routing), then `ATTACH`'s `ACCESS EXCLUSIVE` on the partition and the DEFAULT sibling — all taken before the move |
| `DETACH PARTITION` (plain) | `ACCESS EXCLUSIVE` on parent, partition, and every table referencing the parent; the parent is locked first, as a query through it does, so a reader waits rather than deadlocks |
| `DETACH PARTITION … CONCURRENTLY` | `SHARE UPDATE EXCLUSIVE` on the parent; `ACCESS EXCLUSIVE` on the partition and, in its second transaction, on referencing tables |
| `TRUNCATE` of an expired partition (`expire=truncate`) | `ACCESS EXCLUSIVE` on the partition and every relation below it; nothing on the parent, so writers to the other partitions do not wait |
| `DROP TABLE` of a detached table | `ACCESS EXCLUSIVE` on that table only |
| `COMMENT ON` | `SHARE UPDATE EXCLUSIVE` on the table |
| the catalog reads (tree, orphans, sizes, estimates) | no relation lock: the tree is walked over `pg_inherits`, not with `pg_partition_tree()`, which would take `ACCESS SHARE` on every member — and omit a partition whose `DETACH CONCURRENTLY` was interrupted |
Expand Down Expand Up @@ -189,11 +191,12 @@ one of a small number of states, each of which the next run converges:
| creating a partition or its subtree | a detached, unmarked table, unreachable by writers | completes the subtree, attaches it |
| a backfill, between the fill and the attach | a detached, unmarked table holding its window's rows, which DEFAULT no longer has | `plan` reports `unattached_rows`; `backfill` attaches it |
| a detach | a marked table, attached or pending | finishes the detach (`FINALIZE` if pending), then proceeds |
| a truncate | the partition with its rows, or empty: it is one transaction | empties it, or finds it empty |
| a drop | either the table or nothing | drops it, or finds nothing to do |

## Hooks

Eight hooks fire around create, attach, detach and drop, once per **lifecycle unit** — the partition
Ten hooks fire around create, attach, detach, truncate and drop, once per **lifecycle unit** — the partition
under the root, never per leaf of its subtree — and once per member of a root `HASH` or
`LIST`. A `before_*` hook that raises aborts that operation (the partition comes back on
the next run); an `after_*` hook that raises is logged and re-raised — the operation has
Expand Down
Loading
Loading