Skip to content

Commit f150233

Browse files
feat: partition trees, boundary codecs, static roots and composite keys (#23)
feat: partition trees, boundary codecs, static roots and composite keys
2 parents 50a99b3 + a9ed268 commit f150233

66 files changed

Lines changed: 17192 additions & 435 deletions

Some content is hidden

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

‎README.md‎

Lines changed: 110 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ A single library that covers the full PostgreSQL partition lifecycle: creating p
1515

1616
- **Async and sync** — `pg_partsmith.aio` on the SQLAlchemy async engine, `pg_partsmith.sync` on the classic sync engine
1717
- **Full lifecycle** — create ahead, detach expired, drop orphans in one call
18+
- **Nested partitioning** — `RANGE(time) → HASH(column)` and `→ LIST(column)` trees, reconciled towards the configured shape on every run
19+
- **Time-free tables** — HASH or LIST roots with a fixed partition set, managed by the same reconciler
20+
- **Composite keys** — multi-column partition keys, with trailing columns bounded by `MINVALUE`
21+
- **Encoded partition keys** — partition by time even when the key is a UUIDv7 or another sortable id
1822
- **Extensible hooks** — 6 hook points (`before`/`after` create, detach, drop)
1923
- **Multiple strategies** — hourly, daily, weekly, monthly, quarterly, yearly + fully custom
2024
- **Distributed locking** — PostgreSQL advisory locks (built-in) or Redis
@@ -89,6 +93,8 @@ async def run_maintenance(engine: AsyncEngine) -> None:
8993

9094
> **Transaction semantics** — every DDL operation (CREATE, ATTACH, DETACH, DROP)
9195
> runs in its own connection and commits immediately. Use `AsyncEngine`, not `AsyncSession`.
96+
> A subpartitioned branch is built detached and attached last, so an interrupted run leaves
97+
> an unreachable table rather than a live partition that cannot route part of its keyspace.
9298
9399
> **Timezones** — everything is UTC by default. For calendar partitions in a business
94100
> timezone pass the same zone to both sides: `MonthPeriodCalculator(tz=ZoneInfo("Europe/Moscow"))`
@@ -136,6 +142,94 @@ Hooks and custom lock managers implement the sync protocols from `pg_partsmith.s
136142
- The Redis lock renews its TTL from a background thread; on renewal failure it logs a
137143
warning but cannot cancel the running maintenance (the TTL bounds a stale holder).
138144

145+
## Nested partitioning
146+
147+
A time partition can itself be a partitioned table. Add a `subpartition` spec and each
148+
period is split along a second dimension:
149+
150+
```python
151+
from pg_partsmith import HashSubpartitionSpec
152+
153+
config = TablePartitionConfig(
154+
schema="public",
155+
table_name="events",
156+
partition_type=PartitionType.RANGE,
157+
partition_strategy=PartitionStrategy.TIME_BASED,
158+
partition_column="created_at",
159+
granularity=PartitionGranularity.WEEK,
160+
create_ahead_count=3,
161+
retention_count=12,
162+
subpartition=HashSubpartitionSpec(column="tenant_id", modulus=4),
163+
)
164+
```
165+
166+
```text
167+
events
168+
├── events__2026_w35 PARTITION BY HASH (tenant_id)
169+
│ ├── events__2026_w35__h0
170+
│ ├── events__2026_w35__h1
171+
│ ├── events__2026_w35__h2
172+
│ └── events__2026_w35__h3
173+
└── events__2026_w36 …
174+
```
175+
176+
The two dimensions stay separate: **time is the lifecycle dimension** (create-ahead,
177+
retention, detach, drop, hooks all operate on the whole week) and the nested one is the
178+
distribution dimension. `retention_count=12` keeps twelve weeks, not twelve leaves.
179+
180+
`ListSubpartitionSpec` splits a period into named value sets instead
181+
(`RANGE(time) → LIST(region)`), with an optional DEFAULT catch-all; the strategies also
182+
nest into each other.
183+
184+
Maintenance converges the actual tree towards the configured one on every run: missing
185+
buckets are created, a converged tree costs **zero DDL**, and anything that cannot be
186+
repaired safely — a bucket set at an older modulus, a partition from a previous policy, a
187+
shape the config does not describe — is left intact and reported through
188+
`MaintenanceResult.issues`. See the
189+
[subpartitioning guide](https://bedrock-python.github.io/pg-partsmith/guide/subpartitioning/).
190+
191+
## Tables partitioned without a time dimension
192+
193+
A table divided only by tenant or region has a fixed set of partitions — nothing
194+
is created ahead and nothing ages out. Configure it with `root_layout`:
195+
196+
```python
197+
config = TablePartitionConfig(
198+
table_name="issue_index",
199+
partition_type=PartitionType.HASH,
200+
partition_strategy=PartitionStrategy.HASH_BASED,
201+
partition_column="organization_id",
202+
root_layout=HashSubpartitionSpec(column="organization_id", modulus=16),
203+
)
204+
```
205+
206+
Such a table needs no period calculator, and maintenance is purely
207+
reconciliation: missing partitions are created, nothing is ever pruned.
208+
209+
## Partitioning by an encoded key
210+
211+
When the partition key is a time-sortable identifier rather than a timestamp — a UUIDv7, a
212+
ULID, an epoch bigint — a boundary codec keeps the lifecycle reasoning in calendar periods
213+
while the DDL speaks the key's own language:
214+
215+
```python
216+
from pg_partsmith.boundaries import UUIDv7BoundaryCodec
217+
218+
codec = UUIDv7BoundaryCodec()
219+
220+
service = PartitionLifecycleService(
221+
repo=PostgresPartitionRepository(engine),
222+
metadata=PostgresMetadataProvider(engine, boundary_codec=codec),
223+
locks=PostgresAdvisoryLockManager(engine),
224+
period_calculator=WeekPeriodCalculator(boundary_codec=codec),
225+
)
226+
```
227+
228+
Partition names, create-ahead, and retention are unchanged; only the `FOR VALUES FROM … TO
229+
…` literals become UUIDs. Codecs are bidirectional, so retention and `is_partition_closed`
230+
keep working. See the
231+
[boundary codec guide](https://bedrock-python.github.io/pg-partsmith/guide/boundary-codecs/).
232+
139233
## Multi-schema databases
140234

141235
If your database uses multiple schemas, set `schema` in `TablePartitionConfig`. The library
@@ -306,19 +400,25 @@ scheduler.add_job(
306400

307401
**Entities** — `Period`, `PartitionInfo`, `TablePartitionConfig`, `MaintenanceResult`, `MaintenanceIssue`, `MaintenanceIssueStep`
308402

403+
**Topology** — `HashSubpartitionSpec`, `ListSubpartitionSpec`, `ListGroup`, `SubpartitionSpec`, `PartitionNode`, `RangeBounds`, `HashBounds`, `ListBounds`, `DefaultBounds`, `PartitionBounds`, `SubpartitionBounds`
404+
405+
**Reconciliation** — `SubpartitionPlan`, `SubpartitionAction`, `SubpartitionReconcileResult`, `TopologyFinding`, `TopologyReason`, `plan_subpartitions`
406+
407+
**Boundary codecs** — `RangeBoundaryCodec`, `UUIDv7BoundaryCodec`
408+
309409
**Helpers** — `qualify`, `split_qualified_name`
310410

311411
**Enums** — `PartitionType`, `PartitionGranularity`, `PartitionStrategy`
312412

313-
**Exceptions** — `PartitionError`, `PartitionAlreadyExistsError`, `PartitionNotFoundError`, `PartitionAttachedError`, `PartitionDetachInProgressError`, `InvalidPartitionConfigError`, `LockAcquisitionError`, `DropRetryExhaustedError`, `UnmanagedPartitionDropError`
413+
**Exceptions** — `PartitionError`, `PartitionAlreadyExistsError`, `PartitionNotFoundError`, `PartitionAttachedError`, `PartitionDetachInProgressError`, `InvalidPartitionConfigError`, `LockAcquisitionError`, `DropRetryExhaustedError`, `UnmanagedPartitionDropError`, `PartitionTopologyError`, `UnsupportedCapabilityError`
314414

315-
**Protocols** — `PeriodCalculator`, `TimezoneAwareCalculator`, `DdlTimezoneAware`
415+
**Protocols** — `PeriodCalculator`, `TimezoneAwareCalculator`, `DdlTimezoneAware`, `BoundaryDecoder`
316416

317417
**Strategies** — `BasePeriodCalculator`, `HourPeriodCalculator`, `DayPeriodCalculator`, `WeekPeriodCalculator`, `MonthPeriodCalculator`, `QuarterPeriodCalculator`, `YearPeriodCalculator`, `get_period_calculator`
318418

319419
### `pg_partsmith.aio`
320420

321-
**Protocols** — `PartitionRepository`, `PartitionMetadataProvider`, `LockManager`
421+
**Protocols** — `PartitionRepository`, `PartitionMetadataProvider`, `LockManager`, `SubpartitionRepository`, `NestedPartitionMetadata`, `CompositeKeyRepository`, `CompositeKeyMetadata`
322422

323423
**Hooks** — `BasePartitionLifecycleHooks`
324424

@@ -343,7 +443,13 @@ detached partitions are adopted with `repo.adopt_partition(...)` instead of disa
343443
safe-drop via `drop_allow_unmanaged`; writers that need one specific partition use
344444
`service.ensure_partition(config, period)`; scheduled ticks isolate step failures with
345445
`maintain_lifecycle(..., continue_on_error=True)` → `result.issues`; export pipelines
346-
check `metadata.is_partition_closed(name, settle_seconds=...)` before finalizing.
446+
check `metadata.is_partition_closed(name, settle_seconds=...)` before finalizing; data that
447+
predates the create-ahead window gets partitions via
448+
`service.ensure_partitions(config, periods)`.
449+
450+
For a worked example of adopting a `RANGE(UUIDv7) → HASH(tenant)` event store — including a
451+
non-uniform bucket history and custom partition names — see
452+
[Example: an event store with TIME → HASH](https://bedrock-python.github.io/pg-partsmith/guide/nested-migration/).
347453

348454
## Development
349455

‎docs/guide/boundary-codecs.md‎

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
# Boundary codecs
2+
3+
A time-based partition has two independent notions of "when":
4+
5+
- the **semantic period** — a week, a month — which decides the partition's name, its
6+
place in the create-ahead window, and when retention drops it; and
7+
- the **physical boundary** — the literal PostgreSQL compares the partition key against.
8+
9+
For a `timestamptz` key the two coincide, and there is nothing to configure. They come
10+
apart whenever the partition key is a **time-sortable identifier** rather than a
11+
timestamp: a UUIDv7, a ULID, a Snowflake id, an epoch bigint, an encoded day bucket. Such
12+
a table is still partitioned by time — the ordering of the key *is* the ordering of time —
13+
but its `FOR VALUES FROM … TO …` literals are identifiers, not dates.
14+
15+
A `RangeBoundaryCodec` bridges the two, so the lifecycle keeps reasoning in periods while
16+
the DDL speaks the key's own language.
17+
18+
```python
19+
from pg_partsmith import WeekPeriodCalculator
20+
from pg_partsmith.boundaries import UUIDv7BoundaryCodec
21+
22+
calculator = WeekPeriodCalculator(boundary_codec=UUIDv7BoundaryCodec())
23+
```
24+
25+
Everything else is unchanged. Periods, partition names, create-ahead and retention all
26+
keep working in calendar terms:
27+
28+
```python
29+
calculator.format_partition_name("events", Period(year=2026, week=35))
30+
# 'events__2026_w35'
31+
32+
calculator.get_boundaries(Period(year=2026, week=35))
33+
# ('01a03111-1c00-7000-8000-000000000000',
34+
# '01a0551d-a000-7000-8000-000000000000')
35+
```
36+
37+
## Wiring
38+
39+
Pass the same codec to the metadata provider, so it can read boundaries back:
40+
41+
```python
42+
codec = UUIDv7BoundaryCodec()
43+
44+
service = PartitionLifecycleService(
45+
repo=PostgresPartitionRepository(engine),
46+
metadata=PostgresMetadataProvider(engine, boundary_codec=codec),
47+
locks=PostgresAdvisoryLockManager(engine),
48+
period_calculator=WeekPeriodCalculator(boundary_codec=codec),
49+
)
50+
```
51+
52+
Codecs are **bidirectional on purpose**. Retention selects partitions by comparing a
53+
partition's *catalog* upper bound against the cutoff instant, and `is_partition_closed`
54+
does the same. A codec that could only encode would create partitions the library could
55+
never prune or finalize.
56+
57+
Without a codec, the metadata provider will not try to read a non-timestamp bound: it
58+
reports `is_partition_closed` as `False` rather than raising, and retention skips the
59+
partition with a warning rather than guessing.
60+
61+
## UUIDv7
62+
63+
`UUIDv7BoundaryCodec` implements RFC 9562: a 48-bit big-endian Unix-milliseconds
64+
timestamp in the leading bits, so UUIDv7 values sort chronologically.
65+
66+
Both boundaries use the **minimum** UUID for their instant — every random bit zero. Using
67+
the minimum on both ends is what makes adjacent periods exactly contiguous:
68+
69+
```text
70+
week 35: [min_uuid(2026-08-24), min_uuid(2026-08-31))
71+
week 36: [min_uuid(2026-08-31), min_uuid(2026-09-07))
72+
^^^^^^^^^^^^^^^^ the same value
73+
```
74+
75+
No identifier can fall between two partitions, so nothing silently lands in `DEFAULT`.
76+
Encoding is deterministic — the same instant always yields the same boundary — which is
77+
what makes the create path idempotent.
78+
79+
## Writing your own
80+
81+
The protocol is two methods:
82+
83+
```python
84+
from datetime import UTC, datetime
85+
86+
87+
class EpochMillisBoundaryCodec:
88+
"""Partition key is a bigint of milliseconds since the Unix epoch."""
89+
90+
def encode(self, start: datetime, end: datetime) -> tuple[str, str]:
91+
return str(int(start.timestamp() * 1000)), str(int(end.timestamp() * 1000))
92+
93+
def decode(self, literal: str) -> datetime | None:
94+
try:
95+
return datetime.fromtimestamp(int(literal) / 1000, tz=UTC)
96+
except (TypeError, ValueError):
97+
return None
98+
```
99+
100+
Two rules make a codec correct:
101+
102+
1. **`encode` is monotonic** in its argument — later instants must produce later literals
103+
in the key type's own ordering, or PostgreSQL's range bounds are meaningless.
104+
2. **Adjacent periods are contiguous** — one period's upper bound is the next period's
105+
lower bound, with no gap and no overlap.
106+
107+
`decode` should return `None` for anything carrying no instant (`MINVALUE`, `MAXVALUE`, a
108+
literal from a differently-typed key) rather than raising, so a table whose history mixes
109+
key types can still be introspected.
110+
111+
## Combining with subpartitioning
112+
113+
Boundary encoding and [subpartitioning](subpartitioning.md) are orthogonal, and compose:
114+
115+
```python
116+
config = TablePartitionConfig(
117+
table_name="events",
118+
partition_type=PartitionType.RANGE,
119+
partition_strategy=PartitionStrategy.TIME_BASED,
120+
partition_column="id", # a UUIDv7 column
121+
granularity=PartitionGranularity.WEEK,
122+
subpartition=HashSubpartitionSpec(column="tenant_id", modulus=4),
123+
)
124+
```
125+
126+
That is `RANGE(id UUIDv7)` weekly → `HASH(tenant_id)`: the time dimension picks the
127+
branch, the hash dimension picks the leaf.

‎docs/guide/configuration.md‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,23 +46,27 @@ schema=None # relies on search_path (not recommended)
4646
### `partition_type`
4747

4848
```python
49-
class PartitionType(str, Enum):
50-
RANGE = "RANGE"
51-
LIST = "LIST"
52-
HASH = "HASH"
49+
class PartitionType(StrEnum):
50+
RANGE = "range"
51+
LIST = "list"
52+
HASH = "hash"
5353
```
5454

5555
Use `RANGE` for time-based partitioning.
5656

5757
### `partition_strategy`
5858

5959
```python
60-
class PartitionStrategy(str, Enum):
61-
TIME_BASED = "TIME_BASED"
62-
VALUE_BASED = "VALUE_BASED"
63-
HASH_BASED = "HASH_BASED"
60+
class PartitionStrategy(StrEnum):
61+
TIME_BASED = "time_based"
62+
VALUE_BASED = "value_based"
63+
HASH_BASED = "hash_based"
6464
```
6565

66+
The values matter when the config comes from the environment: a
67+
`PartitionTableSettings` subclass reads `…_PARTITION_STRATEGY=time_based`, not
68+
the member name.
69+
6670
Use `TIME_BASED` for automatic period calculation via a `PeriodCalculator`.
6771

6872
### `partition_column`
@@ -75,6 +79,21 @@ partition_column="created_at"
7579
partition_column="event_date"
7680
```
7781

82+
### `trailing_partition_columns`
83+
84+
The rest of a composite partition key, in key order, when the table partitions on
85+
more than one column. Empty by default, which is the single-column case.
86+
87+
```python
88+
partition_column="created_at"
89+
trailing_partition_columns=("tenant_id",) # PARTITION BY RANGE (created_at, tenant_id)
90+
```
91+
92+
Only the leading column carries the period; the trailing ones are bounded with
93+
`MINVALUE`. Read the whole key back with `config.partition_columns` and its length
94+
with `config.key_arity`. See [Composite partition keys](subpartitioning.md#composite-partition-keys)
95+
for what a nullable trailing column does to row routing.
96+
7897
### `granularity`
7998

8099
Controls which built-in period calculator to use when one is not passed explicitly.

‎docs/guide/migration.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,39 @@ Adoption is idempotent, refuses attached partitions (`PartitionAttachedError`),
4646
`False` for names that do not resolve. The next maintenance tick collects adopted tables
4747
like any other orphan: `before_drop` hooks run, then they are dropped.
4848

49+
## Backfilling partitions for data you already have
50+
51+
`create_future_partitions` walks *forward* from the current period, which is the right
52+
behaviour for a scheduled tick and the wrong one for a migration: the rows already in the
53+
table live in periods create-ahead will never reach.
54+
55+
`ensure_partitions` takes the periods from you instead:
56+
57+
```python
58+
calculator = MonthPeriodCalculator()
59+
current = calculator.current_period()
60+
61+
# every month of the last two years, oldest first
62+
past = [calculator.period_before(current, n) for n in reversed(range(1, 25))]
63+
64+
created = await service.ensure_partitions(config, past)
65+
```
66+
67+
It is idempotent — periods that already have a partition are skipped, and a second run
68+
creates nothing — so it is safe to call from a migration that may be retried. The
69+
catalogue is read once for the whole batch, not once per period.
70+
71+
Two things worth knowing:
72+
73+
- **Only create what you need.** Partitions outside `retention_count` are pruned by the
74+
next maintenance tick. Backfilling further back than your retention window creates
75+
tables that the following run immediately detaches and drops.
76+
- **Subpartitioned configs get complete branches.** Each backfilled period is built with
77+
its full bucket set before it is attached, exactly as create-ahead does.
78+
79+
For a single period — a writer that must guarantee its target partition exists before an
80+
insert — use `ensure_partition(config, period)`.
81+
4982
## Partition names are schema-qualified
5083

5184
`list_partitions` returns names as `schema.relname` (e.g. `public.events__2024_01`) — a

0 commit comments

Comments
 (0)