Skip to content

feat: expired partitions can be emptied in place instead of detached - #149

Merged
AlexeyShalaev merged 6 commits into
masterfrom
feat/empty-expired-partitions-in-place
Nov 23, 2026
Merged

AlexeyShalaev merged 6 commits into
masterfrom
feat/empty-expired-partitions-in-place

Conversation

@AlexeyShalaev

@AlexeyShalaev AlexeyShalaev commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Closes #130.

Retention could only take an expired partition out of the tree, so a project that empties expired partitions in place (data-rentgen's cleanup_partitions truncate) could not switch without changing what its operators see. This adds that choice to the policy:

LifecyclePolicy(retention=KeepFor(timedelta(days=365)), expire=ExpireAction.TRUNCATE)

or expire: truncate in a document's lifecycle. The default stays ExpireAction.DETACH, so a policy that names no expire plans exactly as before.

Under truncate the planner emits TruncatePartition (kind truncate, reason retention_expired) instead of a detach. The repository runs it in one transaction: lock_timeout, LOCK TABLE <partition> IN ACCESS EXCLUSIVE MODE, the OID check, a check that the partition is still attached to the parent (always, since TRUNCATE itself names no parent), a look for foreign tables in the subtree and for foreign keys reaching the partition, then TRUNCATE. Nothing is locked on the parent. detach and drop keep governing orphans that already exist.

The decisions from the issue:

  • Idempotency: a new fact, FactKind.EMPTY, true when no leaf of the subtree has a heap page (pg_relation_size, added to the existing facts query, no scan). An empty expired partition gets no operation, so the second run issues no DDL; a late row makes it non-empty and the next run empties it again.
  • Accumulation: one INFO finding per parent, expired_empty, with the count and the oldest partition. The lifecycle page says what the growing set costs, with numbers.
  • Hooks: before_truncate / after_truncate, covered by on_event, and the same two keys in the document's hooks.
  • Foreign keys: PostgreSQL refuses TRUNCATE of a partition any foreign key reaches, rows or no rows (a key on the parent is cloned onto every partition). FactKind.REFERENCING_TABLES reads the referencing tables from pg_constraint, and an expired partition with rows and a referencing table becomes a truncate_blocked WARNING.
  • Foreign tables: TRUNCATE of a partitioned table reaches its foreign partitions and empties the remote tables. A subtree holding one is truncate_blocked, checked before emptiness since a foreign leaf has no local heap pages, and so is a subtree with a child the tree cannot show (a name with a dot). ForeignLeaves with expire=truncate is refused when the config is built.
  • Late changes: a foreign key or a foreign table that appears after the plan is found under the truncate's lock and recorded as a truncate_blocked issue, and the run goes on.
  • CLI and YAML: no new document field beyond the two hook keys. apply without --allow-destructive withholds every destructive operation, truncates included, maintain(skip_detach=True) leaves them out, and truncated_count is in the result, the apply output and the metrics.
  • then=: left out. data-rentgen never removes an emptied partition, and switching expire back to detach retires them through the ordinary path (there is an integration test for that).

Rejected: DropNever() plus a truncating hook (still detaches first), a generic "run this SQL on expiry" action (a policy decides eligibility and never runs DDL), and DetachMode.TRUNCATE (a truncate is not a way to detach, and the mode also drives finishing an interrupted concurrent detach).

What changes for custom code and operators, also in the changelog: PartitionRepository gains truncate_partition, a metadata provider of your own has to answer the two new facts, a hook class implementing the protocol without subclassing BasePartitionLifecycleHooks needs the two new methods, and a plan saved by 1.10 counts as config drift because the policy serializes one more field. Before switching a table to truncate: the role needs TRUNCATE on partitions another role created (owning the parent does not give it), logical replication carries a TRUNCATE where it never carries a detach or a drop, and a read pruned only when it runs waits for a queued truncate up to ddl_lock_timeout_ms.

Measured on real servers before writing the docs (docs/design/postgresql-semantics.md has the details):

  • PostgreSQL 15.20, 16.16, 17.11 and 18.7, a monthly parent with a DEFAULT partition, one statement held open: TRUNCATE ev_10 holds ACCESS EXCLUSIVE on ev_10 and its indexes and nothing on ev, and inserts and reads pruned at plan time into other partitions finish in about 1 ms. A blocking DETACH PARTITION ev_11 holds ACCESS EXCLUSIVE on ev, ev_11 and ev_default, and the same insert and read hit lock_timeout (55P03 after 1 s).
  • 17.11 and 18.7, a reader holding the expired partition: with the truncate queued under lock_timeout = 3000ms, a now()-relative read of the current month took 2.7 s and an insert 1.6 ms; with a concurrent detach queued instead, 2 ms and 1.8 ms.
  • 15.20 and 18.7: TRUNCATE is refused with 0A000 for a key on the parent, on one partition (that partition only) and a self-referencing key on the parent, and the referencing-tables query gives the same answer in each case.
  • 17.11, two containers: with a default publication, TRUNCATE ev_10 on the publisher emptied ev_10 on the subscriber; with publish = 'insert, update, delete' it did not.
  • 17.11: ALTER TABLE ev OWNER TO partsmith leaves ev_10 with its old owner, TRUNCATE ev_10 as partsmith is denied, and GRANT TRUNCATE ON ev_10 is enough for the lock and the statement.

Tests: the reporter's case end to end (a year of retention, a DEFAULT partition, the partition emptied, still attached, same OID), the second run with no DDL, a late row emptied again, switching back to detach, a live writer inserting through the parent while the truncate waits for a reader of the expired partition (aio, plus a thread-based sync twin), each foreign key shape against a real server (a key on the parent, on one partition, on one hash bucket below an expired branch, a self-referencing key on the parent, a partition referencing itself, a key added after the plan), a RANGE -> HASH branch emptied whole and then left alone, a foreign bucket attached after the plan or named with a dot, and a detached table of the same name. Negative controls, each run against the integration suite:

  • the truncate locking the parent first: the writer test fails with 55P03;
  • no lock-time key check: the late-key test fails with 0A000;
  • no lock-time foreign check: the late foreign bucket's remote table is emptied;
  • no planner check for a child the tree cannot show: the dotted-name test fails;
  • the referencing-tables query limited to the relation itself: the hash-bucket key test fails;
  • its inside-the-subtree exclusion removed: the partition referencing itself is blocked;
  • the facts query reading the branch instead of its leaves: the branch is never emptied.

Results: make check clean (ruff, format, mypy over 92 files); make test on PostgreSQL 17: 3550 passed, 21 skipped (the e2e image tests), coverage 97.88%; integration on 15, 16 and 18: 609 passed on each; docs build clean.

AI Review

Commit f50e743, Claude Opus 5.5, fixes after it not reviewed again

  • Correctness - 6 fixed, 1 dismissed
  • Security - no findings
  • Performance - 2 fixed
  • Design & Style - 7 fixed
  • Tests - 5 fixed
  • Compatibility - 7 fixed
Dismissed (1)
  • pg_partsmith/planner.py:727 - unmeasured empty / referencing_tables facts plan the truncate: only a hand-written metadata provider leaves them unmeasured; truncating an empty table loses nothing, a referencing key is refused under the lock and recorded, and extending.md documents the contract

LifecyclePolicy(expire=ExpireAction.TRUNCATE), expire: truncate in a
document, empties an expired partition with TRUNCATE and leaves it
attached. TRUNCATE locks the partition and its subtree and nothing on
the parent, so writers to the other partitions do not wait for it,
where a blocking detach (forced by a DEFAULT partition) holds the
parent in ACCESS EXCLUSIVE.

The plan carries a TruncatePartition (kind truncate), the result a
truncated_count, and hooks get before_truncate / after_truncate. Two
new facts keep it idempotent and safe: EMPTY (no heap page in any
leaf, read from pg_relation_size) leaves an emptied partition alone
and counts it in one expired_empty INFO finding per parent, and
REFERENCED_BY (from pg_constraint) turns a partition PostgreSQL would
refuse to truncate into a truncate_blocked WARNING. apply without
--allow-destructive and maintain(skip_detach=True) leave truncates out.

Closes #130
The truncate looks for keys reaching the partition under its own lock, so a key added since the plan becomes a truncate_blocked issue and the run goes on. The docs now say that before_truncate runs while the partition still takes writes, that logical replication carries a TRUNCATE, and what a provider of your own has to answer. Tests cover a key on one partition, a self-referencing key and a key added after the plan against a real server.
@codecov

codecov Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

The truncate looks for foreign tables in the subtree under its own lock, as it does for foreign keys, and checks the partition is still attached to the parent whether or not an OID was given. The planner looks at the subtree before emptiness, since a foreign leaf has no local heap pages, and blocks one whose child the tree cannot show. FactKind.REFERENCED_BY is now REFERENCING_TABLES, the executor's truncate step is private and shares the attachment check with detach, both dispatch chains end in assert_never, and apply withholds whatever is destructive. Integration tests cover a RANGE -> HASH branch, a key on one bucket, a partition referencing itself, a foreign bucket added after the plan or named with a dot, and a detached table of the same name.
…eports

Reads pruned only when they run wait for a queued truncate up to ddl_lock_timeout_ms, measured against a concurrent detach; keeping every window costs planning time and locks, with numbers next to expired_empty; the role needs TRUNCATE on partitions another role created; troubleshooting sections for truncate_blocked and expired_empty; truncate added wherever ddl_lock_timeout_ms is described.
…itories mark theirs

A relation missing one statement after it was locked, and an operation outside the plan's discriminated union, are excluded from coverage with a reason, as creator.py already does for a relation missing right after its creation.
@AlexeyShalaev
AlexeyShalaev merged commit 1f95e78 into master Nov 23, 2026
33 checks passed
@AlexeyShalaev
AlexeyShalaev deleted the feat/empty-expired-partitions-in-place branch November 23, 2026 06:08
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.

[Feature]: empty expired partitions in place (TRUNCATE) instead of detaching

1 participant