Skip to content

Commit 680954d

Browse files
AlexeyShalaevAlexey Shalaev
andauthored
feat: an expired partition stays detached for a week unless the policy names a drop (#113)
* 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 * test: the e2e document drops expired partitions in the same run --------- Co-authored-by: Alexey Shalaev <shalaevad.alexey@gmail.com>
1 parent 9a95ca0 commit 680954d

22 files changed

Lines changed: 140 additions & 42 deletions

‎CHANGELOG.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
4040

4141
* a backfilled window always attaches with writers held at the parent ([#89](https://github.com/bedrock-python/pg-partsmith/issues/89)) ([b1260c1](https://github.com/bedrock-python/pg-partsmith/commit/b1260c1a8bcdd6388c3836d57eb548f8fe5959bb))
4242

43+
## 1.9.0 — an expired partition stays detached for a week by default
44+
45+
A policy that named no drop — every flat config (`create_ahead_count`, `retention_count`),
46+
every bare `TablePartitionConfig(...)` and every YAML table without `drop:` — got
47+
`DropAfter()` with no grace, so an expired partition was detached and dropped in the same
48+
run. A wrong `retention_count` or granularity lost the data on the first scheduled run, with
49+
no window to notice ([#106](https://github.com/bedrock-python/pg-partsmith/issues/106)).
50+
51+
**What changes:** when the policy names no drop it is now `DropAfter(grace=timedelta(days=7))`.
52+
An expired partition stays detached for a week, where it can be inspected or re-attached,
53+
and the first run after that drops it. Disk is freed a week later than before.
54+
55+
**What stays:** an explicit `DropAfter()` keeps its zero grace, so a configuration that asked
56+
for the immediate drop keeps it. `DropNever()` is unchanged.
57+
4358
## 1.8.3 — a refused detach no longer starts the drop grace
4459

4560
A `DETACH … CONCURRENTLY` writes the orphan marker, with its `detached-at` instant, in a

‎docs/agents.md‎

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

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -181,15 +181,22 @@ def write_document(
181181
dsn: str | None = None,
182182
hooks: Mapping[str, Any] | None = None,
183183
) -> Path:
184-
"""One table, monthly, two partitions ahead: the document the guides start from, as JSON."""
184+
"""One table, monthly, two partitions ahead, as JSON.
185+
186+
Expired partitions are dropped in the run that detaches them, as these tests
187+
expect; without ``drop`` a detached partition would wait a week.
188+
"""
185189
payload: dict[str, Any] = {
186190
"tables": [
187191
{
188192
"table_name": table,
189193
"partition_column": "created_at",
190194
"granularity": "month",
191-
"create_ahead_count": 2,
192-
"retention_count": retention,
195+
"lifecycle": {
196+
"creation": {"kind": "create_ahead", "count": 2},
197+
"retention": {"kind": "keep_newest", "count": retention},
198+
"drop": {"kind": "drop_after", "grace": "P0D"},
199+
},
193200
}
194201
]
195202
}

0 commit comments

Comments
 (0)