Skip to content

Commit be8a9e3

Browse files
feat: migration-ergonomics APIs — ensure_partition, adopt_partition, continue_on_error, is_partition_closed (#18)
Extracted from a real migration of a hand-rolled partitioner: create one specific period with full reconciliation, adopt legacy detached tables instead of disabling safe-drop, isolate per-step maintenance failures into MaintenanceResult.issues, check partition closure server-side for export pipelines, and expose PartitionInfo schema/relname accessors. Adds the 'Migrating an existing partitioner' guide and refreshes lock/safe-drop docs.
1 parent a8f5201 commit be8a9e3

36 files changed

Lines changed: 1742 additions & 49 deletions

‎CHANGELOG.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,29 @@ 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+
## [Unreleased]
9+
10+
### Added
11+
12+
- Migration-ergonomics APIs (all mirrored in `aio` and `sync`), extracted from a real
13+
migration of a hand-rolled partitioner:
14+
- `service.ensure_partition(config, period)` — create and attach the partition for one
15+
specific period (idempotent, with DEFAULT reconciliation and attach-race handling);
16+
for writers that must guarantee a partition exists before an insert.
17+
- `repository.adopt_partition(table_name, partition_name)` — stamp the orphan marker on
18+
a legacy detached table so safe-drop accepts it, instead of disabling the guard with
19+
`drop_allow_unmanaged`.
20+
- `maintain_lifecycle(..., continue_on_error=True)` (also on the maintainer and
21+
`maintain_partitions`) — isolate create/detach/drop failures into the new
22+
`MaintenanceResult.issues` (`MaintenanceIssue`) instead of aborting the run.
23+
- `metadata.is_partition_closed(partition_name, *, settle_seconds=0)` — server-side
24+
"the partition's upper bound has passed (+ settle buffer)" check for export pipelines.
25+
- `PartitionInfo.schema_name` / `PartitionInfo.relname` accessors; `qualify`,
26+
`split_qualified_name`, and `MaintenanceIssue` are exported from the package root.
27+
- "Migrating an existing partitioner" documentation guide: retention count-vs-distance,
28+
adopting legacy partitions, schema-qualified names, lock ownership of granular calls,
29+
per-step error isolation, and export finalization.
30+
831
## [0.2.0](https://github.com/bedrock-python/pg-partsmith/compare/pg-partsmith-v0.1.0...pg-partsmith-v0.2.0) (2026-08-26)
932

1033
### Added

‎README.md‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,9 @@ scheduler.add_job(
298298

299299
### `pg_partsmith`
300300

301-
**Entities** — `Period`, `PartitionInfo`, `TablePartitionConfig`, `MaintenanceResult`, `MaintenanceIssueStep`
301+
**Entities** — `Period`, `PartitionInfo`, `TablePartitionConfig`, `MaintenanceResult`, `MaintenanceIssue`, `MaintenanceIssueStep`
302+
303+
**Helpers** — `qualify`, `split_qualified_name`
302304

303305
**Enums** — `PartitionType`, `PartitionGranularity`, `PartitionStrategy`
304306

@@ -327,6 +329,16 @@ scheduler.add_job(
327329
Synchronous mirror of `pg_partsmith.aio` — same names, same layout, plain methods
328330
built on the sync SQLAlchemy `Engine`.
329331

332+
## Migrating from a hand-rolled partitioner
333+
334+
The [migration guide](https://bedrock-python.github.io/pg-partsmith/guide/migration/)
335+
covers the traps: retention is a **count**, not a distance (`old_distance + 1`); legacy
336+
detached partitions are adopted with `repo.adopt_partition(...)` instead of disabling
337+
safe-drop via `drop_allow_unmanaged`; writers that need one specific partition use
338+
`service.ensure_partition(config, period)`; scheduled ticks isolate step failures with
339+
`maintain_lifecycle(..., continue_on_error=True)` → `result.issues`; export pipelines
340+
check `metadata.is_partition_closed(name, settle_seconds=...)` before finalizing.
341+
330342
## Development
331343

332344
```bash

‎docs/guide/advanced.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ To override (not recommended):
6565
repo = PostgresPartitionRepository(engine, drop_allow_unmanaged=True)
6666
```
6767

68+
Legacy tables detached by a previous partitioner are better handled with
69+
`repo.adopt_partition(table_name, partition_name)` — it stamps the marker once so the
70+
normal safe path applies, instead of disabling the guard for every future drop. See
71+
[Migrating an existing partitioner](migration.md).
72+
6873
An attempt to drop an unmanaged table raises `UnmanagedPartitionDropError`.
6974
Attempting to drop an attached partition raises `PartitionAttachedError` (which
7075
`PartitionLifecycleService` treats as a warning and skips).

‎docs/guide/locks.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,18 @@ custom implementation satisfies the protocol with `isinstance()`.
6767

6868
Each lock is scoped to `{prefix}:{schema}.{table_name}`, so multiple tables can be
6969
maintained in parallel without blocking each other.
70+
71+
## Who takes the lock
72+
73+
Only `maintain_lifecycle` (and the maintainer on top of it) acquires the lock itself.
74+
The granular service methods — `create_future_partitions`, `ensure_partition`,
75+
`detach_old_partitions`, `drop_detached_partitions` — do **not**: when orchestrating them
76+
directly, hold `locks.acquire_lock(table)` around the whole sequence yourself.
77+
78+
Acquisition is non-blocking (`pg_try_advisory_lock` / Redis `SET NX`): a tick that
79+
collides with another replica raises `LockAcquisitionError` immediately instead of
80+
queueing. Scheduled jobs typically catch it and skip the tick.
81+
82+
The PostgreSQL manager holds the lock on a dedicated AUTOCOMMIT connection, so it
83+
survives commits/rollbacks on the caller's session and can safely span
84+
`DETACH PARTITION CONCURRENTLY`.

‎docs/guide/migration.md‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
# Migrating an existing partitioner
2+
3+
This guide covers the traps we have seen real projects hit when replacing a hand-rolled
4+
partition maintenance script with pg-partsmith. Read it before the first production tick.
5+
6+
## Retention: count, not distance
7+
8+
Hand-rolled pruners usually express retention as a *distance*: "drop everything older than
9+
`N` periods from now", which keeps `N + 1` partitions on disk (the current one plus `N`
10+
past). pg-partsmith's `retention_count` is a *count*: "keep exactly `N` newest periods,
11+
current one included".
12+
13+
Passing a distance straight into `retention_count` silently drops one extra period of data
14+
on the first tick after deploy. Convert once, at the boundary:
15+
16+
```python
17+
config = TablePartitionConfig(
18+
...,
19+
# old semantics: "keep current + N past periods"
20+
retention_count=old_retention_distance + 1,
21+
)
22+
```
23+
24+
Verify on a staging copy: run one maintenance tick and compare the set of surviving
25+
partitions with what the old pruner would have kept.
26+
27+
## Adopting legacy detached partitions
28+
29+
pg-partsmith only ever drops tables that carry its `COMMENT` marker (see
30+
[Advanced](advanced.md)). The marker is stamped automatically when *the library* detaches a
31+
partition — so partitions that are attached at migration time need nothing: the first
32+
maintenance tick detaches and marks them itself.
33+
34+
The one case that needs action is tables your *old* partitioner already detached and never
35+
dropped (a failed export, a crashed run). They carry no marker, so they are invisible to
36+
orphan discovery and will sit there forever. **Do not reach for `drop_allow_unmanaged=True`
37+
to handle them** — that disables the safe-drop guard for every drop, permanently, and does
38+
not even help: unmarked detached tables are never discovered in the first place. Adopt them
39+
once instead:
40+
41+
```python
42+
repo.adopt_partition("events", "events__2024_01") # stamps the marker; True when done
43+
```
44+
45+
Adoption is idempotent, refuses attached partitions (`PartitionAttachedError`), and returns
46+
`False` for names that do not resolve. The next maintenance tick collects adopted tables
47+
like any other orphan: `before_drop` hooks run, then they are dropped.
48+
49+
## Partition names are schema-qualified
50+
51+
`list_partitions` returns names as `schema.relname` (e.g. `public.events__2024_01`) — a
52+
partition may live in a different schema than its parent, and a bare name could resolve to
53+
an unrelated table through `search_path`. Code that works with bare names (period parsing,
54+
export layouts) should use the accessors instead of splitting strings:
55+
56+
```python
57+
for p in metadata.list_partitions("events"):
58+
p.name # "public.events__2024_01" — use for DDL and library calls
59+
p.relname # "events__2024_01" — use for parsing / external layouts
60+
p.schema_name # "public" (None if the name is unqualified)
61+
```
62+
63+
## Mapping partitions back to periods
64+
65+
There is no need for custom catalogue queries to answer "which period does this partition
66+
hold" — combine `list_partitions` with the calculator you already have:
67+
68+
```python
69+
calc = get_period_calculator(config.granularity)
70+
by_period = {
71+
period: p
72+
for p in metadata.list_partitions("events")
73+
if p.is_attached and (period := calc.parse_partition_name(p.relname)) is not None
74+
}
75+
```
76+
77+
## Who takes the lock
78+
79+
`maintain_lifecycle` (and the maintainer on top of it) takes the distributed lock itself.
80+
The granular service methods — `create_future_partitions`, `ensure_partition`,
81+
`get_partitions_for_pruning`, `detach_old_partitions`, `drop_detached_partitions` — do
82+
**not**: when you orchestrate them yourself, hold the lock around the whole sequence:
83+
84+
```python
85+
with locks.acquire_lock("events"):
86+
service.create_future_partitions(config)
87+
...
88+
```
89+
90+
The advisory lock is non-blocking (`pg_try_advisory_lock`): a tick that collides with
91+
another replica raises `LockAcquisitionError` immediately. Catch it and skip the tick —
92+
the schedule brings it back.
93+
94+
## Creating one specific partition
95+
96+
`create_future_partitions` covers the scheduled create-ahead path. When a *writer* must
97+
guarantee a partition exists before an insert (an hourly buffer, a backfill for a past
98+
period), use `ensure_partition` — it targets exactly one period and runs the same DEFAULT
99+
reconciliation and attach-race handling:
100+
101+
```python
102+
service.ensure_partition(config, Period(year=2026, month=8, day=27, hour=14))
103+
```
104+
105+
Do not hand-roll `create_partition` + `attach_partition` for this: the raw repository
106+
calls skip reconciliation, so rows sitting in a DEFAULT partition or a concurrent worker
107+
will fail the attach.
108+
109+
## One failed step should not stop the tick
110+
111+
By default `maintain_lifecycle` aborts on the first error. For a scheduled tick you
112+
usually want the opposite — a failed create must not prevent pruning (which may free the
113+
very space create needs):
114+
115+
```python
116+
result = maintainer.run_maintenance_safe(config, continue_on_error=True)
117+
for issue in result.issues:
118+
log.warning("step failed", step=issue.step, error=issue.error)
119+
```
120+
121+
Step failures land in `result.issues` (`MaintenanceIssue`) instead of aborting;
122+
validation and lock failures are still fatal.
123+
124+
## Export pipelines: when is a partition finished?
125+
126+
Incremental exporters need to know when a partition can no longer receive rows so they can
127+
finalize it. `is_partition_closed` answers this with a single server-side check — `now()`
128+
and the partition bound come from the same query, so replica lag and app-clock skew do not
129+
skew the answer:
130+
131+
```python
132+
if metadata.is_partition_closed("public.events__2026_07", settle_seconds=900):
133+
finalize_export(...)
134+
```
135+
136+
Exports that must happen *before* a partition is dropped belong in a `before_drop` hook:
137+
raising there aborts that partition's drop, and the orphan marker retries it next tick.

‎docs/guide/quickstart.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,3 +136,5 @@ Each step runs only what is needed; idempotent re-runs are safe.
136136
- [Configuration](configuration.md) — full `TablePartitionConfig` reference
137137
- [Lifecycle hooks](hooks.md) — react to create / detach / drop events
138138
- [Advanced](advanced.md) — multi-schema, DEFAULT partition handling, timezone semantics
139+
- [Migrating an existing partitioner](migration.md) — retention semantics, adopting legacy
140+
partitions, lock ownership, per-step error isolation

‎pg_partsmith/__init__.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from .__version__ import __version__
44
from .entities import (
5+
MaintenanceIssue,
56
MaintenanceIssueStep,
67
MaintenanceResult,
78
PartitionGranularity,
@@ -33,6 +34,7 @@
3334
YearPeriodCalculator,
3435
)
3536
from .strategies.selector import get_period_calculator
37+
from .utils import qualify, split_qualified_name
3638

3739
__all__ = [
3840
"BasePeriodCalculator",
@@ -41,6 +43,7 @@
4143
"HourPeriodCalculator",
4244
"InvalidPartitionConfigError",
4345
"LockAcquisitionError",
46+
"MaintenanceIssue",
4447
"MaintenanceIssueStep",
4548
"MaintenanceResult",
4649
"MonthPeriodCalculator",
@@ -62,4 +65,6 @@
6265
"YearPeriodCalculator",
6366
"__version__",
6467
"get_period_calculator",
68+
"qualify",
69+
"split_qualified_name",
6570
]

‎pg_partsmith/aio/maintainer.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ async def run_maintenance(
3939
skip_create: bool = False,
4040
skip_detach: bool = False,
4141
skip_drop: bool = False,
42+
continue_on_error: bool = False,
4243
) -> MaintenanceResult:
4344
"""Execute full partition lifecycle maintenance.
4445
@@ -47,6 +48,8 @@ async def run_maintenance(
4748
skip_create: Skip creating future partitions.
4849
skip_detach: Skip detaching old partitions.
4950
skip_drop: Skip dropping detached partitions.
51+
continue_on_error: Isolate step failures into ``result.issues``
52+
instead of aborting the run (see ``maintain_lifecycle``).
5053
5154
Returns:
5255
Maintenance result with counts and duration.
@@ -70,7 +73,11 @@ async def run_maintenance(
7073

7174
try:
7275
result = await self._service.maintain_lifecycle(
73-
config, skip_create=skip_create, skip_detach=skip_detach, skip_drop=skip_drop
76+
config,
77+
skip_create=skip_create,
78+
skip_detach=skip_detach,
79+
skip_drop=skip_drop,
80+
continue_on_error=continue_on_error,
7481
)
7582

7683
duration_ms = int((time.perf_counter() - start_time) * 1000)
@@ -143,6 +150,7 @@ async def run_maintenance_safe(
143150
skip_create: bool = False,
144151
skip_detach: bool = False,
145152
skip_drop: bool = False,
153+
continue_on_error: bool = False,
146154
) -> MaintenanceResult:
147155
"""Run maintenance and always return ``MaintenanceResult``, never raise.
148156
@@ -156,6 +164,8 @@ async def run_maintenance_safe(
156164
skip_create: Skip creating future partitions.
157165
skip_detach: Skip detaching old partitions.
158166
skip_drop: Skip dropping detached partitions.
167+
continue_on_error: Isolate step failures into ``result.issues``
168+
instead of aborting the run (see ``maintain_lifecycle``).
159169
160170
Returns:
161171
``MaintenanceResult`` with counts on success or ``error`` set on failure.
@@ -167,6 +177,7 @@ async def run_maintenance_safe(
167177
skip_create=skip_create,
168178
skip_detach=skip_detach,
169179
skip_drop=skip_drop,
180+
continue_on_error=continue_on_error,
170181
)
171182
except (asyncio.CancelledError, KeyboardInterrupt, SystemExit) as e:
172183
duration_ms = int((time.perf_counter() - start_time) * 1000)
@@ -187,6 +198,7 @@ async def maintain_partitions(
187198
skip_create: bool = False,
188199
skip_detach: bool = False,
189200
skip_drop: bool = False,
201+
continue_on_error: bool = False,
190202
) -> MaintenanceResult:
191203
"""Convenience wrapper for scheduler integrations.
192204
@@ -197,4 +209,5 @@ async def maintain_partitions(
197209
skip_create=skip_create,
198210
skip_detach=skip_detach,
199211
skip_drop=skip_drop,
212+
continue_on_error=continue_on_error,
200213
)

‎pg_partsmith/aio/metadata.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,49 @@ def _normalize(expr: str) -> str:
447447

448448
return _normalize(from_part), _normalize(to_part)
449449

450+
async def is_partition_closed(self, partition_name: str, *, settle_seconds: int = 0) -> bool:
451+
"""True when the partition's upper bound (+ settle buffer) has passed.
452+
453+
The comparison runs entirely server-side — ``now()`` and the bound come
454+
from the same query — so it tolerates replica lag and app-clock skew.
455+
Useful for export/archive pipelines that must only finalize partitions
456+
that can no longer receive in-range rows.
457+
458+
Args:
459+
partition_name: Attached partition table name.
460+
settle_seconds: Extra buffer after the upper bound for late writers
461+
still holding open transactions.
462+
463+
Returns:
464+
True when ``now() >= upper_bound + settle_seconds``. False for the
465+
DEFAULT partition, non-RANGE partitions, unbounded upper bounds
466+
(MAXVALUE / infinity), detached tables, and unresolvable names.
467+
"""
468+
async with self._engine.connect() as conn:
469+
result = await conn.execute(
470+
text(
471+
"""
472+
SELECT now() >= b.upper_bound + make_interval(secs => :settle_seconds)
473+
FROM (
474+
SELECT (regexp_match(
475+
pg_get_expr(c.relpartbound, c.oid),
476+
'TO \\(''([^'']+)'''
477+
))[1]::timestamptz AS upper_bound
478+
FROM pg_class c
479+
JOIN pg_inherits i ON i.inhrelid = c.oid
480+
JOIN pg_partitioned_table pt ON pt.partrelid = i.inhparent
481+
WHERE c.oid = to_regclass(:partition_name)
482+
AND pt.partstrat = 'r'
483+
) AS b
484+
"""
485+
),
486+
{
487+
"partition_name": to_regclass_argument(partition_name),
488+
"settle_seconds": settle_seconds,
489+
},
490+
)
491+
return bool(result.scalar())
492+
450493
async def get_default_partition(self, table_name: str) -> PartitionInfo | None:
451494
"""Get DEFAULT partition for a table if it exists and is attached.
452495

‎pg_partsmith/aio/protocols.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ async def maintain_lifecycle(
3030
skip_create: bool = False,
3131
skip_detach: bool = False,
3232
skip_drop: bool = False,
33+
continue_on_error: bool = False,
3334
) -> MaintenanceResult: ...
3435

3536

0 commit comments

Comments
 (0)