Repository navigation
feat: partition trees, boundary codecs, static roots and composite keys - #23
Merged
Merged
Conversation
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.
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
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
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_partmanfor a hand-rolledPartitionManager, 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
HASHor byLIST:Time stays the lifecycle dimension — create-ahead, retention, detach, drop and hooks all act on the whole branch, and
retention_countcounts 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:
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):
Names, create-ahead and retention keep working in calendar terms; only the
FOR VALUESliterals 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_BASEDandVALUE_BASEDexisted as enum members but were rejected; they now work viaroot_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"plustrailing_partition_columns=("tenant_id",), at the root and at any nested level. Only the leading column carries the period; trailing ones are bounded withMINVALUE. A trailing column that is nullable changes row routing — PostgreSQL addsIS NOT NULLfor every key column, so a NULL sends the row toDEFAULTwhatever 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:ALTER TABLE branch ATTACH PARTITION leafSHARE UPDATE EXCLUSIVE— DML continuesCREATE TABLE leaf PARTITION OF branchACCESS EXCLUSIVE— writers stallBranch creation via
LIKE roottakes onlyACCESS SHAREon the live table.One caveat the first version of this PR left out, also measured: if the branch has a
DEFAULTpartition,ATTACHtakesACCESS EXCLUSIVEon that partition while itscans 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
partattrsWITH ORDINALITY; ordering byattnum— as the older single-column query does — would silently transpose a composite key.Included bug fix
fix: exclude identity columns when creating partitionsis independent of the features. Partitions are created withLIKE … INCLUDING ALL, which copies an identity column, and PostgreSQL then refuses to attach them — so a root declaredGENERATED ALWAYS AS IDENTITYcould not be partitioned at all, on the flat path too. Verified that this fails identically onmaster, so it is not a regression introduced here.Commits
Not squashed — each is independently green (
ruff+ruff format+mypy+ unit tests, verified withgit rebase --exec):refactor: introduce the partition-tree domain modelfeat: add boundary codecs for time-sortable partition keysfeat: manage nested RANGE -> HASH partition treesfeat: add ensure_partitions for backfilling explicit periodsfix: exclude identity columns when creating partitionsdocs: document subpartitioning, boundary codecs and the migration pathfeat: add LIST subpartitioning alongside HASHfeat: manage HASH and LIST roots that have no time dimensionfeat: support composite partition keysfix: keep doubled quotes from splitting a LIST boundfix: keep partition_column in serialized configurationdocs: add the new boundary and bounds names to the API referencefix: explain a partition that can never report as closedfix: spell a partition key as one leading column plus a trailing tuplefix: stop the planner abandoning subtrees and planning unusable namesfix: tell a lost race apart from a real conflict, and isolate each branchfix: tell NULL from 'NULL', and a hidden child from a missing onefix: answer "is it closed?" instead of raising, and refuse a key we cannot addressfix: leave NULL-keyed rows where PostgreSQL puts themtest: confirm the four semantics against a real PostgreSQLdocs: say what the database reported, not what was assumedtest: cover the paths that were only ever exercised by accidenttest: assert the attach ordering instead of the fixture that set it updocs: correct three more claims, and test the one that was only written downdocs: say that issues now fills up on a successful rundocs: name the difference between two fields called partition_typetest: satisfy the protocol checks the way Python 3.12 checks themfix: read the whole key, every constraint, and the timezone that wrote the boundfix: never publish a branch that cannot route its whole keyspacetest: kill the mutations the suite was letting throughdocs: correct what the fact-checker falsified, and add what it found missingfix: quoting hazards that only a hand-built statement can reachtest: measure branch coverage, and cover the branches it exposedSecond 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
ATTACHwas recorded as a finding and then ignored — the loop attached the parentanyway. Worse, on the creation path the finding was discarded:
build_new_branchcalledmaterialize()with no collector, and the collector it makes for itself was thrown awayunread, so nothing was even logged. Reproduced end to end on PostgreSQL 17:
ensure_partitionreturned a successfulPartitionInfofor a branch that then rejected56 of 200 inserts. A node whose child was refused is now left detached and reported, and
build_new_branchraises rather than handing back a count for a subtree it could notfinish.
reconcile_default_rowsmoved rows by column position.RETURNING *into anunqualified
INSERTbinds the DEFAULT partition's physical order to the target's.ATTACH PARTITIONmatches columns by name, so the two orders need not agree — and whenthey do not, values are silently transposed with the source rows already deleted.
Reproduced:
labelandnoteswapped, no error, on the automatic conflict-retry path.Both sides name their columns now.
Major
PARTITION_TREE_SQLinner-joinedpg_attribute, dropping expression key positions — and a shortened key compares equal to a one-column spec, soCOLUMN_MISMATCHnever firedLEFT JOIN; nodes carryhas_expression_keyand the planner refuses themCREATE UNIQUE INDEXandEXCLUDEconstraints, both of whichLIKE … INCLUDING ALLcopiespg_index, unions in exclusion constraints, counts only key columnsspec.columnsis_partition_closedresolved naive bounds under the reader's session timezone, not theddl_timezonethe writer used — up to a day out on atimestampkeyddl_timezoneplan_new_subtreesilently dropped over-long names, producing a partitioned relation with zero children that was then attachedcontinue_on_error, because prune identification was the one step outside ittzinfo; prune identification is insidecontinue_on_errorPartitionRepository.reconcile_default_rowsin place broke mypy for every third-party implementationCompositeKeyRepositoryWhat 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_branchwithif Falseleft 936tests 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, zeroingrepaired_count, droppingactionable findings from
issues, and dropping the exclusion of partitions about to bepruned. 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
issuessection added lastround 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
NameErrorescapesmaintenance, because
parse_partition_namecatches onlyValueError— its schema useduuid_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
DEFAULT_HOLDS_ROWSconflict leaves one detached table with noorphan 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_partitionsdrops an unaddressable child with a log line whereget_partition_treemarks the parent. The asymmetry errs safely: the tree feeds the planner, where a missing
child would mean proposing a duplicate;
list_partitionsfeeds retention, where it onlymeans not dropping something.
InvalidPartitionConfigErrorwhere repository onesraise
UnsupportedCapabilityError. Both derive fromPartitionError, and each readscorrectly 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:
None;partition_column=andcolumn=remain accepted spellingsperiod_calculatorbecame optional, which is additiveSubpartitionRepository,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 morePartitionTypemoved topg_partsmith.topologyand is re-exported from its historical homeSerialization is a superset, not a rename. Composite-key support turned
partition_columninto a derived value, which would have dropped it frommodel_dump()— parsing an old config still worked, but code readingdump["partition_column"]back would not have found it. It is exposed as acomputed field instead, so the dump carries both spellings. Verified by
diffing the serialized key set of every public model against
master:TablePartitionConfigpartition_columns,root_layout,subpartitionPartitionInfobounds,subpartition_typeMaintenanceResultrepaired_countMaintenanceIssuepartition_nameNothing
masteremitted has stopped being emitted. Round-tripping a dump thatnames 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:
master: 107 pre-existing methods, 0 removed, 0 changed, 20 added. Anyone who implemented a protocol or subclassed a bundled class is unaffected.__all__: identical. Every name in__all__resolves.TODO/FIXMEleft, no skipped orxfailtests, 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
ATTACHotherwise 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.