Skip to content

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

Closed

Description

@AlexeyShalaev

Problem statement

Some teams empty expired partitions in place instead of detaching them. MTS's data-rentgen does it by default: its cleanup_partitions truncate runs TRUNCATE on expired partitions of five lineage tables and leaves them attached (cleanup_partitions.py). pg-partsmith can only detach (and then drop or keep the detached table), so for a project like that it is not a drop-in replacement: it would change what their operators see.

There is a real operational reason to want it. On PostgreSQL 17, TRUNCATE of a leaf takes ACCESS EXCLUSIVE on that leaf only, while a blocking DETACH (the only kind allowed once a DEFAULT partition exists) takes ACCESS EXCLUSIVE on the parent as well:

truncate | ev_10 | ShareLock
truncate | ev_10 | AccessExclusiveLock
detach   | ev    | AccessExclusiveLock
detach   | ev_11 | AccessExclusiveLock

So emptying in place never queues writers to the parent behind the retention step.

Proposed solution

A retention action next to detach, for example:

LifecyclePolicy(
    retention=KeepFor(timedelta(days=365)),
    expire=TruncateInPlace(),                # instead of detach
)
# or, emptied now and removed from the tree later:
LifecyclePolicy(
    retention=KeepFor(timedelta(days=365)),
    expire=TruncateInPlace(then=DropAfter(timedelta(days=90))),
)

Things to decide:

  • Idempotency. An emptied partition stays expired forever. The planner should not truncate it again on every tick (each TRUNCATE still takes ACCESS EXCLUSIVE on the leaf); a cheap "is it empty" fact (SELECT 1 ... LIMIT 1) or a marker comment would do.
  • Accumulation. Without then=, emptied partitions pile up. That may be what the user wants (stable table set), but the plan should report them so it is visible.
  • Hooks. before_drop is where people export data today. A truncate needs the same last-chance hook, probably before_truncate / after_truncate, with on_event covering it.
  • Foreign keys. TRUNCATE of a partition referenced by a foreign key fails unless CASCADE, which the library never uses. That should be a finding with a reason, not an error mid-run.
  • CLI and YAML. The document schema needs the same option.

Alternatives considered

  • DropNever() plus a hook that truncates: the partition is still detached first, so the parent lock and the change in the visible tree remain.
  • ExpireIf(SqlPredicate(...)) cannot express "empty it", only "expire it".

Scope

Lifecycle service

Activity

  1. AlexeyShalaev commented on Nov 22, 2026

    @AlexeyShalaev
    MemberAuthor

    Plan before I write code.

    How I read the problem: retention can only take an expired partition out of the tree, so a project that empties expired partitions in place (data-rentgen's cleanup_partitions truncate) can't switch without changing what its operators see and giving up the lock profile. I checked the locking claim on PostgreSQL 15, 16, 17 and 18. With TRUNCATE ev_10 held open, the session holds ACCESS EXCLUSIVE on ev_10 and its indexes and nothing else, and inserts or pruned reads through ev into other partitions finish in about 1 ms. With a blocking DETACH (DEFAULT present) it holds ACCESS EXCLUSIVE on ev and on the DEFAULT partition, and the same insert hits lock_timeout.

    Design: a new expire field on LifecyclePolicy, an enum next to detach:

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

    In a document that is expire: truncate inside lifecycle:. The default is ExpireAction.DETACH, so existing configs plan exactly as before. Under truncate the planner emits a TruncatePartition operation (kind truncate, reason retention_expired) instead of a detach. It runs in one transaction: lock_timeout, LOCK TABLE <partition> IN ACCESS EXCLUSIVE MODE, the OID and still-attached checks, then TRUNCATE. The parent is never locked. detach and drop keep governing orphans that already exist.

    The open questions from the issue:

    • Idempotency: a new fact, FactKind.EMPTY, true when no leaf of the subtree has a heap page (pg_relation_size, one catalog query for all partitions, no scan). An expired partition that is already empty gets no operation, so the second run is a no-op, and a row that lands there later gets it emptied again. No marker, because the catalog already answers the real question.
    • Accumulation: one INFO finding per parent, expired_empty, with the count and the oldest partition. One per parent because the set only grows.
    • Hooks: before_truncate / after_truncate, covered by on_event, and the same two keys in the document's hooks section. A raising before_truncate leaves the partition alone for the next run, like before_drop.
    • Foreign keys: PostgreSQL refuses TRUNCATE of a partition with 0A000 as soon as any foreign key points at it or its parent, even with no referencing rows (the key is cloned onto every partition). A second fact, FactKind.REFERENCED_BY, reads the referencing tables from pg_constraint, and an expired partition with rows and a referencing table becomes a WARNING finding, truncate_blocked, with no operation. Same finding when the subtree holds a foreign table, since TRUNCATE there empties the remote table. expire=truncate with ForeignLeaves is refused when the config is built.
    • CLI and YAML: lifecycle: already takes the policy's JSON, so no new document field beyond the two hook keys. apply without --allow-destructive withholds truncates with detaches and drops, and maintain(skip_detach=True) leaves them out, because a truncate is what retention does in place of the detach. truncated_count goes on MaintenanceResult, the apply output and the metrics.
    • then=: not in this change. data-rentgen never removes an emptied partition, and switching expire back to detach already retires them (retention still says they expired, so they get detached and dropped under the drop policy). It can be added later without breaking anything.

    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, that is what keeps the ownership checks in the core), and DetachMode.TRUNCATE (a truncate is not a way to detach, and the mode also drives finishing an interrupted concurrent detach).

    Two notes for custom code: PartitionRepository gains truncate_partition, and a hook class that implements the protocol without subclassing BasePartitionLifecycleHooks needs the two new methods before it is used with expire=truncate. And since the policy serializes one more field, a plan saved with 1.10 counts as config drift for apply --plan.

  2. AlexeyShalaev commented on Nov 22, 2026

    @AlexeyShalaev
    MemberAuthor

    #149 implements this, close to the plan above. For data-rentgen's case the config is:

    lifecycle:
      retention: { kind: keep_for, age: P365D }
      expire: truncate

    apply --allow-destructive then empties each expired partition with TRUNCATE and leaves it attached, the parent is never locked, and a partition that is already empty is left alone, so the steady state is a run with no DDL and one expired_empty line in the plan saying how many emptied partitions the table keeps. Without --allow-destructive, truncates are withheld like detaches and drops.

    Two things changed from the plan after a review pass. A foreign key added after the plan was made is now caught under the truncate's own lock and recorded as a truncate_blocked issue, so it never aborts the run. And the docs now spell out two limits: before_truncate runs while the partition still takes writes, so a row written into the expired window after the hook read it is emptied unread, and logical replication carries a TRUNCATE (a detach or a drop never replicates). A table published to a subscriber that keeps more history needs truncate left out of that publication's publish (checked on PostgreSQL 17 with a publisher and a subscriber).

    Nothing else needs to change on your side unless you have your own PartitionRepository (it needs truncate_partition) or a hook class that implements the protocol without subclassing BasePartitionLifecycleHooks (it needs before_truncate and after_truncate).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions