Skip to content

Commit 6f5e742

Browse files
feat: the closed check, on the protocol (#56)
is_partition_closed(name, *, settle_seconds=0, boundaries=None) is a method of PartitionMetadataProvider in both mirrors. It was always the export pipeline's question: the archiving guide is written around it, and PartitionToolkit.from_engine takes a boundary_codec for that one call. But only the Postgres provider declared it, and the toolkit hands its provider back under the protocol's type, so under a type checker kit.metadata.is_partition_closed did not exist and a caller narrowed with isinstance first -- which is what the toolkit was built to make unnecessary. A provider of your own now has to answer it, the way the Postgres one does: True once the upper bound plus the settle buffer has passed on the database's clock, False rather than an exception when the bound cannot be read. A test holds every protocol method to the Postgres implementation's signature, in both mirrors, so the next method to land on the implementation alone is caught there.
1 parent 35a937a commit 6f5e742

7 files changed

Lines changed: 185 additions & 5 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,22 @@ 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.4.0 — the closed check, on the protocol
9+
10+
`is_partition_closed(partition_name, *, settle_seconds=0, boundaries=None)` is a method of
11+
`PartitionMetadataProvider` in both mirrors. It was always the export pipeline's question —
12+
the archiving guide has a section for it, and `PartitionToolkit.from_engine` takes a
13+
`boundary_codec` for that one call — but only the Postgres provider declared it, and the
14+
toolkit hands its provider back under the protocol's type. So under a type checker
15+
`kit.metadata.is_partition_closed(...)` did not exist, and a caller narrowed with
16+
`isinstance` first, which is what the toolkit was built to make unnecessary.
17+
18+
A provider of your own now has to answer it. The contract is the Postgres one: True once
19+
the partition's upper bound plus the settle buffer has passed on the database's clock;
20+
False, never an exception, when the bound cannot be read — a DEFAULT partition, a non-RANGE
21+
one, an unbounded upper bound, a bound the codec cannot decode, a detached table, a name
22+
that does not resolve.
23+
824
## [1.3.0](https://github.com/bedrock-python/pg-partsmith/compare/pg-partsmith-v1.2.0...pg-partsmith-v1.3.0) (2026-09-03)
925

1026

‎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_unique_constraint_columns`, `get_key_high_water_mark(table, column, *, sequence=False)`, `get_leading_key_minimum(table, key_columns)`, `list_partitions`. Plus on the Postgres implementation: `get_partition_column` (single-column only), `get_partition_boundaries`, `is_partition_closed`, `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). 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: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,10 @@ pass the table's boundaries to the one method that uses them:
7878

7979
The protocol's reads: `get_partition_type`, `get_partition_columns`, `get_actual_tree`,
8080
`measure`, `get_partition_tree`, `get_default_partition`, `partition_exists`,
81-
`is_partition_attached`, `get_relation_oid`, `get_unique_constraint_columns`,
82-
`get_key_high_water_mark`, `get_leading_key_minimum`, `list_partitions`.
81+
`is_partition_attached`, `get_relation_oid`, `get_relation_kind`,
82+
`get_unique_constraint_columns`, `get_key_high_water_mark`, `get_leading_key_minimum`,
83+
`list_partitions`, and `is_partition_closed`, which a provider of your own answers with
84+
False rather than an exception when it cannot read the bound.
8385

8486
## A lock manager
8587

‎docs/guide/migration.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -128,5 +128,6 @@ p.schema_name # "public"
128128

129129
`metadata.is_partition_closed(name, settle_seconds=900)` answers "can this partition
130130
still receive in-range rows?" with one server-side check — `now()` is evaluated in the
131-
database, so replica lag and application clock skew do not skew the answer. With an
132-
encoded key pass the codec to the metadata provider.
131+
database, so replica lag and application clock skew do not skew the answer. Hand it the
132+
table's own boundaries, `boundaries=config.time_boundaries`, so the bound is read with the
133+
timezone and codec that wrote it.

‎pg_partsmith/aio/protocols.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from contextlib import AbstractAsyncContextManager
1919
from typing import Any, Protocol, runtime_checkable
2020

21+
from pg_partsmith.boundaries import TimeBoundaries
2122
from pg_partsmith.entities import MaintenanceResult, PartitionInfo, TablePartitionConfig
2223
from pg_partsmith.leaves import LocalLeaves
2324
from pg_partsmith.lifecycle import DetachMode, SqlPredicate
@@ -367,6 +368,29 @@ async def list_partitions(self, table_name: str) -> list[PartitionInfo]:
367368
"""List the direct partitions of a table, including its marker-tagged orphans."""
368369
...
369370

371+
async def is_partition_closed(
372+
self, partition_name: str, *, settle_seconds: int = 0, boundaries: TimeBoundaries | None = None
373+
) -> bool:
374+
"""True when the partition can no longer receive in-range rows.
375+
376+
The question an export pipeline asks before it finalizes: has the
377+
partition's upper bound, plus ``settle_seconds`` for writers still
378+
holding open transactions, passed on the database's own clock? A
379+
provider that cannot read the bound -- a DEFAULT partition, a
380+
non-RANGE one, an unbounded upper bound, a bound the codec cannot
381+
decode, a detached table, a name that does not resolve -- answers
382+
False rather than raising.
383+
384+
Args:
385+
partition_name: Attached partition table name.
386+
settle_seconds: Extra buffer after the upper bound.
387+
boundaries: The RANGE boundaries of the table the partition
388+
belongs to -- ``config.time_boundaries``. When given, its
389+
timezone and codec read the bound instead of whatever the
390+
provider was constructed with.
391+
"""
392+
...
393+
370394

371395
@runtime_checkable
372396
class LockManager(Protocol):

‎pg_partsmith/sync/protocols.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
from contextlib import AbstractContextManager
1919
from typing import Any, Protocol, runtime_checkable
2020

21+
from pg_partsmith.boundaries import TimeBoundaries
2122
from pg_partsmith.entities import MaintenanceResult, PartitionInfo, TablePartitionConfig
2223
from pg_partsmith.leaves import LocalLeaves
2324
from pg_partsmith.lifecycle import DetachMode, SqlPredicate
@@ -367,6 +368,29 @@ def list_partitions(self, table_name: str) -> list[PartitionInfo]:
367368
"""List the direct partitions of a table, including its marker-tagged orphans."""
368369
...
369370

371+
def is_partition_closed(
372+
self, partition_name: str, *, settle_seconds: int = 0, boundaries: TimeBoundaries | None = None
373+
) -> bool:
374+
"""True when the partition can no longer receive in-range rows.
375+
376+
The question an export pipeline asks before it finalizes: has the
377+
partition's upper bound, plus ``settle_seconds`` for writers still
378+
holding open transactions, passed on the database's own clock? A
379+
provider that cannot read the bound -- a DEFAULT partition, a
380+
non-RANGE one, an unbounded upper bound, a bound the codec cannot
381+
decode, a detached table, a name that does not resolve -- answers
382+
False rather than raising.
383+
384+
Args:
385+
partition_name: Attached partition table name.
386+
settle_seconds: Extra buffer after the upper bound.
387+
boundaries: The RANGE boundaries of the table the partition
388+
belongs to -- ``config.time_boundaries``. When given, its
389+
timezone and codec read the bound instead of whatever the
390+
provider was constructed with.
391+
"""
392+
...
393+
370394

371395
@runtime_checkable
372396
class LockManager(Protocol):

‎tests/unit/test_protocols.py‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
"""What a protocol promises is what the Postgres implementation provides, in both mirrors.
2+
3+
A toolkit hands its parts back under the protocols' types, so a method the
4+
implementation has and the protocol lacks is one a caller cannot reach
5+
without narrowing first -- which is what happened to ``is_partition_closed``.
6+
Both directions are held here: every protocol method exists on the
7+
implementation with the same signature, and every public method of the
8+
implementation is on the protocol unless it is listed as the implementation's
9+
own.
10+
"""
11+
12+
from __future__ import annotations
13+
14+
import inspect
15+
from typing import Any
16+
from unittest.mock import MagicMock
17+
18+
import pytest
19+
20+
from pg_partsmith.aio import metadata as aio_metadata
21+
from pg_partsmith.aio import protocols as aio_protocols
22+
from pg_partsmith.aio import repositories as aio_repositories
23+
from pg_partsmith.sync import metadata as sync_metadata
24+
from pg_partsmith.sync import protocols as sync_protocols
25+
from pg_partsmith.sync import repositories as sync_repositories
26+
27+
# Reads only the Postgres provider offers; a caller that wants them narrows to it on purpose.
28+
POSTGRES_ONLY = frozenset({"evaluate_sql_predicate", "get_partition_boundaries", "get_partition_column"})
29+
30+
PAIRS = [
31+
pytest.param(
32+
aio_protocols.PartitionMetadataProvider,
33+
aio_metadata.PostgresMetadataProvider,
34+
POSTGRES_ONLY,
35+
id="aio-metadata",
36+
),
37+
pytest.param(
38+
sync_protocols.PartitionMetadataProvider,
39+
sync_metadata.PostgresMetadataProvider,
40+
POSTGRES_ONLY,
41+
id="sync-metadata",
42+
),
43+
pytest.param(
44+
aio_protocols.PartitionRepository,
45+
aio_repositories.PostgresPartitionRepository,
46+
frozenset(),
47+
id="aio-repository",
48+
),
49+
pytest.param(
50+
sync_protocols.PartitionRepository,
51+
sync_repositories.PostgresPartitionRepository,
52+
frozenset(),
53+
id="sync-repository",
54+
),
55+
]
56+
57+
METADATA_PROTOCOLS = [
58+
pytest.param(aio_protocols.PartitionMetadataProvider, id="aio"),
59+
pytest.param(sync_protocols.PartitionMetadataProvider, id="sync"),
60+
]
61+
62+
63+
def _methods(cls: type[Any]) -> set[str]:
64+
"""The public functions declared on the class itself; a property is not a protocol member here."""
65+
return {name for name, member in vars(cls).items() if inspect.isfunction(member) and not name.startswith("_")}
66+
67+
68+
@pytest.mark.parametrize(("protocol", "implementation", "implementation_only"), PAIRS)
69+
def test__protocol__every_method__is_implemented_with_the_same_signature(
70+
protocol: type[Any], implementation: type[Any], implementation_only: frozenset[str]
71+
) -> None:
72+
# Arrange
73+
names = sorted(_methods(protocol))
74+
75+
# Act -- both files start with ``from __future__ import annotations``, so the signatures compare
76+
# as written: the sync mirror is generated textually from aio, and a spelling that drifts is a
77+
# mirror that drifted.
78+
drift = {
79+
name: (str(inspect.signature(getattr(protocol, name))), str(inspect.signature(getattr(implementation, name))))
80+
for name in names
81+
if inspect.signature(getattr(protocol, name)) != inspect.signature(getattr(implementation, name))
82+
}
83+
84+
# Assert
85+
assert names, "an empty protocol promises nothing"
86+
assert drift == {}
87+
assert isinstance(implementation(MagicMock()), protocol)
88+
assert not implementation_only & set(names), "on the protocol and the implementation's own at once"
89+
90+
91+
@pytest.mark.parametrize(("protocol", "implementation", "implementation_only"), PAIRS)
92+
def test__implementation__every_public_method__is_on_the_protocol_or_listed_as_its_own(
93+
protocol: type[Any], implementation: type[Any], implementation_only: frozenset[str]
94+
) -> None:
95+
# Arrange / Act
96+
unreachable = _methods(implementation) - _methods(protocol) - implementation_only
97+
98+
# Assert
99+
assert unreachable == set(), "reachable only after narrowing to the implementation"
100+
assert implementation_only <= _methods(implementation), "the list names a method that is gone"
101+
102+
103+
@pytest.mark.parametrize("protocol", METADATA_PROTOCOLS)
104+
def test__metadata_protocol__the_closed_check__is_askable_through_it(protocol: type[Any]) -> None:
105+
# Arrange / Act
106+
member = vars(protocol).get("is_partition_closed")
107+
108+
# Assert
109+
assert member is not None, "a toolkit's provider is typed as the protocol; the export question must be on it"
110+
signature = inspect.signature(member)
111+
assert list(signature.parameters) == ["self", "partition_name", "settle_seconds", "boundaries"]
112+
assert signature.parameters["settle_seconds"].default == 0
113+
assert signature.parameters["boundaries"].default is None

0 commit comments

Comments
 (0)