Skip to content

feat: partition trees, boundary codecs, static roots and composite keys - #23

Merged
AlexeyShalaev merged 35 commits into
masterfrom
feat/0.5.0-nested-partitioning
Aug 28, 2026
Merged

AlexeyShalaev merged 35 commits into
masterfrom
feat/0.5.0-nested-partitioning

Conversation

@AlexeyShalaev

@AlexeyShalaev AlexeyShalaev commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

Makes pg-partsmith able to manage partition trees, decouples the semantic period from the physical partition key, and lets a partitioned table have no time dimension at all.

The driving question was: what does a real project have to build for itself that a generic partition manager should be doing? GlitchTip 6 dropped pg_partman for a hand-rolled PartitionManager, so its topology — RANGE(id UUIDv7) → HASH(organization_id), weekly, with a bucket count that changed over time — was used as the target to design against. Nothing GlitchTip-specific enters the library.

What this adds

Nested partitioning. A partition can now be a partitioned table in its own right, by HASH or by LIST:

subpartition=HashSubpartitionSpec(column="tenant_id", modulus=4)
subpartition=ListSubpartitionSpec(column="region", groups=(...), include_default=True)

Time stays the lifecycle dimension — create-ahead, retention, detach, drop and hooks all act on the whole branch, and retention_count counts periods, not leaves. The nested level is the distribution dimension. Strategies compose freely: RANGE(time) → LIST(region) → HASH(tenant_id).

Convergent reconciliation. Between create and prune, each attached branch is compared against the spec and only genuinely missing children are created. What it refuses to do matters as much:

Actual state Action
Missing hash buckets at the configured modulus create exactly those
Complete at the configured modulus nothing — zero DDL
Complete at a different modulus preserve (changing a modulus needs a rewrite)
Incomplete at a different modulus repair at its own modulus — any other would overlap
A plain leaf predating the policy leave valid; new periods use the new topology
LIST group present under another name but the same values leave it
LIST group whose value another partition owns report; a value belongs to one partition
A shape the config does not describe report via MaintenanceResult.issues, never "fix"

Mixed hash moduli are checked for actual coverage over the lcm rather than assumed broken — PostgreSQL permits them when residue classes do not overlap, and a legal non-uniform tiling is left alone.

Boundary codecs. For a key that is time-sortable but not a timestamp (UUIDv7, ULID, Snowflake, epoch bigint):

WeekPeriodCalculator(boundary_codec=UUIDv7BoundaryCodec())

Names, create-ahead and retention keep working in calendar terms; only the FOR VALUES literals change. Codecs are bidirectional on purpose — retention compares catalog upper bounds, so an encode-only codec would create partitions the library could never prune.

Tables with no time dimension. HASH_BASED and VALUE_BASED existed as enum members but were rejected; they now work via root_layout. Such a table has a fixed partition set, needs no period calculator, and maintenance is purely reconciliation — nothing is created ahead and nothing ages out.

Composite partition keys. partition_column="created_at" plus trailing_partition_columns=("tenant_id",), at the root and at any nested level. Only the leading column carries the period; trailing ones are bounded with MINVALUE. A trailing column that is nullable changes row routing — PostgreSQL adds IS NOT NULL for every key column, so a NULL sends the row to DEFAULT whatever its period. Documented, and the DEFAULT-conflict path handles it.

Backfill. ensure_partitions(config, periods) gives partitions to data already in the table, reading the catalogue once for the whole batch.

Decisions worth reviewing

Ordering instead of a subtree transaction. A branch is built detached and attached last, so reachability from the root is the commit point: every intermediate state is either "not there" or "complete". An interrupted run leaves an unreachable table, never a live branch that rejects part of its keyspace. This keeps the existing per-statement transaction semantics. Alternatives A/B/C are written up in the subpartitioning guide.

Repairs use ATTACH, not CREATE … PARTITION OF. Measured on PostgreSQL 17:

Statement Lock on the branch
ALTER TABLE branch ATTACH PARTITION leaf SHARE UPDATE EXCLUSIVE — DML continues
CREATE TABLE leaf PARTITION OF branch ACCESS EXCLUSIVE — writers stall

Branch creation via LIKE root takes only ACCESS SHARE on the live table.

One caveat the first version of this PR left out, also measured: if the branch has a
DEFAULT partition, ATTACH takes ACCESS EXCLUSIVE on that partition while it
scans it. Other buckets keep serving; anything touching the DEFAULT waits. A fully
tiled branch has no DEFAULT and pays nothing.

Key order is not column order. The composite-key query unnests partattrs WITH ORDINALITY; ordering by attnum — as the older single-column query does — would silently transpose a composite key.

Included bug fix

fix: exclude identity columns when creating partitions is independent of the features. Partitions are created with LIKE … INCLUDING ALL, which copies an identity column, and PostgreSQL then refuses to attach them — so a root declared GENERATED ALWAYS AS IDENTITY could not be partitioned at all, on the flat path too. Verified that this fails identically on master, so it is not a regression introduced here.

Commits

Not squashed — each is independently green (ruff + ruff format + mypy + unit tests, verified with git rebase --exec):

Commit Unit tests at that commit
refactor: introduce the partition-tree domain model —
feat: add boundary codecs for time-sortable partition keys —
feat: manage nested RANGE -> HASH partition trees —
feat: add ensure_partitions for backfilling explicit periods —
fix: exclude identity columns when creating partitions —
docs: document subpartitioning, boundary codecs and the migration path —
feat: add LIST subpartitioning alongside HASH —
feat: manage HASH and LIST roots that have no time dimension —
feat: support composite partition keys —
fix: keep doubled quotes from splitting a LIST bound —
fix: keep partition_column in serialized configuration —
docs: add the new boundary and bounds names to the API reference —
fix: explain a partition that can never report as closed —
fix: spell a partition key as one leading column plus a trailing tuple —
fix: stop the planner abandoning subtrees and planning unusable names —
fix: tell a lost race apart from a real conflict, and isolate each branch —
fix: tell NULL from 'NULL', and a hidden child from a missing one —
fix: answer "is it closed?" instead of raising, and refuse a key we cannot address —
fix: leave NULL-keyed rows where PostgreSQL puts them —
test: confirm the four semantics against a real PostgreSQL —
docs: say what the database reported, not what was assumed —
test: cover the paths that were only ever exercised by accident —
test: assert the attach ordering instead of the fixture that set it up —
docs: correct three more claims, and test the one that was only written down —
docs: say that issues now fills up on a successful run —
docs: name the difference between two fields called partition_type —
test: satisfy the protocol checks the way Python 3.12 checks them —
fix: read the whole key, every constraint, and the timezone that wrote the bound 936
fix: never publish a branch that cannot route its whole keyspace 936
test: kill the mutations the suite was letting through 951
docs: correct what the fact-checker falsified, and add what it found missing 964
fix: quoting hazards that only a hand-built statement can reach 964
test: measure branch coverage, and cover the branches it exposed 994

Second review round

Five more independent agents went over the branch after the first remediation —
correctness/concurrency, PostgreSQL semantics, API compatibility, mutation testing, and
fact-checking every documented claim. They found 2 critical defects, 7 major, 10 minor,
11 false documentation claims, and 40 of 124 source mutations surviving the test suite.

Everything material is fixed here.

Critical

A branch was attached with a hole in its keyspace, and nothing reported it. A refused
child ATTACH was recorded as a finding and then ignored — the loop attached the parent
anyway. Worse, on the creation path the finding was discarded: build_new_branch called
materialize() with no collector, and the collector it makes for itself was thrown away
unread, so nothing was even logged. Reproduced end to end on PostgreSQL 17:
ensure_partition returned a successful PartitionInfo for a branch that then rejected
56 of 200 inserts. A node whose child was refused is now left detached and reported, and
build_new_branch raises rather than handing back a count for a subtree it could not
finish.

reconcile_default_rows moved rows by column position. RETURNING * into an
unqualified INSERT binds the DEFAULT partition's physical order to the target's.
ATTACH PARTITION matches columns by name, so the two orders need not agree — and when
they do not, values are silently transposed with the source rows already deleted.
Reproduced: label and note swapped, no error, on the automatic conflict-retry path.
Both sides name their columns now.

Major

Found Fix
PARTITION_TREE_SQL inner-joined pg_attribute, dropping expression key positions — and a shortened key compares equal to a one-column spec, so COLUMN_MISMATCH never fired LEFT JOIN; nodes carry has_expression_key and the planner refuses them
The unique-constraint pre-flight check missed bare CREATE UNIQUE INDEX and EXCLUDE constraints, both of which LIKE … INCLUDING ALL copies reads pg_index, unions in exclusion constraints, counts only key columns
…and tested only the leading column of a subpartition spec all of spec.columns
is_partition_closed resolved naive bounds under the reader's session timezone, not the ddl_timezone the writer used — up to a day out on a timestamp key the provider takes and sets ddl_timezone
plan_new_subtree silently dropped over-long names, producing a partitioned relation with zero children that was then attached findings can be recorded against a name, not only a node
A codec returning a naive datetime aborted the whole run — fatal even with continue_on_error, because prune identification was the one step outside it guard requires tzinfo; prune identification is inside continue_on_error
Widening PartitionRepository.reconcile_default_rows in place broke mypy for every third-party implementation base protocol back to its 0.4.0 signature; the composite variant on CompositeKeyRepository

What mutation testing found

124 targeted mutations, 40 surviving. The worst: the subpartition wiring on the creation
path had no unit pinning at all
— replacing build_new_branch with if False left 936
tests green, as did creating the branch as a plain leaf, skipping convergence of a
half-built branch, and moving the capability check after the first DDL. So did deleting
the whole reconcile stage from maintain_lifecycle, zeroing repaired_count, dropping
actionable findings from issues, and dropping the exclusion of partitions about to be
pruned. Each is now pinned and re-verified dead.

Three tests added in the first round proved nothing and are replaced: a DEFAULT-guard
test whose node was a plain leaf (so the legacy-leaf rule answered instead), two UUIDv7
clamp tests where one compared a function with itself and year 9999 turned out to be well
inside the representable range, and two bounds tests whose payloads matched neither
pattern they claimed to discriminate.

Branch coverage was never enabled. Turning it on dropped the honest figure to 89.94%;
closing the gaps brings it to 94.5%, partial branches down from 121 to 91.

Documentation

Six claims were false, each checked against PostgreSQL 17: the issues section added last
round described the opposite of what happens (the states it named are informational and
never reach issues), the migration guide named the wrong lines as the DDL-issuing ones,
its calculator example crashed for a missing import — and that NameError escapes
maintenance, because parse_partition_name catches only ValueError — its schema used
uuid_generate_v7(), which does not exist before PostgreSQL 18, "zero DDL, zero locks"
was half right, and the README listed an export that does not exist. The reference had no
entry for any of the six protocols the README tells people to implement.

Known and deliberately not fixed

  • A permanently-blocked DEFAULT_HOLDS_ROWS conflict leaves one detached table with no
    orphan marker, so cleanup will not collect it. Marking it would let cleanup drop it, and
    the next run would recreate it — create/drop churn every tick. The whole recovery story
    here treats a detached subpartition as work to resume, not as reclaimable waste, so this
    needs a different kind of marker rather than a patch. The table is empty, there is one
    per blocked partition, and the finding names both the partition and the fix.
  • list_partitions drops an unaddressable child with a log line where get_partition_tree
    marks the parent. The asymmetry errs safely: the tree feeds the planner, where a missing
    child would mean proposing a duplicate; list_partitions feeds retention, where it only
    means not dropping something.
  • Metadata capability failures raise InvalidPartitionConfigError where repository ones
    raise UnsupportedCapabilityError. Both derive from PartitionError, and each reads
    correctly in its own context — a config asking for what the wiring cannot do, versus an
    execution site refusing. Unifying them changes an exception type for style alone.

Backward compatibility

No migration needed. All 776 pre-existing tests pass unchanged. Everything added is optional:

  • new config fields default to None; partition_column= and column= remain accepted spellings
  • period_calculator became optional, which is additive
  • new capabilities are gated behind separate protocols (SubpartitionRepository, NestedPartitionMetadata, CompositeKeyRepository, CompositeKeyMetadata), so an existing custom repository or metadata provider keeps satisfying the flat ones and is only refused when a config actually asks for more
  • PartitionType moved to pg_partsmith.topology and is re-exported from its historical home

Serialization is a superset, not a rename. Composite-key support turned
partition_column into a derived value, which would have dropped it from
model_dump() — parsing an old config still worked, but code reading
dump["partition_column"] back would not have found it. It is exposed as a
computed field instead, so the dump carries both spellings. Verified by
diffing the serialized key set of every public model against master:

Model Removed Added
TablePartitionConfig — partition_columns, root_layout, subpartition
PartitionInfo — bounds, subpartition_type
MaintenanceResult — repaired_count
MaintenanceIssue — partition_name

Nothing master emitted has stopped being emitted. Round-tripping a dump that
names both spellings is pinned by a test: the explicit key wins, so a composite
configuration cannot silently collapse to its leading column.

Six feat: commits → release-please will cut 0.5.0.

Tests

1248 total, 94.5% coverage with branch coverage enabled. Beyond the flat suite: scenarios A–K against real PostgreSQL 17 via testcontainers (fresh creation, no-op convergence proven with a DDL statement counter, single missing bucket, modulus preserved, modulus repaired, inconsistent moduli, topology mismatch, legacy leaf, interrupted run, UUIDv7 bounds, UUIDv7 + hash routing checked through tableoid), plus LIST groups matched by value under foreign names, LIST value conflicts, static HASH/LIST roots, composite-key routing and retention, DEFAULT reconciliation into a hash branch, retention counting periods, hooks firing once per branch, PK validation, adoption of a foreign-named tree, and identity columns. Full aio/sync parity throughout.

Release readiness

Checked mechanically rather than by eye:

  • Extension points are untouched. Diffed the signature of every public method on the protocols and bundled implementations against master: 107 pre-existing methods, 0 removed, 0 changed, 20 added. Anyone who implemented a protocol or subclassed a bundled class is unaffected.
  • aio/sync parity. Compared both mirrors class-by-class and method-by-method across 16 module pairs, plus each package's __all__: identical. Every name in __all__ resolves.
  • The artifact works. Built the wheel, installed it into a clean virtualenv, and exercised the new API end to end — flat, nested, composite and static configs, the UUIDv7 codec's contiguity, and the planner. Only the declared dependencies come along; no new ones crept in.
  • No TODO/FIXME left, no skipped or xfail tests, docs build clean.

Still application-side

For a GlitchTip-shaped migration, two things remain the app's job: a ~15-line calculator subclass if you want to keep existing partition names (verified necessary — the overlapping ATTACH otherwise fails loudly, and both outcomes are regression-tested), and converting a day-based retention window into a period count.

Deliberately not in this PR: repartition/rewrite tooling — changing a modulus with data movement is a separate design with its own locking and rollback story.

Extracts the vocabulary a nested partition tree needs into one IO-free module
and re-exports it from its historical home.

* pg_partsmith.topology owns PartitionType, the discriminated PartitionBounds
  union (RANGE / LIST / HASH / DEFAULT), the declarative HashSubpartitionSpec,
  the introspected PartitionNode, and the hash-keyspace coverage helpers.
* PartitionInfo gains structured `bounds` and `subpartition_type`; the existing
  from_value/to_value pair is derived both ways so neither view can go stale.
* TablePartitionConfig gains a `subpartition` spec, validated for identifier
  length across the whole tree -- PostgreSQL truncates at 63 bytes silently,
  which would collapse two buckets onto one name.
* Boundary-literal parsing moves next to the rest of the bound parsing;
  pruning_rules keeps the old name as an alias.

No behaviour changes: nothing consumes the new fields yet.
A time-based partition has two notions of "when": the semantic period, which
decides its name and lifecycle, and the physical literal PostgreSQL compares
the partition key against. For a timestamptz key they coincide. They come apart
whenever the key is a time-sortable identifier -- a UUIDv7, a ULID, a Snowflake
id, an epoch bigint -- which is still partitioning by time, just not by a
timestamp.

RangeBoundaryCodec bridges the two:

    WeekPeriodCalculator(boundary_codec=UUIDv7BoundaryCodec())

Names, create-ahead and retention keep working in calendar terms; only the
FOR VALUES literals change. Codecs are bidirectional on purpose -- retention
compares catalog upper bounds, so an encode-only codec would create partitions
the library could never prune.

UUIDv7BoundaryCodec (RFC 9562) uses the minimum UUID of each boundary instant,
which is what makes adjacent periods exactly contiguous: one period's upper
bound is the next one's lower bound, so no id can fall between two partitions.

The default path is unchanged and still emits the same calendar literals.
A time partition can now be a partitioned table in its own right:

    subpartition=HashSubpartitionSpec(column="tenant_id", modulus=4)

The two dimensions keep separate jobs. Time stays the lifecycle dimension --
create-ahead, retention, detach, drop and hooks all act on the whole branch,
and retention_count still counts periods, not leaves. Hash is the distribution
dimension.

Maintenance is a convergent desired-state loop. Between create and prune it
compares each attached branch against the spec and creates only the buckets
that are genuinely missing; a converged tree costs zero DDL. What it refuses to
touch matters as much: a complete bucket set at an older modulus is preserved
(changing a modulus needs a rewrite), an incomplete one is repaired at its own
modulus rather than the configured one (any other modulus would overlap it), a
partition predating the policy stays a valid leaf, and a shape the config does
not describe is reported through MaintenanceResult.issues instead of being
"fixed" into something PostgreSQL would reject. Mixed moduli are checked for
actual coverage over the lcm rather than assumed broken -- PostgreSQL permits
them when the residue classes do not overlap.

Ordering substitutes for atomicity on the create path: a branch is built
detached and attached last, so reachability from the root is the commit point.
An interrupted run leaves an unreachable table, never a live branch that
rejects part of its keyspace; the next run completes and attaches it. Repairs
use ATTACH rather than CREATE ... PARTITION OF, which takes SHARE UPDATE
EXCLUSIVE instead of ACCESS EXCLUSIVE and so does not stall writers.

Subpartition columns must appear in every UNIQUE/PRIMARY KEY on the root, so
validation reads the constraints and refuses an impossible config before any
DDL runs. Nested support is gated behind optional protocols, so existing
repositories and metadata providers keep satisfying the flat ones.
create_future_partitions walks forward from the current period, which is right
for a scheduled tick and wrong for a migration: the rows already in the table
live in periods create-ahead will never reach.

ensure_partitions takes the periods from the caller instead:

    past = [calculator.period_before(current, n) for n in range(1, 53)]
    await service.ensure_partitions(config, past)

The catalogue is read once for the whole batch rather than once per period, so
backfilling a year costs one listing instead of fifty-two -- ensure_partition
now delegates to it and gets that for free. Duplicates are ignored while the
caller's order is preserved, and subpartitioned periods are built with their
complete bucket set before being attached, exactly as create-ahead does.
Partitions are created with LIKE ... INCLUDING ALL, which copies an identity
column, and PostgreSQL then refuses to attach them:

    table "events__2026_w35" being attached contains an identity column "id"
    DETAIL: The new partition may not contain an identity column.

So a root declared with GENERATED ALWAYS AS IDENTITY could not be partitioned
at all -- create succeeded and attach failed, leaving the table orphaned. This
predates subpartitioning and affected the flat path identically.

EXCLUDING IDENTITY fixes it: PostgreSQL propagates the parent's own identity to
the partition on ATTACH, so ids are still generated and keep advancing. Tables
without an identity column are unaffected, and everything else INCLUDING ALL
carries over -- nextval defaults, generated-STORED columns, indexes and
constraints -- is untouched.
Adds three guides -- subpartitioning (including the ADR for why a subtree is
built detached and attached last rather than wrapped in one transaction, and
the measured lock levels behind it), boundary codecs, and a worked example of
adopting an event store keyed by UUIDv7 with a non-uniform bucket history.
A level can now be divided into named value sets instead of anonymous buckets:

    subpartition=ListSubpartitionSpec(
        column="region",
        groups=(ListGroup(name="eu", values=("de", "fr")), ...),
        include_default=True,
    )

The strategies share a base and compose freely, so RANGE(time) -> LIST(region)
-> HASH(tenant_id) is expressible; SubpartitionSpec is now a union discriminated
on `strategy`, which every spec already serialised, so stored configs keep
parsing unchanged.

LIST reconciles differently from HASH, because a LIST level is never complete:
there is always another value the world could produce, so there is no gap to
detect -- only groups that do not exist yet. `include_default` maintains a
catch-all so an unconfigured value is stored rather than rejected.

Groups are matched by the values they own rather than by name, so a tree an
earlier tool named differently is recognised instead of duplicated. A value
belongs to exactly one partition, so a group claiming one that another
partition already owns is reported through MaintenanceResult.issues rather than
attempted -- moving it would mean detaching the partition holding it.

LIST values are caller data, so they are rendered through the existing literal
placeholder mechanism rather than spliced into the DDL template: a value
containing a brace would otherwise be re-interpreted when the template is
formatted.
Not every partitioned table is partitioned by time. A table divided only by
tenant, or only by region, has a fixed set of partitions: nothing is created
ahead of the clock and nothing ages out. PartitionStrategy.HASH_BASED and
VALUE_BASED existed as enum members but were rejected at construction; they now
work, described by a `root_layout` spec:

    TablePartitionConfig(
        table_name="issue_index",
        partition_type=PartitionType.HASH,
        partition_strategy=PartitionStrategy.HASH_BASED,
        partition_column="organization_id",
        root_layout=HashSubpartitionSpec(column="organization_id", modulus=16),
    )

The root is just another level, so this is the planner that already existed,
pointed one step higher: the same rules preserve an existing hash set at another
modulus and report a LIST value another partition owns.

Such a table has no periods, so `period_calculator` is now optional. The
period-driven services are built only when one is supplied, and the APIs that
need them -- create_future_partitions, ensure_partitions,
get_partitions_for_pruning -- raise InvalidPartitionConfigError explaining that
this wiring has no periods. maintain_lifecycle short-circuits to reconciliation
alone: created_count reports what it made, and detached/dropped stay zero
because there is no retention window.

`granularity`, and a `subpartition` alongside `root_layout`, are refused rather
than silently ignored, so a config cannot claim two different shapes at once.
A partition key may now span several columns, at the root and at any nested
level:

    partition_columns=("created_at", "tenant_id")
    HashSubpartitionSpec(columns=("tenant_id", "shard_id"), modulus=8)

Only the leading column carries the period; trailing ones are bounded with
MINVALUE at both ends, which selects exactly the rows a single-column bound
would -- verified against PostgreSQL rather than assumed. Bound parsing returns
that leading value, so retention and pruning compare the same instant they
always did, and DEFAULT reconciliation keeps filtering on the leading column.

Key order is not column order. The new catalogue query unnests `partattrs` WITH
ORDINALITY to preserve it; ordering by attnum, as the older single-column query
does, would silently transpose a composite key. That query is left alone: it
still refuses composite keys, and single-column configs keep using it, so a
metadata provider written before this change is only refused when a config
actually declares a multi-column key.

PostgreSQL's two restrictions are enforced up front rather than discovered
mid-run: LIST takes exactly one column, and every key column must appear in
every UNIQUE/PRIMARY KEY constraint.

`partition_column` is now a property returning the leading column, and is still
accepted as constructor input, so single-column configs and the code reading
them are untouched.
@AlexeyShalaev AlexeyShalaev changed the title feat: nested partition trees, boundary codecs, and desired-state reconciliation feat: partition trees, boundary codecs, static roots and composite keys Aug 28, 2026
@AlexeyShalaev
AlexeyShalaev marked this pull request as ready for review August 28, 2026 07:02
`FOR VALUES IN ('O''Brien', 'other')` parsed as a single value. A doubled quote
is how SQL escapes a quote inside a literal, and the splitter stepped over only
the first of the two characters -- leaving the second to flip the in-quotes
state, so every comma after it was read as part of the value rather than as a
separator.

Consuming both characters together fixes it. Introduced with LIST
subpartitioning earlier in this branch and caught by a test written for the
refusal paths; it would have mis-read any LIST partition holding a value with
an apostrophe in it.

Also adds coverage for the configuration and wiring refusals that had none: a
static root disagreeing with its strategy, layout, granularity or name length,
and a metadata provider asked for composite keys or partition trees it cannot
introspect.
Making `partition_column` a property for composite key support dropped it from
`model_dump()`, which changed the serialized shape: a config persisted by 0.4.0
still parsed, but anything reading `dump["partition_column"]` back stopped
finding it. Constructing from either spelling always worked; only the output
had changed.

Exposing it as a computed field restores that. The dump now carries both
`partition_column` and `partition_columns`, so it is a strict superset of what
0.4.0 emitted -- verified by diffing the serialized key set of every public
model against master.

Round-tripping a dump that names both is the case worth pinning: the explicit
key has to win, or a composite configuration would silently collapse to its
leading column. The pre-existing single-column spelling is now dropped after
being read rather than left to be rejected as an unknown field.
BoundaryDecoder, PartitionBounds and SubpartitionBounds were reachable from the
package root but absent from the generated reference. The two bound aliases are
Annotated unions, so they are named in prose beside the members they combine
rather than through a directive that would not render them.
Without a boundary codec, an encoded upper bound is unreadable, so
`is_partition_closed` answered False forever and said nothing about why. An
export pipeline gated on it would wait indefinitely with an empty log -- the
worst kind of failure to diagnose, because nothing appears to be wrong.

It now names the cause: the bound it could not read, and the codec it needed.
The bound is only re-read once the timestamp path has already declined to
answer, so a timestamp-keyed table pays nothing for this, and a partition with
no upper bound at all -- DEFAULT, detached, non-RANGE -- stays quiet because
there is nothing to explain.
Independent review found that replacing `partition_column` with a
`partition_columns` tuple caused a cluster of defects, all rooted in having two
spellings for one thing:

* Type-checking broke for every 0.4.0 user. The package ships py.typed, so
  `TablePartitionConfig(partition_column=...)` became an error under mypy even
  though it still worked at runtime -- a red CI on upgrade with no code change
  on their side, and every example in this repo's own README and guides was
  affected too.
* `model_copy(update={"partition_column": ...})` silently did nothing, and left
  the object disagreeing with itself: `model_dump()` reported the old value
  while `dict(model)` reported the new one. On a frozen model that method is
  the idiomatic way to derive a config.
* Passing both spellings resolved silently instead of raising, so DDL could be
  emitted against a column the caller did not ask for.
* `SubpartitionSpecBase.column` *raised* for a composite spec. Validation calls
  it, so composite HASH keys -- a headline feature -- crashed for any table
  carrying a UNIQUE or PRIMARY KEY constraint, with an error telling the user
  to do what they had already done. It also broke `hasattr`, which only
  swallows AttributeError.
* `PartitionTableSettings` lost fail-fast: a deployment missing the column
  booted green and died at the first maintenance tick.

Keeping `partition_column` a real required field and naming the rest of the key
`trailing_partition_columns` removes the ambiguity rather than managing it.
`partition_columns` remains, derived. The same shape applies to subpartition
levels via `column` + `trailing_columns`.

Verified: `mypy --strict` passes on 0.4.0-shaped user code, and the serialized
key set of every public model is once again a strict superset of master's.
Three defects found by independent review, each of which produced a branch that
silently rejected rows while maintenance reported nothing:

* Leaving a hash level's modulus alone abandoned every level *below* it.
  `_plan_hash_level` returned an empty tuple, and `_plan_into` recurses over
  exactly that, so a config changing `modulus` from 4 to 8 against a complete
  4-bucket branch stopped converging the branch's own children entirely --
  reported as an informational finding, so nothing reached
  MaintenanceResult.issues. The tiling argument is about one level; the levels
  under it are an independent question.

* A planned name already held by a mismatched relation was planned anyway. The
  executor then read PostgreSQL's "already exists" and "already a partition"
  errors as an interrupted run and a lost race, and reported success. The
  planner now refuses the name and reports it, because at execution time the
  collision is genuinely indistinguishable from a race.

* Repairing at a branch's own larger modulus generated names past the 63-byte
  identifier limit -- the config validator sized them against the *configured*
  modulus. PostgreSQL truncates silently, so the buckets collided with existing
  ones and fed straight into the swallow above.

Also anchors the hash-bound pattern. It was an unanchored search run before the
LIST and RANGE shape tests, so `FOR VALUES IN ('modulus 4, remainder 1')`
parsed as HashBounds. A partition whose bounds are misread is invisible to the
planner, which plans a duplicate that PostgreSQL then refuses with 42P17 -- not
a tolerated SQLSTATE -- on every run, forever.
…anch

Independent review showed the execution layer reporting success for partitions
PostgreSQL had refused, and one bad branch stopping maintenance for a whole
table. Four changes:

* An attach conflict is only treated as a lost race when the relation holding
  the name owns the bounds that were planned. PostgreSQL reports the same
  SQLSTATE whether another worker just created this partition or an unrelated
  relation happens to hold the name, so "is something attached here?" proved
  nothing -- and a genuine collision was reported as `created=0, findings=[]`
  while that slice of the keyspace rejected rows forever.

* A DEFAULT sibling holding rows that belong to the new partition is reported
  rather than raised. This is the documented workflow -- `include_default`
  exists so unknown values land somewhere, and configuring a group for one is
  the natural next step -- yet 23514 propagated out of reconcile, and because
  reconcile runs before pruning it also stopped the table reclaiming disk on
  every subsequent run.

* Each branch is converged in isolation, so one that cannot be converged no
  longer denies its siblings their turn.

* A detached branch is converged *before* it is re-attached, not after.
  Re-attaching first -- which is what backfill and create-ahead did for any
  partition that already existed -- made the branch live for row routing while
  its child set could still be short, and a process stopping in that window
  left it live and rejecting. That is precisely what building detached and
  attaching last is supposed to prevent.

Also: a static root now honours `skip_create` and `continue_on_error` like
every other step; repository capabilities are checked before the first
statement rather than after the relation exists, so a mis-wired composite
config no longer leaks an unmarked detached table on every tick;
`SubpartitioningNotSupportedError` becomes `UnsupportedCapabilityError`, which
names the capability instead of hardcoding one; and the hand-copied table of
protocol members is replaced by the isinstance check it duplicated.
Three ways a bound or a tree could be read as something it is not.

A LIST partition declared FOR VALUES IN (NULL) and one declared FOR VALUES
IN ('NULL') both normalised to the same three characters. The planner would
then see a value it has a partition for, propose a duplicate, and fail on the
conflict every single run. ListBounds keeps the keyword apart from the string,
and the DDL renders it back as a keyword.

A child whose schema or relation name contains a dot cannot be addressed by
qualified-name DDL, so it is left out of the introspected tree. What remains is
a subset of the real child set -- and reading a subset as a set of gaps makes
the planner propose partitions that already exist. The parent is now marked, and
a marked parent is reported as COVERAGE_UNKNOWN rather than planned from.

PartitionInfo's before-validator wrote its derived fields into the caller's own
dict, and derived nothing at all from the dict form model_dump() produces, so a
dump-and-reload silently lost from_value/to_value.
…annot address

is_partition_closed guarded its cast with a regex for a date-like shape, which
a sortable identifier such as '2026-08-28-a1b2c3' passes without being a date.
The cast then raised out of a predicate that documents False as its answer for
a bound it cannot read. Both paths now read the raw bound first and compare it
in one place, and a bound that will not cast is warned about and reported as
not closed -- the same answer an unreadable encoded bound already got.

A partition key position holding an expression rather than a column is recorded
as attnum 0, which joins to no pg_attribute row. Dropping it reported a
one-column key for a two-column table, and every bound built from that key
would have been the wrong arity. The join is now LEFT so the position survives,
and both accessors refuse the table by name and position.

get_partition_column no longer carries its own copy of the key query: reading
the same key through the same statement is what keeps the two accessors from
disagreeing about a table.
PostgreSQL adds an IS NOT NULL test for *every* key column to a range
partition's constraint. A row whose trailing key column is NULL therefore
belongs in the DEFAULT partition whatever its leading value says -- and the
statement that clears a DEFAULT conflict was selecting it anyway, on the
leading column alone. The insert was rejected with a check violation that looks
exactly like the conflict the move exists to clear, so the retry never
converged and the period partition never attached.

The move now excludes rows with a NULL in any trailing key column. Those rows
stay in DEFAULT, which is where PostgreSQL routes them and where they belong.

trailing_columns is only ever passed for a composite config, so a repository
written against the single-column signature keeps serving every config it could
already serve -- the same accommodation get_partition_column already gets.

quote_literal stops assuming standard_conforming_strings is on. It is a session
setting any client can turn off, and with it off a value ending in a backslash
would escape its own closing quote. Values carrying one are emitted as an
E-string, where the escaping rules are the same either way.
Each of these was a claim before it was a test. A nullable trailing key column
with a row in DEFAULT; an expression key; a bound shaped like a date that is
not one; and a LIST partition holding NULL beside one holding the string
'NULL'. All four run against PostgreSQL 17, not against a mock of it.
Three corrections.

The composite-key section still spelled the API as partition_columns=(...) and
HashSubpartitionSpec(columns=...), which was the shape before the config was
split into a leading column and its trailing ones. Nothing in the library ever
accepted what the page showed.

It also claimed a composite bound selects "the same set a single-column bound
would". It does not: PostgreSQL adds an IS NOT NULL test for every key column,
so a NULL trailing value sends a row to DEFAULT regardless of its timestamp --
and DEFAULT is never pruned. The page now says so, and says how to avoid it.

The lock table said ATTACH takes SHARE UPDATE EXCLUSIVE and stopped there. It
also takes ACCESS EXCLUSIVE on the parent's DEFAULT partition, if it has one,
while scanning it. Both were measured on PostgreSQL 17; only one was written
down.
The review found several behaviours the suite asserted nothing about.

The DDL the composite and LIST paths render: MINVALUE padding scaled to the key
arity, NULL emitted as a keyword rather than a quoted value, a composite
PARTITION BY, and a duplicate name reported as PartitionAlreadyExistsError.

Which branches a reconcile run touches: an excluded one, a detached one and the
DEFAULT partition are all left alone, each for a different reason. And when one
branch cannot be converged, the others still are -- the isolation that keeps a
single bad branch from stopping the table reclaiming disk forever.

The static-root run flags, which were added without a test that they mean
anything: skip_create skips the only stage a static root has, and
continue_on_error records a RECONCILE issue instead of raising.

hash_children over a branch that also holds a DEFAULT and a legacy LIST sibling
-- counting either into the keyspace arithmetic would report a tiled branch as
short. And the UUIDv7 clamp at both ends of the representable range.
The interrupted-run test built a detached branch and then asserted the root had
no children -- which is what the fixture had just arranged, not anything the
library does. It would have passed against a library that attaches first.

Replaced with the claim that actually matters: the branch is attached only
after every one of its buckets exists. A branch becomes reachable the moment it
is attached, and a reachable branch missing a bucket rejects every row that
hashes into it, so the order of those statements is the whole recovery story.
…en down

PartitionType and PartitionStrategy were documented with their member names as
their values. They are StrEnums whose values are lowercase, which matters the
moment a config is read from the environment -- PARTITION_STRATEGY=TIME_BASED
does not validate. The first test to load settings from env found it.

attach_composite_partition still said its bound selects "the same set a
single-column bound would". It does not, for the same NULL reason the guide now
explains, and the docstring says so where the DDL is written.

reconcile_subpartitions takes no distributed lock -- unlike maintain_lifecycle,
which runs its whole sequence under one. Safe to call concurrently either way;
worth knowing before you do.
Before subpartitioning existed, MaintenanceResult.issues was only ever
populated by a step that had failed under continue_on_error, so paging on a
non-empty issues list was a reasonable thing to build. Reconciliation puts
topology findings there too, and a finding describes something the run
deliberately left alone rather than anything that went wrong.

success is unchanged -- it still reports a fatal error and nothing else -- so
the migration guide says how to filter instead.
PartitionNode.partition_type says how a relation partitions its children;
PartitionInfo.partition_type says how its parent partitions it. Both spellings
are right for the model they belong to and reading one as the other inverts the
meaning, so each now points at the other.

TablePartitionConfig's trailing_partition_columns said the columns must be NOT
NULL without saying what happens if they are not. What happens is that those
rows go to DEFAULT and stay there.

SubpartitionAction was reachable through SubpartitionPlan.actions without being
importable from the package or appearing in the reference.
From 3.12, isinstance against a runtime_checkable Protocol resolves members
with getattr_static, which does not see attributes a mock creates on demand.
The three new static-root tests left get_partition_tree to the mock's
__getattr__ and passed only on 3.11.

Set explicitly, as the rest of the suite already does.
…e the bound

Four ways the catalog was read too narrowly, each ending somewhere worse than
an error message.

PARTITION_TREE_SQL inner-joined pg_attribute, so a key position holding an
expression vanished and the key came back shorter than it is. A shortened
one-column key compares *equal* to a one-column spec, so the COLUMN_MISMATCH
guard never fired and the planner treated an unaddressable branch as a match.
This is the same defect already fixed in PARTITION_COLUMNS_SQL, in the query
next to it. Nodes now carry has_expression_key and the planner refuses them.

The unique-constraint query read pg_constraint and only contypes 'p' and 'u'.
PostgreSQL applies the all-partition-key-columns rule to unique *indexes* too,
and to EXCLUDE constraints, and LIKE ... INCLUDING ALL copies each of them --
so both got past the pre-flight check and failed mid-DDL with the very message
that check exists to turn into a config error. It reads pg_index now, unions in
the exclusion constraints, and counts only key columns: a covering index's
INCLUDE columns do not satisfy the requirement.

The check itself tested only the leading column of a subpartition spec, so a
composite subpartition key failed the same way. All of spec.columns now.

is_partition_closed resolved a naive bound under whatever timezone the reader's
session happened to have, while the creator writes partitions under its
configured ddl_timezone. On a timestamp or date key the two disagreeing moves
the answer by up to a day. The provider takes ddl_timezone and sets it.

And a codec returning a naive datetime is no longer passed through to be
compared against an aware cutoff -- that TypeError surfaced from the middle of
retention, nowhere near the codec that caused it.
A refused child ATTACH was recorded as a finding and then ignored: the loop
carried on and attached the parent anyway, so the branch went live with a hole
in its keyspace -- the exact outcome attaching last exists to prevent. And on
the creation path the finding was not merely ignored, it was discarded:
build_new_branch called materialize() with no collector, and the collector
materialize() makes for itself was thrown away unread, so nothing was even
logged. Reproduced end to end on PostgreSQL 17: ensure_partition returned a
successful PartitionInfo for a branch that then rejected 56 of 200 inserts.

Now a node whose child was refused is left detached and reported, and
build_new_branch raises PartitionTopologyError rather than handing the caller a
count for a subtree it could not finish -- the caller attaches the branch the
moment it returns.

plan_new_subtree had the same silence one level down: _is_unusable_name skipped
an over-long name without recording it, because recording needed a node and the
creation path has none. A repaired branch can need wider names than the config
validator budgeted for, and the result was a partitioned relation created with
zero children and attached. Findings can now be recorded against a name.

reconcile_default_rows moved rows with RETURNING * into an unqualified INSERT,
binding the DEFAULT partition's physical column order positionally to the
target's. ATTACH PARTITION matches columns by name, so the two orders need not
agree -- and when they do not, values are silently transposed with the source
rows already deleted. Verified on PostgreSQL 17: label and note swapped, no
error. Both sides name their columns now.

PartitionRepository.reconcile_default_rows goes back to its 0.4.0 signature.
Widening it in place type-checked here but broke every third-party
implementation under mypy, which is the one thing every other new capability on
this branch was carved into a separate protocol to avoid. The composite variant
lives on CompositeKeyRepository, and a repository that satisfies that protocol
by name but not by signature is told which capability it is missing.

Identifying what to prune is now inside continue_on_error like every other
step; it was the one that could abort a run after create and reconcile had
already committed DDL. And the async DEFAULT-conflict path compensates on
KeyboardInterrupt and SystemExit as well as cancellation, matching sync.
Mutation testing over the branch found 40 of 124 source mutations surviving.
These are the ones that mattered.

The subpartition wiring on the creation path had no unit pinning at all: with
build_new_branch replaced by `if False`, a new period's branch was created with
no buckets and 936 tests stayed green. So did creating the branch as a plain
leaf, skipping convergence of a branch an interrupted run left half-built, and
moving the capability check to after the first DDL statement. Only Docker
integration caught any of it.

Neither did the reconcile stage inside maintain_lifecycle: deleting it whole,
zeroing repaired_count, dropping actionable findings from issues, and dropping
the exclusion of partitions this run is about to prune -- all four survived, and
the exclusion rule was pinned by no test anywhere, integration included.

Three tests I added in the previous round proved nothing:

The DEFAULT-partition guard built a node with no partition_type, so it was
skipped by the legacy-leaf rule and said nothing about the rule it named. It now
uses a DEFAULT that is itself hash-partitioned and one bucket short.

Both UUIDv7 clamp tests: one compared a deterministic function with itself, and
year 9999 is 253e12 ms against a field that holds 281e12 -- so the "clamps to
the highest" test clamped nothing and the upper clamp was unguarded. Replaced
with an instant past the representable range, plus a test that min_uuid_for
really is the minimum for its millisecond, which nothing checked.

The two bounds tests claiming to guard the anchored hash pattern used payloads
matching neither pattern; unanchoring it survived. They now carry a whole hash
bound spelled out inside a LIST value, which an unanchored search does find.

Each of the eleven mutations above was re-applied after these tests and is now
killed.
…missing

An independent pass treated every claim in the guides and docstrings as a
hypothesis and checked it against PostgreSQL 17. Six were false.

The "issues now fills up on a successful run" section I added last round was
backwards. The two states it names -- a preserved modulus and a repaired one --
are informational, so they never reach MaintenanceResult.issues at all, and
subpartitioning.md already said so two pages away. Rewritten to say which
findings are actionable and which are only logged, and to keep the one thing
that is true: issues can now carry a non-failure, so alerting on it needs a step
filter.

The migration guide named the wrong lines as the ones that issue DDL (the third
issues none), and its calculator example was missing `from datetime import
date` -- which matters more than a typo, because parse_partition_name catches
only ValueError, so the NameError would escape maintenance. The example now runs
as written; I ran it.

Its schema used uuid_generate_v7(), which does not exist on PostgreSQL 17 --
uuidv7() arrives in 18 and uuid-ossp stops at v5 -- on the very page that
measures everything against 17. Replaced with a note on where the value comes
from instead.

"Zero DDL, zero locks" was half right: reading the tree takes ACCESS SHARE on
every relation in it, like any SELECT.

README listed SubpartitionSpecBase as an export it does not have, and omitted
SubpartitionAction, which it does.

And the reference had no entry for any protocol at all -- the six extension
points the README tells people to implement. Added, along with a Raises: section
on every new call that raises one, and is_partition_closed's prose moved out of
the middle of its Args: block where mkdocstrings would fold it into an argument.
build_ddl_statement rewrote every `[word]` in its template into a format field,
so a template containing an array subscript or a JSON literal failed on a
placeholder that was never one. Only the keys the caller passed are rewritten
now. No template in the library tripped it, but repositories are a documented
extension point.

The DEFAULT-row move built its statement by hand and skipped the colon escaping
build_ddl_statement applies, so an identifier or boundary carrying a colon would
be read by text() as a bind parameter and fail for want of a value. It goes
through the same helper now.

A NUL byte is refused by both quoters rather than passed to a driver that
truncates at it -- what reached the server was a prefix of what was built,
reported as an unterminated string.

And validate_subpartitioning's RANGE-root rule is unreachable today: a static
root rejects `subpartition` earlier, and TIME_BASED already requires RANGE. Kept
as defence in depth, and now says so, because a test was claiming to cover it.
The coverage config had no `branch = true`, so a guard with only one of its two
outcomes ever taken counted as fully covered. Turning it on dropped the honest
figure to 89.94%.

Closing the gaps it revealed brings it to 94.5%, with partial branches down from
121 to 91. The ones that mattered: prune identification failing under
continue_on_error and without it (code this round added, previously untested in
either direction), a composite config handed to a repository that satisfies
CompositeKeyRepository by method name but not by signature, the static-root
reconcile path, execution findings travelling out with the result rather than
only into the log, hash bounds rendered as MODULUS-then-REMAINDER (swapping them
is legal SQL whenever remainder < modulus, so it builds a different tree instead
of failing), EXCLUDING IDENTITY surviving in the branch DDL, a DEFAULT adopted
under a foreign name not being duplicated forever, retention actually using a
boundary codec, a codec combined with a non-UTC calculator, and the three bound
parser paths the docstring advertises but nothing exercised.

Also: the hash name budget is now tested at modulus 10, where the widest
remainder is one digit shorter than the modulus and an off-by-one shows. At 16
both are two digits and the test could not fail.
Cross-referencing the branch diff against coverage found 75 added lines that no
test reaches. Most are the `raise` inside a KeyboardInterrupt guard, which is
not worth staging. These thirty are real decisions:

Reconciliation failing under continue_on_error and without it, on a time-based
table -- only the static-root equivalents were covered. A period-driven call on
a service built without a calculator. A composite config handed to a repository
with no attach_composite_partition at all, and a creation service wired without
its subpartition collaborator. A relation whose column lookup comes back empty,
where moving rows would mean guessing at a shape.

Plus the small accessors the branch introduced and nothing called:
SubpartitionSpecBase's abstract members, bounds_for, PartitionNode.relname with
and without a schema, identifier validation rejecting an expression and folding
mixed case, a hash bound the models refuse, a blank boundary literal, a codec
declining a value it does not recognise, and the calculator's boundary_codec
accessor that pruning reads to decide how to compare.

45 added lines remain unexecuted, all of them re-raises inside interrupt guards
or protocol stubs.
A run that finds a branch an earlier run left detached completes its bucket set
and attaches it. Those buckets were reported nowhere. `created_count` is right
to stay 0 -- the partition already existed -- but the work happens under CREATE,
before the reconcile stage that would otherwise count it, and by the time
reconcile runs the branch is complete, so it counts 0 too. A run that built four
buckets and attached a branch could report `created_count=0, repaired_count=0`.

They belong in `repaired_count`, which is documented as subpartitions created
inside pre-existing branches to close gaps in their child sets -- exactly this.

The same call was dropping `findings` outright. A branch whose shape the planner
refuses is reported by the later reconcile only if reconcile still sees the
problem; a branch completed here looks fine by then, so the finding was lost.
Both now travel out through a collector the lifecycle service passes down, the
same shape `materialize` already uses.
@AlexeyShalaev
AlexeyShalaev merged commit f150233 into master Aug 28, 2026
7 checks passed
@AlexeyShalaev
AlexeyShalaev deleted the feat/0.5.0-nested-partitioning branch September 1, 2026 11:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant