Skip to content

Commit 1245fd9

Browse files
committed
fix: refuse a mismatched orphan marker, and let the boundaries answer for themselves
Three settings live on two objects and have to agree: the orphan marker prefix, the DDL timezone and the boundary codec. Passing one of them to a single collaborator is silent, which is the part worth fixing. The marker prefix is the one that matters to maintenance: the repository stamps it on detach, the metadata provider looks for it when discovering orphans, and a disagreement means nothing detached is ever seen again — no error, just partitions accumulating. PartitionLifecycleService now refuses that pair where the two first meet, structurally, the way the calculator/DDL timezone pair is already refused; a repository or provider that declares no prefix is trusted and skipped. Both now expose marker_prefix, and OrphanMarkerAware is the protocol that says so. The other two are used by is_partition_closed alone, and the object that knows both is the table's own TimeBoundaries — it chose the calendar, the timezone and the encoding. It can now be handed over directly, is_partition_closed(name, boundaries=config.time_boundaries), so reader and writer cannot disagree; the constructor arguments stay for callers without a config at hand. DropPartition also carries the bounds it was planned with. DETACH clears relpartbound, so by drop time the catalog no longer records where a partition sat and its name is the only evidence left — which the planner already decodes to decide the drop. Reporting it costs nothing, puts the period in the plan a reader sees, and gives an export a typed window without a second guess at the name. Refs #27.
1 parent 5f9185a commit 1245fd9

24 files changed

Lines changed: 342 additions & 35 deletions

‎docs/agents.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,12 @@ Constructor options worth knowing:
117117
* `RedisDistributedLockManager(redis_client, prefix=…, ttl_seconds=300, acquire_min_interval_seconds=0.0)`
118118
— needs the `redis-locks` extra; renews itself while long DDL runs.
119119

120+
`marker_prefix` must be the same on the repository and the provider — the first writes the
121+
ownership marker, the second finds it — and `PartitionLifecycleService` refuses a pair that
122+
disagrees. The provider's `boundary_codec` and `ddl_timezone` are used by
123+
`is_partition_closed` alone, which also takes `boundaries=config.time_boundaries` and reads
124+
both from there instead.
125+
120126
## Configuration
121127

122128
`TablePartitionConfig` is a frozen Pydantic model with `extra="forbid"`: an unknown keyword

‎docs/concepts/boundaries.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,10 @@ bound against the cutoff, and ownership compares it against the grid; a codec th
143143
only encode would create partitions the library could never recognise again.
144144

145145
`PostgresMetadataProvider(engine, boundary_codec=…)` needs the codec only for
146-
`is_partition_closed`; planning decodes through the configuration.
146+
`is_partition_closed`; planning decodes through the configuration. That one call also
147+
accepts the boundaries directly — `is_partition_closed(name, boundaries=config.time_boundaries)`
148+
— which is the way to be sure the reader and the writer agree about both the codec and the
149+
timezone.
147150

148151
## Cursors, in one place
149152

‎docs/concepts/ownership.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,11 @@ repo = PostgresPartitionRepository(engine, marker_prefix="app")
8282
metadata = PostgresMetadataProvider(engine, marker_prefix="app")
8383
```
8484

85-
Pass the same prefix to both.
85+
Pass the same prefix to both — the repository stamps the marker, the metadata provider
86+
looks for it, and a partition detached under one prefix is invisible to the other, so it
87+
would simply never be dropped. `PartitionLifecycleService` refuses a pair that disagrees
88+
when it is constructed rather than letting the orphans pile up quietly. (A custom
89+
repository or provider that declares no prefix is trusted and not checked.)
8690

8791
## Revalidation before anything destructive
8892

‎docs/concepts/plan.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ Operations are typed, ordered as they must execute, and nested where order matte
3030
| `CreatePartition` | create a partition, build its subtree, attach it | `parent_name`, `bounds`, `partition_by` (for a branch), `children`, `counts_as` |
3131
| `AttachPartition` | re-attach a detached orphan whose window is wanted again | `parent_name`, `bounds` |
3232
| `DetachPartition` | detach an expired partition, subtree included | `parent_name`, `mode`, `oid` |
33-
| `DropPartition` | drop a detached, marker-tagged orphan | `oid`, `detached_at`, `follows_detach` |
33+
| `DropPartition` | drop a detached, marker-tagged orphan | `oid`, `detached_at`, `follows_detach`, `bounds` |
3434

3535
Creations come first (each with its subtree inside it), then re-attachments, then
3636
detaches, then drops. Every operation records:

‎docs/guide/archiving.md‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,38 @@ service = PartitionLifecycleService(repo, metadata, locks, hooks=[ArchiveHooks(a
4848
Hooks are called in the order given; pass several for notifications, metrics and audit
4949
logs.
5050

51+
### What a drop hook can know
52+
53+
`before_detach` is handed the whole `PartitionInfo`, bounds included, because the
54+
partition is still attached and the catalog still describes it. `DETACH` clears
55+
`relpartbound`, so by drop time — usually a later run, after the grace — the database no
56+
longer records where the partition sat; its name is what is left. Two ways to get the
57+
window back, neither of them a catalog query:
58+
59+
```python
60+
class ExportHooks(BasePartitionLifecycleHooks):
61+
def __init__(self, config: TablePartitionConfig) -> None:
62+
self._boundaries = config.time_boundaries # the object that made the bounds
63+
64+
async def before_drop(self, table_name: str, partition_name: str) -> None:
65+
_, relname = split_qualified_name(partition_name)
66+
window = self._boundaries.parse_child_name(relname) # None if the name is not ours
67+
await self._archive.finalize(partition_name, covering=window)
68+
```
69+
70+
Or take the plan apart before applying it — every `DropPartition` carries the bounds it
71+
was planned with, plus `detached_at`, the OID and any size the policy measured:
72+
73+
```python
74+
plan = await service.plan(config)
75+
for drop in plan.drops:
76+
await archive.finalize(drop.target, covering=drop.bounds, size=drop.size_bytes)
77+
await service.apply(config, plan)
78+
```
79+
80+
This is the same reading the planner itself used to decide the drop, so the two cannot
81+
disagree.
82+
5183
## The grace period
5284

5385
```python
@@ -112,8 +144,15 @@ if await metadata.is_partition_closed(partition_name, settle_seconds=900):
112144
```
113145

114146
The check runs `now()` on the server, so replica lag and application clock skew do not
115-
skew it. With an encoded key (UUIDv7, epoch) pass the codec to
116-
`PostgresMetadataProvider(boundary_codec=…)`.
147+
skew it. Reading a bound back needs the same timezone and codec that wrote it, so hand it
148+
the table's own boundaries and the question cannot be asked with the wrong ones:
149+
150+
```python
151+
await metadata.is_partition_closed(name, settle_seconds=900, boundaries=config.time_boundaries)
152+
```
153+
154+
Without that argument the provider's own `ddl_timezone` and `boundary_codec` decide, which
155+
is only safe if they were constructed to match the table.
117156

118157
## Cold tiering instead of dropping
119158

‎docs/guide/extending.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,11 @@ class ReplicaMetadata(PostgresMetadataProvider):
7070
super().__init__(replica_engine, **kwargs)
7171
```
7272

73-
Constructor knobs: `marker_prefix` (pass the repository's), `boundary_codec` (only for
74-
`is_partition_closed`), `ddl_timezone` (for reading naive bounds).
73+
Constructor knobs: `marker_prefix` (pass the repository's — the service refuses a pair
74+
that disagrees), `boundary_codec` (only for `is_partition_closed`), `ddl_timezone` (for
75+
reading naive bounds). Rather than keeping the last two in step with each table by hand,
76+
pass the table's boundaries to the one method that uses them:
77+
`is_partition_closed(name, boundaries=config.time_boundaries)`.
7578

7679
The protocol's reads: `get_partition_type`, `get_partition_columns`, `get_actual_tree`,
7780
`measure`, `get_partition_tree`, `get_default_partition`, `partition_exists`,

‎docs/reference/configuration.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,12 @@ drop_max_retries=3, drop_retry_delay=0.5, drop_max_backoff=300)`.
144144
`PostgresMetadataProvider(engine, *, marker_prefix=None, boundary_codec=None,
145145
ddl_timezone=None)`.
146146

147+
`marker_prefix` must be the same on the repository and the provider — the first writes the
148+
ownership marker, the second finds it — and `PartitionLifecycleService` refuses a pair that
149+
disagrees. The provider's `boundary_codec` and `ddl_timezone` are used by
150+
`is_partition_closed` alone, which also takes `boundaries=config.time_boundaries` and reads
151+
both from there instead.
152+
147153
`PostgresAdvisoryLockManager(engine, prefix="partitioner", acquire_min_interval_seconds=0)`;
148154
`RedisDistributedLockManager(redis_client, prefix="partitioner:lock", ttl_seconds=300,
149155
acquire_min_interval_seconds=0)`.

‎pg_partsmith/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@
9393
from .protocols import (
9494
BoundaryDecoder,
9595
DdlTimezoneAware,
96+
OrphanMarkerAware,
9697
PeriodCalculator,
9798
PositionedCalculator,
9899
TimezoneAwareCalculator,
@@ -171,6 +172,7 @@
171172
"Operation",
172173
"OperationCapabilities",
173174
"OperationKind",
175+
"OrphanMarkerAware",
174176
"PartitionAlreadyExistsError",
175177
"PartitionAttachedError",
176178
"PartitionBounds",

‎pg_partsmith/aio/metadata.py‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555
if TYPE_CHECKING:
5656
from sqlalchemy.ext.asyncio import AsyncEngine
5757

58-
from pg_partsmith.boundaries import RangeBoundaryCodec
58+
from pg_partsmith.boundaries import RangeBoundaryCodec, TimeBoundaries
5959
from pg_partsmith.lifecycle import SqlPredicate
6060

6161

@@ -104,6 +104,11 @@ def __init__(
104104
self._boundary_codec = boundary_codec
105105
self._ddl_timezone = ddl_timezone
106106

107+
@property
108+
def marker_prefix(self) -> str:
109+
"""Prefix of the COMMENT marker orphan discovery looks for."""
110+
return self._marker_prefix
111+
107112
# ── The root ────────────────────────────────────────────────────────────────
108113

109114
async def get_partition_type(self, table_name: str) -> PartitionType | None:
@@ -577,7 +582,9 @@ async def get_partition_boundaries(self, partition_name: str) -> tuple[str, str]
577582

578583
return None
579584

580-
async def is_partition_closed(self, partition_name: str, *, settle_seconds: int = 0) -> bool:
585+
async def is_partition_closed(
586+
self, partition_name: str, *, settle_seconds: int = 0, boundaries: TimeBoundaries | None = None
587+
) -> bool:
581588
"""True when the partition's upper bound (+ settle buffer) has passed.
582589
583590
``now()`` is evaluated on the server rather than on the client, so the
@@ -590,27 +597,37 @@ async def is_partition_closed(self, partition_name: str, *, settle_seconds: int
590597
subtree closes with it.
591598
592599
A naive bound -- which is what a ``timestamp`` or ``date`` key produces
593-
-- is resolved under this provider's ``ddl_timezone``. Configure it with
594-
the same value the repository writes partitions with, or the two
595-
disagree about when the bound falls.
600+
-- is resolved under this provider's ``ddl_timezone``, and an encoded
601+
bound is read with its ``boundary_codec``. Both have to match what wrote
602+
the partition, so the simplest way to ask is to hand over the table's
603+
own ``TimeBoundaries``: it is the object that decided the calendar, the
604+
timezone and the encoding in the first place, and it overrides whatever
605+
this provider was constructed with.
596606
597607
Args:
598608
partition_name: Attached partition table name.
599609
settle_seconds: Extra buffer after the upper bound for late writers
600610
still holding open transactions.
611+
boundaries: The RANGE boundaries of the table this partition belongs
612+
to -- ``config.time_boundaries``. When given, its timezone and
613+
codec are used instead of this provider's, which is the way to
614+
be sure reader and writer agree.
601615
602616
Returns:
603617
True when ``now() >= upper_bound + settle_seconds``. False for the
604618
DEFAULT partition, non-RANGE partitions, unbounded upper bounds
605619
(MAXVALUE / infinity), detached tables, unresolvable names, and
606620
boundaries that carry no instant this provider can read.
607621
"""
622+
ddl_timezone = boundaries.timezone_name if boundaries is not None else self._ddl_timezone
623+
codec = boundaries.codec if boundaries is not None else self._boundary_codec
624+
608625
async with self._engine.connect() as conn:
609-
if self._ddl_timezone is not None:
626+
if ddl_timezone is not None:
610627
# A naive bound is resolved by the session timezone, so this has
611628
# to be the one the partition was written with. Without it the
612629
# server default decides, and the two need not agree.
613-
await conn.execute(text(f"SET LOCAL TIME ZONE {quote_literal(self._ddl_timezone)}"))
630+
await conn.execute(text(f"SET LOCAL TIME ZONE {quote_literal(ddl_timezone)}"))
614631

615632
bound_result = await conn.execute(
616633
text(PARTITION_UPPER_BOUND_SQL),
@@ -621,8 +638,8 @@ async def is_partition_closed(self, partition_name: str, *, settle_seconds: int
621638
# No upper bound to read: DEFAULT, non-RANGE, detached, or unknown.
622639
return False
623640

624-
if self._boundary_codec is not None:
625-
instant = self._boundary_codec.decode(raw_bound)
641+
if codec is not None:
642+
instant = codec.decode(raw_bound)
626643
if instant is None:
627644
self._warn_unreadable_bound(partition_name, raw_bound)
628645
return False

‎pg_partsmith/aio/repositories/repository.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def __init__(
5454
drop_retry_delay: float = DEFAULT_DROP_RETRY_DELAY,
5555
drop_max_backoff: float = DEFAULT_DROP_MAX_BACKOFF,
5656
) -> None:
57-
marker_prefix = orphan_comment_prefix(marker_prefix=marker_prefix)
57+
marker_prefix = self._marker_prefix = orphan_comment_prefix(marker_prefix=marker_prefix)
5858
ddl_timeout_seconds = validate_ddl_timeout(ddl_timeout_seconds)
5959
self._ddl_timezone = validate_timezone(ddl_timezone)
6060
drop_lock_timeout_ms = validate_int(drop_lock_timeout_ms, "drop_lock_timeout_ms", min_val=0)
@@ -84,6 +84,11 @@ def __init__(
8484
allow_unmanaged=bool(drop_allow_unmanaged),
8585
)
8686

87+
@property
88+
def marker_prefix(self) -> str:
89+
"""Prefix of the COMMENT marker stamped on detach and verified before a drop."""
90+
return self._marker_prefix
91+
8792
@property
8893
def ddl_timezone(self) -> str | None:
8994
"""Timezone applied via ``SET LOCAL TIME ZONE`` around boundary-sensitive DDL.

0 commit comments

Comments
 (0)