Skip to content

Commit 2d4ac4c

Browse files
committed
Merge remote-tracking branch 'origin/master' into test/regenerate-sync-integration-mirror
2 parents 60e78cd + 1f95e78 commit 2d4ac4c

84 files changed

Lines changed: 3314 additions & 180 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,45 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## 1.11.0 — expired partitions can be emptied in place
9+
10+
A retention policy could only take an expired partition out of the tree: detach it, then
11+
drop it or keep it. A project that empties expired partitions in place, as data-rentgen's
12+
`cleanup_partitions truncate` does, could not switch without changing what its operators
13+
see ([#130](https://github.com/bedrock-python/pg-partsmith/issues/130)).
14+
15+
**What is new:** `LifecyclePolicy(expire=ExpireAction.TRUNCATE)`, `expire: truncate` in a
16+
document, empties an expired partition with `TRUNCATE` and leaves it attached. The plan
17+
carries a `TruncatePartition` (kind `truncate`), the result a `truncated_count`, and hooks
18+
get `before_truncate` / `after_truncate`, which a document's `hooks` section takes too. The
19+
truncate locks the partition and the relations below it and never the parent, so writers to
20+
the other partitions do not wait for it, where a blocking detach holds the whole parent. A
21+
partition that is empty already gets no operation, and one `expired_empty` finding per
22+
parent counts them. One that a foreign key reaches, which PostgreSQL refuses to truncate
23+
whether or not a row is referenced, is reported as `truncate_blocked` rather than failing
24+
the run, and so is one whose subtree holds a foreign table, whose remote table `TRUNCATE`
25+
would empty, including a key or a foreign table that appears after the plan was made.
26+
`apply` without
27+
`--allow-destructive` and `maintain(skip_detach=True)` leave truncates out.
28+
29+
**What stays:** the default is `ExpireAction.DETACH`, and a policy that names no `expire`
30+
plans exactly as before.
31+
32+
**What to check:** a repository of your own has to implement
33+
`PartitionRepository.truncate_partition`, a metadata provider of your own has to answer
34+
`FactKind.EMPTY` and `FactKind.REFERENCING_TABLES` in `measure` (or every expired partition
35+
is truncated on every run), and a hook class that implements the protocol without
36+
subclassing `BasePartitionLifecycleHooks` needs `before_truncate` and `after_truncate`
37+
before it runs under `expire=truncate`. The policy serializes one more field, so
38+
`apply --plan` refuses a plan saved by 1.10 as made under another configuration: plan
39+
again, or pass `--allow-config-drift`. Before switching a table to `expire=truncate`, check
40+
three things: the role needs the `TRUNCATE` privilege on its partitions, which owning the
41+
parent does not give on partitions another role created; its publications, since logical
42+
replication carries a `TRUNCATE`, which it never did for a detach or a drop, so a subscriber
43+
keeping more history needs `truncate` left out of `publish`; and its readers, since a query
44+
pruned only when it runs, a `now()`-relative one say, waits for a truncate queued behind a
45+
reader of the expired partition, up to `ddl_lock_timeout_ms`.
46+
847
## [1.10.0](https://github.com/bedrock-python/pg-partsmith/compare/pg-partsmith-v1.9.0...pg-partsmith-v1.10.0) (2026-10-17)
948

1049

‎README.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@ Something else is probably the better fit when:
6767
integers, your own codec); fixed-width integer windows for id-partitioned queues
6868
- **Lifecycle policies** — create ahead by count, until a horizon or when the newest
6969
partition says so; expire by count, age or distance, or by a predicate (size, rows,
70-
foreign-key references, SQL); detach now, drop after a grace period
70+
foreign-key references, SQL); detach now, drop after a grace period, or empty in place
71+
and leave the partition attached
7172
- **Leaf backends** — local tables with a tablespace, storage parameters and the parent's
7273
grants, or foreign tables on an FDW server (`postgres_fdw`, ClickHouse)
7374
- **Batched data movement** — drain a DEFAULT partition into lifecycle partitions
@@ -86,7 +87,7 @@ Something else is probably the better fit when:
8687
CronJob / init container, CI and systemd
8788
- **Examples that are tested** — every document under `examples/` validates in CI, the hook
8889
scripts parse, and `pg-partsmith schema` gives an editor the JSON Schema
89-
- **Hooks, locks, schemas** — eight lifecycle hooks, in Python or as commands named in a
90+
- **Hooks, locks, schemas** — ten lifecycle hooks, in Python or as commands named in a
9091
config file; PostgreSQL advisory or Redis locks; schema-qualified everything
9192
- **Type-safe, tested** — Pydantic models, full mypy, real PostgreSQL 15 through 18 via testcontainers
9293

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

‎docs/agents.md‎

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ a method that sounds plausible.
3333
## Scope
3434

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

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

219221
### Levels
220222

@@ -242,6 +244,7 @@ Nesting is `child=`, up to five levels including the root.
242244
|---|---|
243245
| `creation` | `CreateAhead(count)`, `CreateUntil(position)`, `CreateNextIf(when)` |
244246
| `retention` | `KeepNewest(count)`, `KeepFor(age)`, `KeepBehind(distance)`, `ExpireIf(when)` |
247+
| `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 |
245248
| `detach` | `DetachMode.AUTO` (concurrent where PostgreSQL allows), `.CONCURRENT`, `.BLOCKING` |
246249
| `drop` | `DropAfter(grace, when=None)`, `DropNever()` |
247250
| predicates | `SizeAbove(bytes)`, `RowsAbove(rows)`, `WindowAgeAbove(age)`, `Unreferenced()`, `SqlPredicate(sql)`, `Callback(fn, facts, label)` |
@@ -293,8 +296,8 @@ error (`LockLostError`).
293296
`EXPLICIT` (only the windows named in `windows=`).
294297

295298
On a `MaintenancePlan`: `.operations`, `.findings`, `.cursors`, `.generated_at`,
296-
`.config_fingerprint`, `.creates` / `.attaches` / `.detaches` / `.drops`, `.is_noop`,
297-
`.only(*kinds)`, `.without(*kinds)`, `.describe()`. Filtering a plan and applying the rest
299+
`.config_fingerprint`, `.creates` / `.attaches` / `.detaches` / `.truncates` / `.drops`,
300+
`.is_noop`, `.only(*kinds)`, `.without(*kinds)`, `.describe()`. Filtering a plan and applying the rest
298301
is supported and is how you split creation from pruning across schedules.
299302

300303
Every operation dumps its `capabilities` (the heaviest lock it takes, and whether it can
@@ -312,11 +315,11 @@ still the same intent.
312315
Results:
313316

314317
* `MaintenanceResult` — `created_count`, `repaired_count`, `attached_count`,
315-
`detached_count`, `dropped_count`, `duration_ms`, `error`, `issues`, `.success`,
316-
`.maintenance_plan`.
318+
`detached_count`, `truncated_count`, `dropped_count`, `duration_ms`, `error`, `issues`,
319+
`.success`, `.maintenance_plan`.
317320
* `MigrationResult` — `rows_moved`, `batches`, `partitions`, `complete`, `issues`. Call
318321
again while `complete` is `False`.
319-
* `MaintenanceIssue` — `step` (`create` `reconcile` `attach` `detach` `drop` `move`),
322+
* `MaintenanceIssue` — `step` (`create` `reconcile` `attach` `detach` `truncate` `drop` `move`),
320323
`error` (`"TypeName: message"`), `partition_name`.
321324

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

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

‎docs/concepts/execution.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,10 +128,11 @@ repository).
128128

129129
## Waiting for a lock
130130

131-
An attach, a row move and a blocking detach each run under `lock_timeout`
131+
An attach, a row move, a blocking detach and a truncate each run under `lock_timeout`
132132
(`ddl_lock_timeout_ms` on the repository, 3000 by default). A statement waiting for a lock
133133
keeps its place in PostgreSQL's queue, and every session that asks for a conflicting lock
134-
after it waits behind it; for the locks these steps take, that is every writer of the table.
134+
after it waits behind it; for the locks the first three take, that is every writer of the
135+
table, and for a truncate every query that has to lock the partition it empties.
135136
The move-and-attach holds `EXCLUSIVE` on the parent while it waits for the DEFAULT
136137
partition, so a reader holding the table for a minute would otherwise stop writes for that
137138
minute.
@@ -154,6 +155,7 @@ writers and runs without one.
154155
| 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 |
155156
| `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 |
156157
| `DETACH PARTITION … CONCURRENTLY` | `SHARE UPDATE EXCLUSIVE` on the parent; `ACCESS EXCLUSIVE` on the partition and, in its second transaction, on referencing tables |
158+
| `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 |
157159
| `DROP TABLE` of a detached table | `ACCESS EXCLUSIVE` on that table only |
158160
| `COMMENT ON` | `SHARE UPDATE EXCLUSIVE` on the table |
159161
| 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 |
@@ -189,11 +191,12 @@ one of a small number of states, each of which the next run converges:
189191
| creating a partition or its subtree | a detached, unmarked table, unreachable by writers | completes the subtree, attaches it |
190192
| 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 |
191193
| a detach | a marked table, attached or pending | finishes the detach (`FINALIZE` if pending), then proceeds |
194+
| a truncate | the partition with its rows, or empty: it is one transaction | empties it, or finds it empty |
192195
| a drop | either the table or nothing | drops it, or finds nothing to do |
193196

194197
## Hooks
195198

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

0 commit comments

Comments
 (0)