Repository navigation
feat: expired partitions can be emptied in place instead of detached - #149
Merged
Merged
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
11 of 15 tasks
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.
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.
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:or
expire: truncatein a document'slifecycle. The default staysExpireAction.DETACH, so a policy that names noexpireplans exactly as before.Under
truncatethe planner emitsTruncatePartition(kindtruncate, reasonretention_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, sinceTRUNCATEitself names no parent), a look for foreign tables in the subtree and for foreign keys reaching the partition, thenTRUNCATE. Nothing is locked on the parent.detachanddropkeep governing orphans that already exist.The decisions from the issue:
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.expired_empty, with the count and the oldest partition. The lifecycle page says what the growing set costs, with numbers.before_truncate/after_truncate, covered byon_event, and the same two keys in the document'shooks.TRUNCATEof a partition any foreign key reaches, rows or no rows (a key on the parent is cloned onto every partition).FactKind.REFERENCING_TABLESreads the referencing tables frompg_constraint, and an expired partition with rows and a referencing table becomes atruncate_blockedWARNING.TRUNCATEof a partitioned table reaches its foreign partitions and empties the remote tables. A subtree holding one istruncate_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).ForeignLeaveswithexpire=truncateis refused when the config is built.truncate_blockedissue, and the run goes on.applywithout--allow-destructivewithholds every destructive operation, truncates included,maintain(skip_detach=True)leaves them out, andtruncated_countis in the result, the apply output and the metrics.then=: left out. data-rentgen never removes an emptied partition, and switchingexpireback todetachretires 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), andDetachMode.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:
PartitionRepositorygainstruncate_partition, a metadata provider of your own has to answer the two new facts, a hook class implementing the protocol without subclassingBasePartitionLifecycleHooksneeds 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 totruncate: the role needsTRUNCATEon partitions another role created (owning the parent does not give it), logical replication carries aTRUNCATEwhere it never carries a detach or a drop, and a read pruned only when it runs waits for a queued truncate up toddl_lock_timeout_ms.Measured on real servers before writing the docs (
docs/design/postgresql-semantics.mdhas the details):TRUNCATE ev_10holdsACCESS EXCLUSIVEonev_10and its indexes and nothing onev, and inserts and reads pruned at plan time into other partitions finish in about 1 ms. A blockingDETACH PARTITION ev_11holdsACCESS EXCLUSIVEonev,ev_11andev_default, and the same insert and read hitlock_timeout(55P03after 1 s).lock_timeout = 3000ms, anow()-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.TRUNCATEis refused with0A000for 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.TRUNCATE ev_10on the publisher emptiedev_10on the subscriber; withpublish = 'insert, update, delete'it did not.ALTER TABLE ev OWNER TO partsmithleavesev_10with its old owner,TRUNCATE ev_10aspartsmithis denied, andGRANT TRUNCATE ON ev_10is 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:
55P03;0A000;Results:
make checkclean (ruff, format, mypy over 92 files);make teston 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 againDismissed (1)
pg_partsmith/planner.py:727- unmeasuredempty/referencing_tablesfacts 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