Skip to content

Commit 6c14f9b

Browse files
author
Alexey Shalaev
committed
feat: plan on the database's clock, not the process's
A plan's "now" is the database's clock unless the caller names an instant. It used to be the clock of the process running maintenance, and nothing compared the two: with a container at June 2027 against data through September 2026, one apply --allow-destructive detached and dropped every monthly partition, the current one included, and exited 0. current_time() is a method of PartitionMetadataProvider in both mirrors: SELECT now(), in UTC. PartitionInspector.context() reads it when no instant is given; plan(now=...) is unchanged. The integration suites travel in time with freezegun, which moves only the process clock, so tests/integration/conftest.py answers current_time() from the process clock there, except in tests marked database_clock. The new one freezes the process three years ahead and checks that the database's current month survives; it fails on the old inspector. The detach stamp the orphan grace period counts from still comes from the process; moving it changes the repository protocol. Closes #74
1 parent 13ce1d3 commit 6c14f9b

25 files changed

Lines changed: 275 additions & 83 deletions

‎CHANGELOG.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,24 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## 1.6.0 — plans on the database's clock
9+
10+
A plan is made against the database's clock, `now()`, unless the caller names an instant.
11+
It used to be made against the clock of the process running maintenance, and nothing
12+
compared the two: a container whose clock ran ahead decided retention for a date the data
13+
had not reached. With the container at June 2027 and the data at September 2026, one
14+
`apply --allow-destructive` detached and dropped every monthly partition, the current one
15+
included, and exited 0 ([#74](https://github.com/bedrock-python/pg-partsmith/issues/74)).
16+
pg_partman never had this problem, because it runs inside the database.
17+
18+
`current_time()` is a method of `PartitionMetadataProvider` in both mirrors, and a provider
19+
of your own now has to answer it with the clock of the database it reads. `plan(now=...)`
20+
still plans against whatever instant it is given.
21+
22+
Not moved yet: the instant a detach is stamped with, which the orphan grace period counts
23+
from, is still the process's, so a clock that is off moves the end of the grace period by
24+
as much. Moving the stamp changes the repository protocol and is its own change.
25+
826
## [1.5.1](https://github.com/bedrock-python/pg-partsmith/compare/pg-partsmith-v1.5.0...pg-partsmith-v1.5.1) (2026-09-07)
927

1028

‎docs/concepts/boundaries.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ partition for a window is called. Three implementations ship.
77

88
| Boundaries | Axis | Window | Cursor |
99
|---|---|---|---|
10-
| `TimeBoundaries` | instants | a calendar period | the clock |
10+
| `TimeBoundaries` | instants | a calendar period | the database's clock |
1111
| `NumericBoundaries` | integers | a fixed-width step | `max(key)` or the key's sequence |
1212
| `IntegerSequence` | integers | one value | the newest partition |
1313

@@ -47,7 +47,9 @@ or a custom one. The calculator names partitions and renders their bounds:
4747
| `QUARTER` | `events__2026_q3` | |
4848
| `YEAR` | `events__2026` | |
4949

50-
The cursor is the clock, read in the calendar's timezone.
50+
The cursor is the database's clock, `now()`, read in the calendar's timezone. It is the
51+
database's rather than the maintenance process's so that a container with a wrong clock
52+
cannot decide retention for a date the data has not reached.
5153

5254
### Timezones
5355

@@ -152,7 +154,7 @@ timezone.
152154

153155
| Axis | Cursor | Where it comes from |
154156
|---|---|---|
155-
| time | the current instant, in the calendar's zone | the clock (`now=` on `plan()` to override) |
157+
| time | the current instant, in the calendar's zone | the database's clock (`now=` on `plan()` to override) |
156158
| integer (`NumericBoundaries`) | the key's high-water mark | `max(key)` over the table, or the sequence |
157159
| integer (`IntegerSequence`) | the newest partition's value | the tree (`NEWEST_MEMBER`), or `max(key)` |
158160

‎docs/concepts/overview.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,8 @@ timezone, optionally over an encoded key (UUIDv7, epoch) through a codec.
4848
`NumericBoundaries` cuts an integer axis into fixed steps. `IntegerSequence` gives a
4949
sliding LIST one value per partition. Boundaries also decide the partition **names**.
5050

51-
The **cursor** is "now" on the axis: the clock for time, the key's high-water mark for
52-
integers, the newest partition for a sliding list.
51+
The **cursor** is "now" on the axis: the database's clock for time, the key's high-water
52+
mark for integers, the newest partition for a sliding list.
5353

5454
→ [Boundaries, cursors and calendars](boundaries.md)
5555

‎docs/design/api-cheatsheet-1.0.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ Executor (`aio/services/execution.py` `PlanExecutor(repo, metadata, hooks)`): `a
5252

5353
Repository protocol (`PartitionRepository`): `create_table_like(template_name, table_name, partition_by: PartitionBy | None, *, physical: LocalLeaves | None = None)`, `create_foreign_table_like(template_name, table_name, *, server, options)`, `move_rows(source, target, *, limit=None) -> int`, `attach_partition(parent, partition, bounds: PartitionBounds, *, key_arity=1)`, `detach_partition(parent, partition, *, mode=DetachMode.AUTO)`, `drop_partition(partition, *, expected_oid=None)`, `adopt_partition(table, partition) -> bool`, `reconcile_default_rows(*, default_partition_name, target_partition_name, key_columns, from_value, to_value, limit=None) -> int`. Old `create_partition/create_branch/create_subpartition_table/attach_subpartition/attach_composite_partition` are gone.
5454

55-
Metadata protocol (`PartitionMetadataProvider`): `get_partition_type`, `get_partition_columns`, `get_actual_tree(table) -> ActualTree | None`, `measure(tree, *, targets, facts, sql_predicates) -> ActualTree`, `get_partition_tree(name) -> PartitionNode | None`, `get_default_partition`, `partition_exists`, `is_partition_attached`, `get_relation_oid(name)`, `get_relation_kind(name)`, `get_unique_constraint_columns`, `get_key_high_water_mark(table, column, *, sequence=False)`, `get_leading_key_minimum(table, key_columns)`, `list_partitions`, `is_partition_closed(partition_name, *, settle_seconds=0, boundaries=None)` (on the protocol since 1.4.0). Plus on the Postgres implementation: `get_partition_column` (single-column only), `get_partition_boundaries`, `evaluate_sql_predicate`.
55+
Metadata protocol (`PartitionMetadataProvider`): `get_partition_type`, `get_partition_columns`, `get_actual_tree(table) -> ActualTree | None`, `measure(tree, *, targets, facts, sql_predicates) -> ActualTree`, `get_partition_tree(name) -> PartitionNode | None`, `get_default_partition`, `partition_exists`, `is_partition_attached`, `get_relation_oid(name)`, `get_relation_kind(name)`, `get_unique_constraint_columns`, `get_key_high_water_mark(table, column, *, sequence=False)`, `get_leading_key_minimum(table, key_columns)`, `list_partitions`, `is_partition_closed(partition_name, *, settle_seconds=0, boundaries=None)` (on the protocol since 1.4.0), `current_time()` (since 1.6.0; the database's clock, what `plan()` uses when `now` is not given). Plus on the Postgres implementation: `get_partition_column` (single-column only), `get_partition_boundaries`, `evaluate_sql_predicate`.
5656

5757
Hooks: in 1.0 `before_create(config, partition: PartitionInfo)` (was `(config, name, from_value, to_value)`) and the other five unchanged. **Superseded in 1.1**: every method takes one `PartitionEvent`, and there are eight phases plus `on_event` — see the changelog. Hooks fire for partitions directly under the root only (lifecycle units / root set members), never per leaf of a subtree.
5858

‎docs/guide/extending.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,9 @@ The protocol's reads: `get_partition_type`, `get_partition_columns`, `get_actual
9191
`measure`, `get_partition_tree`, `get_default_partition`, `partition_exists`,
9292
`is_partition_attached`, `get_relation_oid`, `get_relation_kind`,
9393
`get_unique_constraint_columns`, `get_key_high_water_mark`, `get_leading_key_minimum`,
94-
`list_partitions`, and `is_partition_closed`, which a provider of your own answers with
95-
False rather than an exception when it cannot read the bound.
94+
`list_partitions`, `is_partition_closed`, which a provider of your own answers with
95+
False rather than an exception when it cannot read the bound, and `current_time`, the
96+
database's clock a plan is made against when the caller names no instant.
9697

9798
## A lock manager
9899

‎docs/guide/troubleshooting.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ maintainer.
1010
- The windows exist already. Check `service.inspect(config)`.
1111
- The creation rule is `CreateNextIf` and the newest partition does not satisfy it yet.
1212
- The cursor is not where you think: an integer axis reads `max(key)` — an empty table
13-
starts at `origin`; a time axis reads the clock in the calendar's `tz`.
13+
starts at `origin`; a time axis reads the database's clock in the calendar's `tz`.
1414
- The run was planned in `RECONCILE` mode (`reconcile()` creates nothing ahead).
1515

1616
## `range_overlap` — a wanted window overlaps a partition I did not configure

‎pg_partsmith/aio/metadata.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,14 @@
44

55
import logging
66
from dataclasses import dataclass
7-
from datetime import datetime
7+
from datetime import UTC, datetime
88
from typing import TYPE_CHECKING, Any
99

1010
from sqlalchemy import text
1111
from sqlalchemy.exc import DBAPIError
1212

1313
from pg_partsmith.catalog_queries import (
14+
CURRENT_TIME_SQL,
1415
INCOMING_FOREIGN_KEYS_SQL,
1516
INSTANT_HAS_PASSED_SQL,
1617
ORPHANS_SQL,
@@ -556,6 +557,19 @@ async def get_relation_oid(self, name: str) -> int | None:
556557
value = result.scalar()
557558
return None if value is None else int(value)
558559

560+
async def current_time(self) -> datetime:
561+
"""The database's current time, in UTC.
562+
563+
What a plan is made against when the caller names no instant. Reading
564+
it here rather than off the process keeps a maintenance container with
565+
a wrong clock from deciding retention for a date the data has not
566+
reached.
567+
"""
568+
async with self._engine.connect() as conn:
569+
result = await conn.execute(text(CURRENT_TIME_SQL))
570+
instant: datetime = result.scalar()
571+
return instant.astimezone(UTC)
572+
559573
async def get_relation_kind(self, name: str) -> RelationKind | None:
560574
"""What the relation holding ``name`` physically is, or None when there is none."""
561575
async with self._engine.connect() as conn:

‎pg_partsmith/aio/protocols.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from __future__ import annotations
1717

1818
from contextlib import AbstractAsyncContextManager
19+
from datetime import datetime
1920
from typing import Any, Protocol, runtime_checkable
2021

2122
from pg_partsmith.boundaries import TimeBoundaries
@@ -438,6 +439,16 @@ async def is_partition_closed(
438439
"""
439440
...
440441

442+
async def current_time(self) -> datetime:
443+
"""The database's current time, timezone-aware.
444+
445+
What a plan is made against when the caller names no instant. A
446+
provider answers with the clock of the database it reads, not the
447+
process's: a maintenance process with a wrong clock would otherwise
448+
decide retention for a date the data has not reached.
449+
"""
450+
...
451+
441452

442453
@runtime_checkable
443454
class LockManager(Protocol):

‎pg_partsmith/aio/service.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ async def plan(
108108
mode: What the plan is for: the scheduled tick (``MAINTAIN``),
109109
converging the existing tree only (``RECONCILE``), or ensuring
110110
specific windows exist (``EXPLICIT``, with ``windows``).
111-
now: The instant to plan against; the current time by default.
111+
now: The instant to plan against; the database's current time by default.
112112
windows: In ``EXPLICIT`` mode, the windows to ensure at each
113113
progression level, keyed by leading column.
114114

‎pg_partsmith/aio/services/inspection.py‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ class PartitionInspector:
1919
2020
Two things beyond the tree itself: the *facts* the lifecycle policy asked
2121
for, gathered only for the relations a policy can decide over, and the
22-
*cursor* of every integer axis -- the clock needs no query.
22+
*cursors* -- the database's clock for a time axis, the high-water mark
23+
for an integer axis that reads one.
2324
"""
2425

2526
def __init__(self, metadata: PartitionMetadataProvider) -> None:
@@ -62,8 +63,13 @@ async def context(
6263
mode: PlanMode = PlanMode.MAINTAIN,
6364
explicit_windows: dict[str, tuple[Window, ...]] | None = None,
6465
) -> PlanningContext:
65-
"""Resolve the clock and the cursors the plan is made against."""
66-
instant = datetime.now(UTC) if now is None else now
66+
"""Resolve the clock and the cursors the plan is made against.
67+
68+
Without ``now`` the clock is the database's, not this process's: a
69+
maintenance container whose clock runs ahead would otherwise expire
70+
partitions the data has not finished with.
71+
"""
72+
instant = await self._metadata.current_time() if now is None else now
6773
if instant.tzinfo is None:
6874
instant = instant.replace(tzinfo=UTC)
6975

0 commit comments

Comments
 (0)