Skip to content

Commit 38d8c23

Browse files
committed
fix: close the review findings on the hook event
Signature validation had a false positive and a false negative. A hook using functools.singledispatchmethod reports (self, event) even when bound, so judging by arity alone refused a hook written exactly right; a method taking no event at all passed and failed at its first call. Both are gone: a leading self or cls is dropped, then the signature is asked whether it can be called with one event, which accepts (event), (*args) and (event, extra=None) alike. on_event now runs before the method named for the phase. It used to run after, so a before_* hook that refused an operation by raising left an audit trail with nothing in it -- the one case an audit hook most wants recorded. An attach is counted before after_attach fires, as a creation already was, so a failing notification no longer makes the result disagree with the database. (detach and drop have the same shape and count after their hook; that is 1.0 behaviour and needs the tally to move into the executor's own methods, so it is left for its own change.) The three event builders take the config: DEFAULT bounds say nothing about the parent's method -- every method may have one -- and were reported as RANGE, so a DEFAULT member of a LIST root lied about its parent. _parent_method now answers None where the bounds do not say and the configured root decides. The attach event also names how the partition will divide its own children, which it knew from the operation and threw away. is_naive_timestamp_literal no longer reads reduced ISO forms as timestamps: "2024-01", "2024-W01" and "2024-001" are values a text or encoded key really has, and they were drawing a timezone warning meant for real timestamps. Docs: the ported hook example in the agent page still called the old parameter, three places still showed the table-name argument these methods no longer take, and the README example annotated a type it did not import. Four integration call sites were still passing a table name where the config now goes -- they only worked because no hooks were registered there. Refs #27.
1 parent 0ddff78 commit 38d8c23

24 files changed

Lines changed: 362 additions & 87 deletions

‎CHANGELOG.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ now takes one `PartitionEvent`:
3838
| `before_drop(table_name, partition_name)` | `before_drop(event)` — and now `event.window`, `event.operation.reason` |
3939
| `after_drop(table_name, partition_name)` | `after_drop(event)` |
4040
| — | `before_attach(event)` / `after_attach(event)`, new: a detached partition going back into the tree |
41-
| — | `on_event(event)`, new: fires for every phase in addition to the method named for it |
41+
| — | `on_event(event)`, new: fires for every phase, just before the method named for it |
4242

4343
### Also breaking, in the same area
4444

@@ -53,7 +53,9 @@ now takes one `PartitionEvent`:
5353

5454
- `PartitionEvent`, `HookPhase` (exported from `pg_partsmith`), and `on_event` — one
5555
method for an audit trail or a metrics counter across every phase, instead of one
56-
identical delegating method per phase, plus another with every phase added.
56+
identical delegating method per phase, plus another with every phase added. It runs
57+
before the method named for the phase, so a `before_*` that refuses an operation by
58+
raising still leaves the audit trail with the attempt in it.
5759
- `before_attach` / `after_attach`: a partition retention released is re-attached when its
5860
window is wanted again — retention grew, or create-ahead reached back to it — and that
5961
transition used to happen silently. An export taken while it was detached goes stale the

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@ Two behavioural differences: `ddl_timeout_seconds` is enforced server-side via
223223
## Hooks
224224

225225
```python
226+
from pg_partsmith import PartitionEvent
226227
from pg_partsmith.aio import BasePartitionLifecycleHooks
227228

228229

‎docs/agents.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -239,8 +239,8 @@ Every method takes the `TablePartitionConfig` as its first argument.
239239
| `unpartition(config, into, *, batch_rows=10_000, max_batches=None, drop_emptied=False)` | **yes** | yes | `MigrationResult` |
240240
| `create_future_partitions(config)` | no | yes | `list[PartitionInfo]` |
241241
| `get_partitions_for_pruning(config)` | no | no | `list[PartitionInfo]` |
242-
| `detach_old_partitions(table_name, partitions)` | no | yes | `list[str]` |
243-
| `drop_detached_partitions(table_name, partition_names)` | no | yes | `int` |
242+
| `detach_old_partitions(config, partitions)` | no | yes | `list[str]` |
243+
| `drop_detached_partitions(config, partition_names)` | no | yes | `int` |
244244

245245
`maintain_lifecycle` is the same method as `maintain`. `PartitionMaintainer(service)` adds
246246
`run_maintenance(...)` and `run_maintenance_safe(...)` — same keywords; the *safe* one never
@@ -269,7 +269,7 @@ Results:
269269
```python
270270
class ColdStorageHooks(BasePartitionLifecycleHooks):
271271
async def before_drop(self, event: PartitionEvent) -> None:
272-
await export(partition_name) # raising aborts this drop; it is retried next tick
272+
await export(event.partition.name) # raising aborts this drop; it is retried next tick
273273
```
274274

275275
Nine methods, each taking one `PartitionEvent(phase, config, partition, window, operation)`:

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ TablePartitionConfig(table_name="regions", scheme=ListPartitioning(key="region",
4646

4747
Service wiring: `PartitionLifecycleService(repo, metadata, locks, hooks=None)` — **no `period_calculator` argument**; the calculator/tz/codec live in `TimeBoundaries`. `PostgresMetadataProvider(engine, marker_prefix=, boundary_codec=, ddl_timezone=)` (codec only for `is_partition_closed`).
4848

49-
Service methods: `inspect(config) -> ActualTree | None`, `plan(config, *, mode=, now=, windows=) -> MaintenancePlan` (no lock, no DDL), `apply(config, plan, *, continue_on_error=) -> MaintenanceResult` (lock), `maintain(config, *, skip_create, skip_detach, skip_drop, continue_on_error)` (= `maintain_lifecycle`, lock; plan + apply), `reconcile(config)`, `ensure_partition(config, period|Window) -> PartitionInfo | None`, `ensure_partitions(config, periods) -> list[PartitionInfo]`, granular `create_future_partitions(config)`, `get_partitions_for_pruning(config)`, `detach_old_partitions(table, partitions)`, `drop_detached_partitions(table, names)`; movers `partition_data(config, *, batch_rows, max_batches) -> MigrationResult` and `unpartition(config, into, *, batch_rows, max_batches, drop_emptied)` (both take the lock).
49+
Service methods: `inspect(config) -> ActualTree | None`, `plan(config, *, mode=, now=, windows=) -> MaintenancePlan` (no lock, no DDL), `apply(config, plan, *, continue_on_error=) -> MaintenanceResult` (lock), `maintain(config, *, skip_create, skip_detach, skip_drop, continue_on_error)` (= `maintain_lifecycle`, lock; plan + apply), `reconcile(config)`, `ensure_partition(config, period|Window) -> PartitionInfo | None`, `ensure_partitions(config, periods) -> list[PartitionInfo]`, granular `create_future_partitions(config)`, `get_partitions_for_pruning(config)`, `detach_old_partitions(config, partitions)`, `drop_detached_partitions(config, names)` (both took the parent's name until 1.1); movers `partition_data(config, *, batch_rows, max_batches) -> MigrationResult` and `unpartition(config, into, *, batch_rows, max_batches, drop_emptied)` (both take the lock).
5050

5151
Executor (`aio/services/execution.py` `PlanExecutor(repo, metadata, hooks)`): `apply(config, plan, continue_on_error)`, extension points `create_partition(config, plan, op, *, issues, fill=None) -> bool`, `detach_single_partition(config, DetachPartition)`, `drop_single_partition(config, DropPartition)` (both took the parent's name until 1.1). Mover (`services/migration.py` `DataMover(repo, metadata, executor)`). Inspector (`services/inspection.py` `PartitionInspector(metadata)`): `inspect(config, measure=)`, `context(config, now=, mode=, explicit_windows=)`. Validation unchanged in spirit (`PartitionValidationService(metadata).validate_config(config)`).
5252

‎docs/guide/archiving.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ drop=DropNever()
149149

150150
Expired partitions are detached, marked, and left alone. A cold-storage pipeline or a DBA
151151
owns them from there: `list_partitions` reports them with `is_attached=False`, and
152-
`drop_detached_partitions(table, names)` drops them on request through the same guarded
152+
`drop_detached_partitions(config, names)` drops them on request through the same guarded
153153
path. Under `DropNever` orphans are never re-attached either — they belong to whatever
154154
process the policy hands them to.
155155

‎pg_partsmith/aio/hooks.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,10 @@ async def before_attach(self, event: PartitionEvent) -> None:
101101
is about to go stale: this is where to say so. Raising aborts the
102102
attach; the relation stays detached and the next run plans it again.
103103
104+
The guarantee is that *this run* has not attached it yet, not that
105+
nothing else has: a partition someone else attached under the planned
106+
name in the meantime is recognised as a benign race after this fires.
107+
104108
Args:
105109
event: The partition about to go live, its subtree already
106110
complete.

‎pg_partsmith/aio/services/execution.py‎

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -410,13 +410,13 @@ async def _attach_detached(
410410
# same relation before it goes live (the attach re-checks under
411411
# its own lock either way).
412412
await self._require_same_relation(op.target, op.oid)
413-
info = _attach_info(op)
413+
info = _attach_info(config, op)
414414
await self._fire(HookPhase.BEFORE_ATTACH, config, info, op)
415415
await self._attach_with_reconcile(
416416
config, op.parent_name, op.target, op.bounds, key_columns=op.key_columns, expected_oid=op.oid
417417
)
418-
await self._fire(HookPhase.AFTER_ATTACH, config, info.model_copy(update={"is_attached": True}), op)
419418
tally.attached += 1
419+
await self._fire(HookPhase.AFTER_ATTACH, config, info.model_copy(update={"is_attached": True}), op)
420420
return True
421421

422422
async def _attach_with_reconcile(
@@ -652,7 +652,7 @@ async def detach_single_partition(self, config: TablePartitionConfig, op: Detach
652652
if not await self._metadata.is_partition_attached(op.parent_name, op.target):
653653
raise PlanStaleError(op.target, f"it is no longer attached to {op.parent_name}")
654654

655-
info = _detach_info(op)
655+
info = _detach_info(config, op)
656656
await self._fire(HookPhase.BEFORE_DETACH, config, info, op)
657657
await self._repo.detach_partition(op.parent_name, op.target, mode=op.mode, expected_oid=op.oid)
658658
await self._fire(HookPhase.AFTER_DETACH, config, info.model_copy(update={"is_attached": False}), op)
@@ -673,7 +673,7 @@ async def drop_single_partition(
673673
without a drain) when the partition was dropped; None when it is
674674
still attached (logged and skipped).
675675
"""
676-
info = _drop_info(op)
676+
info = _drop_info(config, op)
677677
await self._fire(HookPhase.BEFORE_DROP, config, info, op)
678678
try:
679679
drained = await self._repo.drop_partition(op.target, expected_oid=op.oid, drain_into=drain_into)
@@ -704,17 +704,19 @@ async def _fire(
704704
partition: PartitionInfo,
705705
operation: Operation,
706706
) -> None:
707-
"""Hand one event to the method named after its phase, and to ``on_event``.
707+
"""Hand one event to ``on_event``, then to the method named after its phase.
708708
709-
Both, always: the named method is where a hook does something to one
710-
moment, ``on_event`` is where it watches all of them. A hook that
711-
implements both is called twice on purpose.
709+
That order is the contract: ``on_event`` sees every event the library
710+
reaches, and the named method -- where a hook does something about one
711+
moment, and where a ``before_*`` may refuse it by raising -- runs after.
712+
Were it the other way round, a refusal would leave an audit trail with
713+
nothing in it. A hook implementing both is called twice, on purpose.
712714
"""
713715
if not self._hooks:
714716
return
715717
event = PartitionEvent.build(phase, config, partition, operation)
716-
await self._run_hooks(lambda h: getattr(h, phase.value)(event), phase.value, partition_name=partition.name)
717718
await self._run_hooks(lambda h: h.on_event(event), "on_event", partition_name=partition.name)
719+
await self._run_hooks(lambda h: getattr(h, phase.value)(event), phase.value, partition_name=partition.name)
718720

719721
async def _run_hooks(
720722
self,
@@ -775,7 +777,7 @@ def _step_of(op: Operation) -> MaintenanceIssueStep:
775777
return MaintenanceIssueStep.DROP
776778

777779

778-
def _detach_info(op: DetachPartition) -> PartitionInfo:
780+
def _detach_info(config: TablePartitionConfig, op: DetachPartition) -> PartitionInfo:
779781
"""What hooks see of a partition about to be detached.
780782
781783
Built without validation: the plan may know the partition only by name and
@@ -790,7 +792,7 @@ def _detach_info(op: DetachPartition) -> PartitionInfo:
790792
return PartitionInfo.model_construct(
791793
name=op.target,
792794
oid=op.oid,
793-
partition_type=_parent_method(bounds),
795+
partition_type=_parent_method(bounds) or config.partition_type,
794796
from_value=from_value,
795797
to_value=to_value,
796798
boundaries_expr=None if bounds is None else bounds.kind,
@@ -803,7 +805,7 @@ def _detach_info(op: DetachPartition) -> PartitionInfo:
803805
)
804806

805807

806-
def _attach_info(op: AttachPartition) -> PartitionInfo:
808+
def _attach_info(config: TablePartitionConfig, op: AttachPartition) -> PartitionInfo:
807809
"""What hooks see of a detached partition on its way back into the tree."""
808810
bounds = op.bounds
809811
from_value = to_value = None
@@ -812,20 +814,20 @@ def _attach_info(op: AttachPartition) -> PartitionInfo:
812814
return PartitionInfo.model_construct(
813815
name=op.target,
814816
oid=op.oid,
815-
partition_type=_parent_method(bounds),
817+
partition_type=_parent_method(bounds) or config.partition_type,
816818
from_value=from_value,
817819
to_value=to_value,
818820
boundaries_expr=bounds.kind,
819821
bounds=bounds,
820822
is_attached=False,
821823
is_default=bounds.kind == "default",
822824
relkind=RelationKind.TABLE,
823-
subpartition_type=None,
825+
subpartition_type=None if op.partition_by is None else op.partition_by.method,
824826
parent_table=op.parent_name,
825827
)
826828

827829

828-
def _drop_info(op: DropPartition) -> PartitionInfo:
830+
def _drop_info(config: TablePartitionConfig, op: DropPartition) -> PartitionInfo:
829831
"""What hooks see of a partition about to be dropped.
830832
831833
Detached by definition, and by then the catalog no longer records where it
@@ -839,7 +841,7 @@ def _drop_info(op: DropPartition) -> PartitionInfo:
839841
return PartitionInfo.model_construct(
840842
name=op.target,
841843
oid=op.oid,
842-
partition_type=_parent_method(bounds),
844+
partition_type=_parent_method(bounds) or config.partition_type,
843845
from_value=from_value,
844846
to_value=to_value,
845847
boundaries_expr=None if bounds is None else bounds.kind,
@@ -867,8 +869,16 @@ def _partition_info(config: TablePartitionConfig, op: CreatePartition) -> Partit
867869
)
868870

869871

870-
def _parent_method(bounds: PartitionBounds | None) -> PartitionType:
871-
if bounds is None or bounds.kind in {"range", "default"}:
872+
def _parent_method(bounds: PartitionBounds | None) -> PartitionType | None:
873+
"""How the parent partitions a relation with these bounds, when they say.
874+
875+
A DEFAULT partition's bounds say nothing about its parent's method -- every
876+
method may have one -- and neither does a partition the plan knows only by
877+
name. Both answer None, and the caller falls back to the configured root.
878+
"""
879+
if bounds is None or bounds.kind == "default":
880+
return None
881+
if bounds.kind == "range":
872882
return PartitionType.RANGE
873883
return PartitionType.HASH if bounds.kind == "hash" else PartitionType.LIST
874884

‎pg_partsmith/events.py‎

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,9 @@ def _window_of(config: TablePartitionConfig, bounds: PartitionBounds | None) ->
123123
HOOK_METHODS: tuple[str, ...] = (*(phase.value for phase in HookPhase), "on_event")
124124
"""Every method a hook may implement: one per phase, plus the catch-all."""
125125

126+
_EVENT_PLACEHOLDER = object()
127+
"""Stands in for the event while a hook's signature is tried against it."""
128+
126129

127130
def validate_hook_signatures(hooks: Iterable[object]) -> None:
128131
"""Refuse a hook whose methods still take the arguments they took before 1.1.
@@ -134,33 +137,35 @@ def validate_hook_signatures(hooks: Iterable[object]) -> None:
134137
middle of a maintenance run and after some of its DDL had committed.
135138
Reading the signature at wiring time turns that into a refusal to start.
136139
137-
Methods whose signature cannot be read (built-ins, mocks, anything taking
138-
``*args``) are left alone rather than guessed at.
140+
The test is whether the method can be called with one event and nothing
141+
else, which accepts ``(event)``, ``(*args)`` and ``(event, extra=None)``
142+
alike. Some descriptors -- ``functools.singledispatchmethod`` among them --
143+
report their receiver even when bound, so a leading ``self`` or ``cls`` is
144+
dropped before judging. Methods whose signature cannot be read (built-ins,
145+
mocks) are left alone rather than guessed at.
139146
140147
Raises:
141-
ValueError: If a hook method requires more than the event.
148+
ValueError: If a hook method cannot be called with one event.
142149
"""
143150
for hook in hooks:
144151
for name in HOOK_METHODS:
145152
method = getattr(hook, name, None)
146153
if method is None or not callable(method):
147154
continue
148155
try:
149-
parameters = inspect.signature(method).parameters.values()
156+
signature = inspect.signature(method)
150157
except (TypeError, ValueError):
151158
continue
152-
required = [
153-
parameter
154-
for parameter in parameters
155-
if parameter.kind in {parameter.POSITIONAL_ONLY, parameter.POSITIONAL_OR_KEYWORD}
156-
and parameter.default is parameter.empty
157-
]
158-
if len(required) > 1:
159-
taken = ", ".join(parameter.name for parameter in required)
159+
parameters = list(signature.parameters.values())
160+
if parameters and parameters[0].name in {"self", "cls"}:
161+
parameters = parameters[1:]
162+
try:
163+
signature.replace(parameters=parameters).bind(_EVENT_PLACEHOLDER)
164+
except TypeError:
160165
msg = (
161-
f"{type(hook).__name__}.{name} takes ({taken}); since 1.1 every hook method takes one "
162-
f"PartitionEvent. The event carries the config, the partition, the window it covers and "
163-
f"the operation: {name}(self, event) -> None, then event.partition.name, event.table_name, "
164-
f"event.window, event.operation.reason."
166+
f"{type(hook).__name__}.{name}{signature} cannot be called with one PartitionEvent; since 1.1 "
167+
f"every hook method takes exactly that: {name}(self, event) -> None. The event carries the "
168+
f"config, the partition, the window it covers and the operation -- event.partition.name, "
169+
f"event.table_name, event.window, event.operation.reason."
165170
)
166-
raise ValueError(msg)
171+
raise ValueError(msg) from None

‎pg_partsmith/partition_bounds.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
)
3434
_LIST_BOUND_PATTERN = re.compile(r"^\s*FOR\s+VALUES\s+IN\s*\((?P<values>.*)\)\s*$", re.IGNORECASE | re.DOTALL)
3535
_DATE_ONLY_PATTERN = re.compile(r"\d{4}-\d{2}-\d{2}")
36+
_DATE_PREFIX_PATTERN = re.compile(r"\d{4}-\d{2}-\d{2}[T ]")
3637

3738
# Bound spellings that carry no instant at all.
3839
_UNBOUNDED_LITERALS = frozenset({"MINVALUE", "MAXVALUE"})
@@ -267,7 +268,10 @@ def is_naive_timestamp_literal(value: str | None) -> bool:
267268
return False
268269
if _DATE_ONLY_PATTERN.fullmatch(v):
269270
return True
270-
if "-" not in v and ":" not in v:
271+
if not _DATE_PREFIX_PATTERN.match(v):
272+
# ``isoparse`` reads reduced forms -- "2024-01", "2024-W01", "2024-001" --
273+
# as timestamps, and a text or encoded key may well look like one. Only a
274+
# full calendar date is taken as evidence that this is a timestamp at all.
271275
return False
272276
try:
273277
parsed = isoparse(v)

‎pg_partsmith/sync/hooks.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,10 @@ def before_attach(self, event: PartitionEvent) -> None:
101101
is about to go stale: this is where to say so. Raising aborts the
102102
attach; the relation stays detached and the next run plans it again.
103103
104+
The guarantee is that *this run* has not attached it yet, not that
105+
nothing else has: a partition someone else attached under the planned
106+
name in the meantime is recognised as a benign race after this fires.
107+
104108
Args:
105109
event: The partition about to go live, its subtree already
106110
complete.

0 commit comments

Comments
 (0)