Skip to content

Commit 424a882

Browse files
fix: harden partition lifecycle against wedges, data-loss edges, and lock races (#16)
Complete cancelled DETACH CONCURRENTLY via FINALIZE; never prune MAXVALUE partitions; run DEFAULT reconciliation under the ATTACH timezone and return moved rows to DEFAULT when the attach ultimately fails; tolerate 42809 attach races while propagating 55006; escape colons in DDL literals; skip dotted relation names in list_partitions; parse only RANGE bounds; reject mixed-case partition columns up front; fix lock-manager rate limiting, Redis lock leak windows and cancellation swallowing; log operational PartitionErrors as warnings. Refactor Period onto a per-granularity spec table and derive calculator names/boundaries from Period itself (behavior unchanged).
1 parent 71305fb commit 424a882

42 files changed

Lines changed: 2048 additions & 352 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

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

88
## [Unreleased]
99

10+
### Fixed
11+
12+
- Detach: a partition left in `inhdetachpending` state by a cancelled
13+
`DETACH CONCURRENTLY` (e.g. a DDL timeout) is now completed with
14+
`DETACH PARTITION ... FINALIZE` instead of failing on every subsequent run.
15+
- Pruning: partitions with a `MAXVALUE` upper bound are never pruned any more —
16+
previously the unparseable boundary fell back to name-based ageing, which could
17+
drop a catch-all partition holding current data.
18+
- DEFAULT reconciliation now runs under the same `SET LOCAL TIME ZONE` as
19+
`ATTACH PARTITION`, so a non-UTC server timezone no longer moves the wrong row
20+
range; if the attach still fails after rows were reconciled, they are moved
21+
back to the DEFAULT partition (best effort) instead of being stranded in a
22+
detached table.
23+
- Attach race handling: SQLSTATE `42809` ("already a partition", the code
24+
PostgreSQL actually raises when a concurrent worker wins the attach) is now
25+
tolerated, while `55006` (partition mid-detach) correctly propagates instead of
26+
being mislabelled as "already attached".
27+
- DDL statements no longer break when an identifier or literal contains `:`
28+
(e.g. a pre-existing table comment) — colons are escaped before SQLAlchemy
29+
`text()` parses them as bind parameters.
30+
- `list_partitions` skips (with a warning) partitions whose schema or name
31+
contains a dot: such names cannot be addressed safely as `schema.relname`
32+
strings and previously produced DDL against the wrong relation.
33+
- Boundary parsing only applies to RANGE bound expressions; LIST/HASH bounds no
34+
longer yield fabricated from/to values.
35+
- Config validation rejects quoted mixed-case partition columns up front instead
36+
of failing later inside reconciliation SQL.
37+
- Lock managers: the per-table acquire rate limit no longer serializes unrelated
38+
tables (the delay is now slept outside the shared mutex) and no longer sleeps
39+
spuriously on the first acquire after host boot; the Redis lock is released
40+
even when the renewal watchdog fails to start; the async Redis lock no longer
41+
swallows an external task cancellation during watchdog teardown.
42+
- Maintainer logging: operational `PartitionError`s (e.g. lock contention) are
43+
logged as warnings instead of "unexpected exception" errors with tracebacks.
44+
45+
### Changed
46+
47+
- `Period` internals were restructured around a single per-granularity dispatch;
48+
behaviour is unchanged. Built-in calculators now derive names and boundaries
49+
from `Period` itself instead of duplicating the formatting and arithmetic.
50+
1051
### Added
1152

1253
- Hour and quarter partition granularities: `PartitionGranularity.HOUR` / `.QUARTER`,

‎docs/guide/configuration.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,11 +80,13 @@ partition_column="event_date"
8080
Controls which built-in period calculator to use when one is not passed explicitly.
8181

8282
```python
83-
class PartitionGranularity(str, Enum):
84-
DAY = "DAY"
85-
WEEK = "WEEK"
86-
MONTH = "MONTH"
87-
YEAR = "YEAR"
83+
class PartitionGranularity(StrEnum):
84+
HOUR = "hour"
85+
DAY = "day"
86+
WEEK = "week"
87+
MONTH = "month"
88+
QUARTER = "quarter"
89+
YEAR = "year"
8890
```
8991

9092
See [Period strategies](strategies.md) for details.

‎docs/guide/strategies.md‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,17 +48,25 @@ service = PartitionLifecycleService(
4848

4949
## Custom calculator
5050

51-
Subclass `BasePeriodCalculator` to define a custom naming scheme or non-standard boundaries:
51+
Subclass `BasePeriodCalculator` to define a custom naming scheme or non-standard boundaries.
52+
A subclass must define `_NAME_PATTERN` (a compiled regex whose group 1 is the table name)
53+
and implement `_period_from_match`; the inherited `parse_partition_name` then matches names
54+
against the pattern and returns `None` for names that do not match or encode invalid values:
5255

5356
```python
57+
import re
58+
from datetime import datetime, timezone
59+
from typing import ClassVar
60+
5461
from pg_partsmith.strategies import BasePeriodCalculator
5562
from pg_partsmith.entities import Period
56-
from datetime import datetime, timezone
5763

5864

5965
class FiscalYearPeriodCalculator(BasePeriodCalculator):
6066
"""Yearly partitions aligned to a fiscal year starting April 1."""
6167

68+
_NAME_PATTERN: ClassVar[re.Pattern[str]] = re.compile(r"^(.+)__fy(\d{4})$")
69+
6270
def current_period(self) -> Period:
6371
now = datetime.now(timezone.utc)
6472
fiscal_year = now.year if now.month >= 4 else now.year - 1
@@ -67,13 +75,13 @@ class FiscalYearPeriodCalculator(BasePeriodCalculator):
6775
def format_partition_name(self, table_name: str, period: Period) -> str:
6876
return f"{table_name}__fy{period.year}"
6977

70-
def parse_partition_name(self, partition_name: str) -> Period | None:
71-
# parse back to Period for retention logic
72-
...
78+
def _period_from_match(self, match: re.Match[str]) -> Period:
79+
# group 1 is the table name, group 2 encodes the fiscal year
80+
return Period(year=int(match.group(2)))
7381

7482
def get_boundaries(self, period: Period) -> tuple[str, str]:
75-
# return (from_value, to_value) as SQL-compatible strings
76-
...
83+
# fiscal year N runs from 1 April N to 1 April N+1
84+
return (f"{period.year}-04-01", f"{period.year + 1}-04-01")
7785
```
7886

7987
## Protocol

‎pg_partsmith/aio/lock/postgres.py‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -108,16 +108,21 @@ async def _lock_scope(self, table_name: str) -> AsyncIterator[None]:
108108
await self._release_safely(conn, lock_id, table_name, body_exc)
109109

110110
async def _respect_rate_limit(self, table_name: str) -> None:
111-
"""Sleep enough to enforce the configured min-interval between acquires."""
111+
"""Sleep enough to enforce the configured min-interval between acquires.
112+
113+
The per-table slot is reserved under the mutex; the sleep itself happens
114+
outside it so one table's owed delay never blocks acquires for other tables.
115+
"""
112116
if self._acquire_min_interval <= 0:
113117
return
114118
async with self._rate_limit_lock:
115119
now = time.monotonic()
116-
last = self._last_acquire_time.get(table_name, 0.0)
117-
delay = last + self._acquire_min_interval - now
118-
if delay > 0:
119-
await asyncio.sleep(delay)
120-
self._last_acquire_time[table_name] = time.monotonic()
120+
last = self._last_acquire_time.get(table_name)
121+
slot = now if last is None else max(now, last + self._acquire_min_interval)
122+
self._last_acquire_time[table_name] = slot
123+
delay = slot - now
124+
if delay > 0:
125+
await asyncio.sleep(delay)
121126

122127
async def _try_acquire(self, conn: AsyncConnection, lock_id: int, table_name: str) -> None:
123128
"""Run ``pg_try_advisory_lock`` and raise if not granted."""

‎pg_partsmith/aio/lock/redis.py‎

Lines changed: 36 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
from __future__ import annotations
99

1010
import asyncio
11-
import contextlib
1211
import logging
1312
import random
1413
import secrets
@@ -152,31 +151,41 @@ async def _lock_scope(self, table_name: str) -> AsyncIterator[None]:
152151
if not await self._redis.set(key, token, ex=self._ttl, nx=True):
153152
raise LockAcquisitionError(table_name, "Redis lock unavailable")
154153

155-
holder_task = asyncio.current_task()
156-
if holder_task is None:
157-
raise RuntimeError("Could not determine current asyncio task")
158-
159-
watchdog = asyncio.create_task(
160-
self._renewal_watchdog(key, token, table_name, holder_task),
161-
name=f"redis-lock-watchdog:{key}",
162-
)
154+
# From here on the key is held: any failure must release it rather than leak it until TTL.
155+
watchdog: asyncio.Task[None] | None = None
163156
try:
157+
holder_task = asyncio.current_task()
158+
if holder_task is None:
159+
raise RuntimeError("Could not determine current asyncio task")
160+
161+
watchdog = asyncio.create_task(
162+
self._renewal_watchdog(key, token, table_name, holder_task),
163+
name=f"redis-lock-watchdog:{key}",
164+
)
164165
yield
165166
finally:
166-
await self._cancel_watchdog(watchdog)
167-
await asyncio.shield(self._release_safely(key, token, table_name))
167+
try:
168+
if watchdog is not None:
169+
await self._cancel_watchdog(watchdog)
170+
finally:
171+
await asyncio.shield(self._release_safely(key, token, table_name))
168172

169173
async def _respect_rate_limit(self, table_name: str) -> None:
170-
"""Sleep enough to enforce the configured min-interval between acquires."""
174+
"""Sleep enough to enforce the configured min-interval between acquires.
175+
176+
The per-table slot is reserved under the mutex; the sleep itself happens
177+
outside it so one table's owed delay never blocks acquires for other tables.
178+
"""
171179
if self._acquire_min_interval <= 0:
172180
return
173181
async with self._rate_limit_lock:
174182
now = time.monotonic()
175-
last = self._last_acquire_time.get(table_name, 0.0)
176-
delay = last + self._acquire_min_interval - now
177-
if delay > 0:
178-
await asyncio.sleep(delay)
179-
self._last_acquire_time[table_name] = time.monotonic()
183+
last = self._last_acquire_time.get(table_name)
184+
slot = now if last is None else max(now, last + self._acquire_min_interval)
185+
self._last_acquire_time[table_name] = slot
186+
delay = slot - now
187+
if delay > 0:
188+
await asyncio.sleep(delay)
180189

181190
async def _renewal_watchdog(
182191
self,
@@ -230,10 +239,18 @@ def _fail_holder(
230239
holder_task.cancel()
231240

232241
async def _cancel_watchdog(self, watchdog: asyncio.Task[None]) -> None:
233-
"""Cancel the renewal watchdog and absorb its CancelledError."""
242+
"""Cancel the renewal watchdog and absorb its CancelledError.
243+
244+
If the holder task itself is being cancelled while awaiting the watchdog
245+
(e.g. app shutdown calls ``task.cancel()``), the cancellation must
246+
propagate — only the watchdog's own cancellation is swallowed.
247+
"""
234248
watchdog.cancel()
235-
with contextlib.suppress(asyncio.CancelledError):
249+
try:
236250
await watchdog
251+
except asyncio.CancelledError:
252+
if (cur := asyncio.current_task()) is not None and cur.cancelling() > 0:
253+
raise
237254

238255
async def _release_safely(self, key: str, token: str, table_name: str) -> None:
239256
"""Release the lock; failures are logged but do not propagate.

‎pg_partsmith/aio/maintainer.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from pg_partsmith.aio.protocols import PartitionLifecycle
88
from pg_partsmith.entities import MaintenanceResult, TablePartitionConfig
9+
from pg_partsmith.exceptions import PartitionError
910
from pg_partsmith.utils import format_duration_ms, qualify
1011

1112
logger = logging.getLogger(__name__)
@@ -97,6 +98,18 @@ async def run_maintenance(
9798
},
9899
)
99100
raise
101+
except PartitionError as e:
102+
duration_ms = int((time.perf_counter() - start_time) * 1000)
103+
logger.warning(
104+
"Partition maintenance failed (operational error)",
105+
extra={
106+
"table_name": qualified_table,
107+
"duration_ms": duration_ms,
108+
"error": str(e),
109+
"error_type": type(e).__name__,
110+
},
111+
)
112+
raise
100113
except (RuntimeError, ValueError) as e:
101114
duration_ms = int((time.perf_counter() - start_time) * 1000)
102115
logger.warning(

‎pg_partsmith/aio/metadata.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""PostgreSQL metadata provider."""
22

3+
import logging
34
import re
45

56
from sqlalchemy import text
@@ -15,12 +16,32 @@
1516
)
1617

1718
# Pre-compiled regex patterns for partition boundary parsing.
19+
_RANGE_BOUND_PATTERN = re.compile(r"^\s*FOR\s+VALUES\s+FROM\s*\(", re.IGNORECASE)
1820
_BOUNDARY_SEP_PATTERN = re.compile(r"\)\s+TO\s+\(", re.IGNORECASE)
1921
_FROM_PREFIX_PATTERN = re.compile(r"^.*?FROM\s*\(", re.IGNORECASE | re.DOTALL)
2022
_TRAILING_PAREN_PATTERN = re.compile(r"\)\s*$", re.IGNORECASE | re.DOTALL)
2123
_CAST_PATTERN = re.compile(r"^CAST\((?P<inner>.*)\s+AS\s+.*\)$", re.IGNORECASE | re.DOTALL)
2224
_STR_LITERAL_PATTERN = re.compile(r"'(?P<s>(?:[^']|'')*)'")
2325

26+
logger = logging.getLogger(__name__)
27+
28+
29+
def _is_addressable(schema: str, relname: str) -> bool:
30+
"""Return False for relations whose schema or name contains a dot.
31+
32+
The library addresses relations as ``schema.relname`` strings, so a dot
33+
inside either part would be re-split into a different relation by
34+
``quote_identifier`` — DDL could then target the wrong table. Such
35+
partitions are never created by this library; skip them with a warning.
36+
"""
37+
if "." in schema or "." in relname:
38+
logger.warning(
39+
"Skipping partition with '.' in its schema or name; not addressable by qualified-name DDL",
40+
extra={"partition_schema": schema, "partition_name": relname},
41+
)
42+
return False
43+
return True
44+
2445

2546
class PostgresMetadataProvider:
2647
"""Provider for PostgreSQL partition metadata.
@@ -217,6 +238,9 @@ async def list_partitions(self, table_name: str) -> list[PartitionInfo]:
217238
if isinstance(part_schema, bytes):
218239
part_schema = part_schema.decode("utf-8", errors="replace")
219240

241+
if not _is_addressable(part_schema, relname):
242+
continue
243+
220244
name = qualify(part_schema if want_qualified else None, relname)
221245

222246
boundaries = row.boundaries
@@ -248,6 +272,9 @@ async def list_partitions(self, table_name: str) -> list[PartitionInfo]:
248272
if isinstance(orphan_schema, bytes):
249273
orphan_schema = orphan_schema.decode("utf-8", errors="replace")
250274

275+
if not _is_addressable(orphan_schema, orphan_relname):
276+
continue
277+
251278
name = qualify(orphan_schema if want_qualified else None, orphan_relname)
252279
partitions.append(
253280
PartitionInfo(
@@ -372,6 +399,11 @@ def _parse_boundaries(self, boundaries_expr: str | None) -> tuple[str | None, st
372399
if boundaries_expr.strip().upper() == "DEFAULT":
373400
return None, None
374401

402+
# Only RANGE bounds carry FROM/TO values; LIST/HASH expressions could
403+
# contain a ") TO (" inside a string value and must not be mis-parsed.
404+
if not _RANGE_BOUND_PATTERN.match(boundaries_expr):
405+
return None, None
406+
375407
# Split into FROM and TO parts by finding ") TO (" which is the most
376408
# reliable separator for range boundaries.
377409
parts = _BOUNDARY_SEP_PATTERN.split(boundaries_expr)

‎pg_partsmith/aio/repositories/creator.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,10 @@ async def reconcile_default_rows(
106106
)
107107

108108
async with asyncio.timeout(self._ddl_timeout), self._engine.begin() as conn:
109+
# Boundary literals must be interpreted in the same timezone ATTACH uses,
110+
# otherwise a non-UTC server timezone moves the wrong row range.
111+
if self._ddl_timezone is not None:
112+
await conn.execute(text(f"SET LOCAL TIME ZONE {quote_literal(self._ddl_timezone)}"))
109113
# Lock both tables to minimize race conditions
110114
await conn.execute(text(f"LOCK TABLE {default_quoted} IN SHARE ROW EXCLUSIVE MODE"))
111115
await conn.execute(text(f"LOCK TABLE {target_quoted} IN SHARE ROW EXCLUSIVE MODE"))

0 commit comments

Comments
 (0)