Skip to content

Commit d9a7b1c

Browse files
author
Alexey Shalaev
committed
feat: an expired partition stays detached for a week unless the policy names a drop
A LifecyclePolicy without drop= (every flat config, every bare TablePartitionConfig, every YAML table without drop:) used DropAfter() with no grace, so an expired partition was detached and dropped in the same run and a wrong retention lost the data at once. The default is now DropAfter(grace=timedelta(days=7)). An explicit DropAfter() keeps its zero grace; DropNever() is unchanged. Closes #106
1 parent a0e8730 commit d9a7b1c

21 files changed

Lines changed: 130 additions & 39 deletions

‎CHANGELOG.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,21 @@ inspection had put on it, so `plan`, `plan --check` and `apply` were silent abou
2929
states those findings exist for. It now returns a copy with the facts added
3030
([#108](https://github.com/bedrock-python/pg-partsmith/issues/108)).
3131

32+
## 1.9.0 — an expired partition stays detached for a week by default
33+
34+
A policy that named no drop — every flat config (`create_ahead_count`, `retention_count`),
35+
every bare `TablePartitionConfig(...)` and every YAML table without `drop:` — got
36+
`DropAfter()` with no grace, so an expired partition was detached and dropped in the same
37+
run. A wrong `retention_count` or granularity lost the data on the first scheduled run, with
38+
no window to notice ([#106](https://github.com/bedrock-python/pg-partsmith/issues/106)).
39+
40+
**What changes:** when the policy names no drop it is now `DropAfter(grace=timedelta(days=7))`.
41+
An expired partition stays detached for a week, where it can be inspected or re-attached,
42+
and the first run after that drops it. Disk is freed a week later than before.
43+
44+
**What stays:** an explicit `DropAfter()` keeps its zero grace, so a configuration that asked
45+
for the immediate drop keeps it. `DropNever()` is unchanged.
46+
3247
## 1.8.0 — rows in DEFAULT that no run would reach are reported
3348

3449
An application that writes its own key values can put a row into DEFAULT after the table

‎docs/agents.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -356,9 +356,10 @@ lifecycle units — partitions directly under the root — never once per leaf o
356356
(recorded as an issue under `continue_on_error=True`).
357357
7. **`create_ahead_count` and `retention_count` include the current period.**
358358
`create_ahead_count=3` means this month and the next two.
359-
8. **The default lifecycle drops.** `DropAfter()` has a zero grace, so an expired partition
360-
is detached and dropped in the same run. Choose `DropAfter(grace=…)` or `DropNever()`
361-
consciously.
359+
8. **The default lifecycle drops a week after the detach.** A policy that names no `drop`
360+
keeps an expired partition detached for seven days, where it can be inspected or
361+
re-attached, then drops it. `DropAfter()` (zero grace) drops in the same run as the
362+
detach; `DropNever()` leaves detached tables to someone else. Choose consciously.
362363
9. **`lifecycle` is meaningless for a scheme with no progression level** — a root
363364
`HashPartitioning` or a static `ListPartitioning` has a fixed set of partitions, and the
364365
policy is ignored rather than obeyed.

‎docs/concepts/lifecycle.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,8 +138,8 @@ referencing rows are gone. See [Handle foreign keys](../guide/foreign-keys.md).
138138

139139
| Rule | Effect |
140140
|---|---|
141-
| `DropAfter()` (default: no grace) | dropped in the same run as the detach |
142-
| `DropAfter(grace=timedelta(days=7))` | kept detached for a week, then dropped. The detach instant is recorded on the table's marker; an orphan marked by an older version, or adopted, has no instant and is treated as past its grace |
141+
| `DropAfter()` (no grace) | dropped in the same run as the detach |
142+
| `DropAfter(grace=timedelta(days=7))` (the default when the policy names no drop) | kept detached for a week, then dropped. The detach instant is recorded on the table's marker; an orphan marked by an older version, or adopted, has no instant and is treated as past its grace |
143143
| `DropAfter(grace=…, when=predicate)` | dropped only once the grace has passed *and* the predicate holds — "not while bigger than 150 GB on a weekday" is a `Callback` over the size fact |
144144
| `DropNever()` | detached partitions are left alone; something else owns the drop — an archive pipeline, a DBA. They are never re-attached, and a wanted window whose name such a table holds is reported (`name_unusable`), not recreated over it |
145145

‎docs/getting-started/first-table.md‎

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -241,14 +241,13 @@ plan for public.events at 2027-09-15T03:00:00+00:00
241241
CREATE public.events__2027_11 (create_ahead)
242242
DETACH public.events__2026_08 (retention_expired)
243243
DETACH public.events__2026_09 (retention_expired)
244-
DROP public.events__2026_08 (follows_detach)
245-
DROP public.events__2026_09 (follows_detach)
246244
```
247245

248-
Two things to notice. Retirement is a **detach** followed by a **drop**, two separate
249-
statements: the partition leaves the parent first, and only a table that is detached is
250-
ever dropped. And `events__2026_10` survives: the twelve newest months, counted back from
251-
September 2027, are October 2026 through September 2027.
246+
Two things to notice. Retirement is a **detach**, and the **drop** comes later: the
247+
partition leaves the parent first, and only a table that is detached is ever dropped —
248+
by default a week after its detach (see step 9). And `events__2026_10` survives: the
249+
twelve newest months, counted back from September 2027, are October 2026 through
250+
September 2027.
252251

253252
After `apply()`:
254253

@@ -261,14 +260,17 @@ events partitioned table PARTITION BY RANGE (created_at)
261260
```
262261

263262
(Only three months were ever created between the two runs, which is why the table looks
264-
sparse. A daily tick fills the calendar continuously.)
263+
sparse. A daily tick fills the calendar continuously. The two detached months are still in
264+
the database, outside the parent, until their week is up.)
265265

266-
## 9. A week between detach and drop
266+
## 9. Between detach and drop
267267

268-
Dropping in the same run as the detach is the default. Most teams want a pause — to
269-
export the partition, to be able to put it back. That is the `drop` half of a lifecycle
270-
policy. The flat fields you used so far are sugar for a scheme and a policy; spell the
271-
policy out to change it:
268+
A detached partition waits a week before it is dropped — a pause to export it, or to put
269+
it back if the retention was wrong. That is the `drop` half of a lifecycle policy, and the
270+
flat fields you used so far leave it at its default. The flat fields are sugar for a
271+
scheme and a policy; spell the policy out to choose the pause yourself (`DropAfter()`
272+
drops in the same run as the detach, `DropNever()` leaves detached tables to someone
273+
else):
272274

273275
```python
274276
from datetime import timedelta
@@ -325,8 +327,8 @@ meantime, a marked table whose month is wanted is *re-attached* rather than recr
325327
## What you have learned
326328

327329
- A configuration is a **scheme** (monthly partitions of `created_at`) plus a **lifecycle
328-
policy** (three ahead, twelve kept, drop a week after detach). The flat fields are sugar
329-
for both.
330+
policy** (three ahead, twelve kept, drop a week after detach — the default). The flat
331+
fields are sugar for both.
330332
- `plan()` is read-only and explains itself; `apply()` runs the plan under a lock.
331333
- Retirement is detach, then drop; grace periods live on the marker.
332334
- Findings are the planner telling you what it chose not to do, and why.

‎docs/guide/cli.md‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -174,14 +174,11 @@ pg-partsmith plan -c partitions.yaml --locks
174174
plan for public.events at 2026-09-01T02:15:00+00:00
175175
CREATE public.events__2026_10 (create_ahead)
176176
DETACH public.events__2025_08 (retention_expired) size=1073741824 rows~4021553
177-
DROP public.events__2025_08 (follows_detach)
178177
locks:
179178
CREATE public.events__2026_10
180179
ACCESS SHARE on the template during CREATE; SHARE UPDATE EXCLUSIVE on the parent and ACCESS EXCLUSIVE on the new partition (and on a DEFAULT sibling) during ATTACH -- EXCLUSIVE on the parent instead, which holds off writes, when rows of the window are taken out of a DEFAULT sibling in the attach's transaction; SHARE ROW EXCLUSIVE on every table referencing the parent through a foreign key
181180
DETACH public.events__2025_08 (outside a transaction block)
182181
SHARE UPDATE EXCLUSIVE on the parent (CONCURRENTLY), ACCESS EXCLUSIVE on the partition and, in the second transaction, on every table referencing the parent through a foreign key; ...
183-
DROP public.events__2025_08
184-
ACCESS EXCLUSIVE on the dropped table only
185182
```
186183
187184
The heaviest lock each operation takes, and on what, as measured on PostgreSQL 15 and 17

‎docs/reference/configuration.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Types are the accepted inputs; defaults are what you get when the field is omitt
1010
| `schema` | `str` | `None` | Schema of the parent table; read back as `db_schema`. Recommended. |
1111
| `table_name` | `str` | required | The parent table, lowercase, at most 63 bytes minus the scheme's longest suffix. |
1212
| `scheme` | `RangePartitioning \| ListPartitioning \| HashPartitioning` | from the flat fields | The root level and everything below it. |
13-
| `lifecycle` | `LifecyclePolicy` | `CreateAhead(count=6)`, `KeepNewest(count=12)`, `DetachMode.AUTO`, `DropAfter()` | When partitions of the progression level are created, detached and dropped. |
13+
| `lifecycle` | `LifecyclePolicy` | `CreateAhead(count=6)`, `KeepNewest(count=12)`, `DetachMode.AUTO`, `DropAfter(grace=timedelta(days=7))` | When partitions of the progression level are created, detached and dropped. |
1414
| `leaves` | `LocalLeaves \| ForeignLeaves` | `LocalLeaves()` | What kind of relation the leaves are. |
1515

1616
Flat fields, accepted instead of `scheme` / `lifecycle` for a time-partitioned RANGE root:
@@ -103,7 +103,7 @@ literals.
103103
| `creation` | `CreateAhead \| CreateUntil \| CreateNextIf` | `CreateAhead(count=6)` | which windows must exist ahead of the cursor |
104104
| `retention` | any predicate | `KeepNewest(count=12)` | when a window behind the cursor has expired |
105105
| `detach` | `DetachMode` | `AUTO` | `AUTO`, `CONCURRENT`, `BLOCKING` |
106-
| `drop` | `DropAfter \| DropNever` | `DropAfter()` | what happens after the detach |
106+
| `drop` | `DropAfter \| DropNever` | `DropAfter(grace=timedelta(days=7))` | what happens after the detach; `DropAfter()` drops in the same run |
107107

108108
Creation rules: `CreateAhead(count ≥ 1)`; `CreateUntil(position)` — a `datetime`, an
109109
`int`, or their string forms; `CreateNextIf(when)` — a predicate over the newest

‎pg_partsmith/constants.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
# Default configuration values.
44
DEFAULT_CREATE_AHEAD_COUNT = 6
55
DEFAULT_RETENTION_COUNT = 12
6+
# How long an expired partition stays detached, and can be re-attached, when the policy names no drop.
7+
DEFAULT_DROP_GRACE_DAYS = 7
68

79
# PostgreSQL limits.
810
MAX_IDENTIFIER_LENGTH = 63

‎pg_partsmith/entities.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,9 @@ class TablePartitionConfig(BaseModel):
238238
)
239239
240240
The ordinary time-partitioned table keeps its flat spelling, which is sugar
241-
for exactly that::
241+
for exactly that. Neither names a drop, so an expired partition stays
242+
detached for a week before it is dropped; pass ``drop=`` in a
243+
``LifecyclePolicy`` to choose otherwise::
242244
243245
TablePartitionConfig(
244246
table_name="events",

‎pg_partsmith/lifecycle.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
from pydantic import BaseModel, ConfigDict, Field, field_validator
2626

2727
from .boundaries import Axis, RangeBoundaries, Window
28-
from .constants import DEFAULT_CREATE_AHEAD_COUNT, DEFAULT_RETENTION_COUNT
28+
from .constants import DEFAULT_CREATE_AHEAD_COUNT, DEFAULT_DROP_GRACE_DAYS, DEFAULT_RETENTION_COUNT
2929
from .topology import FactKind, PartitionFacts, PartitionNode
3030
from .types import NonNegativeInt, PositiveInt
3131

@@ -776,15 +776,18 @@ class LifecyclePolicy(BaseModel):
776776
creation: Which windows ahead of the cursor must exist.
777777
retention: When a window behind the cursor has expired.
778778
detach: How an expired partition is detached.
779-
drop: What happens to it afterwards.
779+
drop: What happens to it afterwards. Unless the policy says otherwise, it
780+
stays detached for a week, where it can still be inspected or
781+
re-attached, and is dropped after that. ``DropAfter()`` drops in the
782+
same run as the detach; ``DropNever()`` leaves it alone.
780783
"""
781784

782785
model_config = ConfigDict(frozen=True, extra="forbid")
783786

784787
creation: CreationPolicy = Field(default_factory=CreateAhead)
785788
retention: RetentionPolicy = Field(default_factory=KeepNewest)
786789
detach: DetachMode = DetachMode.AUTO
787-
drop: DropPolicy = Field(default_factory=DropAfter)
790+
drop: DropPolicy = Field(default_factory=lambda: DropAfter(grace=timedelta(days=DEFAULT_DROP_GRACE_DAYS)))
788791

789792
@property
790793
def required_facts(self) -> frozenset[FactKind]:

‎tests/integration/aio/builder.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from pg_partsmith.entities import PartitionGranularity, Period, TablePartitionConfig
1818
from pg_partsmith.lifecycle import DetachMode
1919
from pg_partsmith.topology import RangeBounds
20+
from tests.integration.nested_support import drops_at_once
2021

2122
if TYPE_CHECKING:
2223
from sqlalchemy.ext.asyncio import AsyncEngine
@@ -99,7 +100,7 @@ async def build(self) -> PartitioningTestContext:
99100
metadata = PostgresMetadataProvider(self._engine)
100101
locks = PostgresAdvisoryLockManager(self._engine)
101102

102-
config = TablePartitionConfig(
103+
config = drops_at_once(TablePartitionConfig)(
103104
table_name=self._table_name,
104105
partition_column="created_at",
105106
granularity=self._granularity,

0 commit comments

Comments
 (0)