Skip to content

Commit 810f8a0

Browse files
fix: address external review findings — pruning fail-closed, qualified names, drop revalidation (#17)
* fix: address external review findings — pruning fail-closed, qualified names, drop revalidation Treat infinity upper bounds as unbounded and skip attached partitions with uninterpretable boundaries instead of name-guessing; always schema-qualify partition names from the catalog; revalidate attachment and orphan marker under ACCESS EXCLUSIVE in the DROP transaction; recognise subpartitioned children (relkind 'p') in existence and orphan discovery; verify attach-race conflicts via is_partition_attached postcondition; run the compensating DEFAULT restore on cancellation/interrupt; release the Redis key when cancellation lands mid-SET; document COMMENT-marker dump/restore semantics. * test: cover interruption and conflict-postcondition branches
1 parent 424a882 commit 810f8a0

33 files changed

Lines changed: 1597 additions & 146 deletions

‎CHANGELOG.md‎

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

1010
### Fixed
1111

12+
- Pruning fails closed: `infinity` upper bounds are treated as unbounded (like
13+
`MAXVALUE`), and an attached partition whose catalog boundary cannot be
14+
interpreted is skipped with a warning instead of being pruned by its name.
15+
- `list_partitions` always returns schema-qualified partition names taken from
16+
the catalog — a partition living in a different schema than its parent can no
17+
longer be re-resolved via `search_path` to an unrelated same-named table.
18+
- `drop_partition` revalidates attachment and the orphan marker under an
19+
`ACCESS EXCLUSIVE` lock in the same transaction as `DROP TABLE`, closing the
20+
window where a concurrently reattached or replaced relation could be dropped.
21+
- Subpartitioned partitions (`relkind='p'`) are now recognised by existence
22+
checks and orphan discovery, so a detached partitioned child is dropped
23+
instead of being silently leaked.
24+
- Attach conflict SQLSTATEs (incl. `42809`) are only treated as a lost race
25+
after verifying the partition is actually attached to the requested parent.
26+
- The compensating "return rows to DEFAULT" step now also runs when the attach
27+
is interrupted by cancellation (async, shielded) or KeyboardInterrupt (sync).
28+
- A cancellation that lands while awaiting the Redis `SET NX` response performs
29+
a token-checked release, so a server-side-applied SET no longer leaks the
30+
lock until TTL.
31+
1232
- Detach: a partition left in `inhdetachpending` state by a cancelled
1333
`DETACH CONCURRENTLY` (e.g. a DDL timeout) is now completed with
1434
`DETACH PARTITION ... FINALIZE` instead of failing on every subsequent run.

‎README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,11 @@ database contains similarly named tables not managed by this library.
145145
Set `marker_prefix` explicitly on both `PostgresPartitionRepository` and
146146
`PostgresMetadataProvider` to ensure consistent orphan marker recognition across deployments.
147147

148+
> **Marker semantics** — the `COMMENT` marker means "this library owns cleanup of this
149+
> table". It survives `pg_dump`/restore (comments are dumped by default), so a restored
150+
> copy of a marked table is again eligible for dropping. When repurposing such a table,
151+
> clear its comment (`COMMENT ON TABLE ... IS NULL`) or restore with `--no-comments`.
152+
148153
## DEFAULT partition reconciliation
149154

150155
When creating a new partition, if the DEFAULT partition contains rows belonging to the

‎cov.json‎

Lines changed: 1 addition & 0 deletions
Large diffs are not rendered by default.

‎pg_partsmith/aio/lock/redis.py‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,16 @@ async def _lock_scope(self, table_name: str) -> AsyncIterator[None]:
148148
key = self._get_lock_key(table_name)
149149
token = secrets.token_hex(16)
150150

151-
if not await self._redis.set(key, token, ex=self._ttl, nx=True):
151+
try:
152+
acquired = await self._redis.set(key, token, ex=self._ttl, nx=True)
153+
except asyncio.CancelledError:
154+
# The SET may have been applied server-side before the cancellation
155+
# landed; the unlock script checks the token, so this is a safe no-op
156+
# when it was not.
157+
await asyncio.shield(self._release_safely(key, token, table_name))
158+
raise
159+
160+
if not acquired:
152161
raise LockAcquisitionError(table_name, "Redis lock unavailable")
153162

154163
# From here on the key is held: any failure must release it rather than leak it until TTL.

‎pg_partsmith/aio/metadata.py‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
orphan_comment_prefix,
1212
orphan_table_comment,
1313
qualify,
14-
split_qualified_name,
1514
to_regclass_argument,
1615
)
1716

@@ -139,10 +138,11 @@ async def list_partitions(self, table_name: str) -> list[PartitionInfo]:
139138
detached by this library. They are detected by a COMMENT marker set on
140139
successful detach and returned with ``is_attached=False`` and ``None``
141140
boundaries.
142-
"""
143-
parent_schema, _ = split_qualified_name(table_name)
144-
want_qualified = parent_schema is not None
145141
142+
Partition names are always schema-qualified with the child's catalog
143+
schema — a partition may live in a different schema than its parent,
144+
and a bare name could resolve to an unrelated table via ``search_path``.
145+
"""
146146
async with self._engine.connect() as conn:
147147
# 1. Get partition type and canonical parent name in one query
148148
parent_info_result = await conn.execute(
@@ -210,7 +210,7 @@ async def list_partitions(self, table_name: str) -> list[PartitionInfo]:
210210
ON d.objoid = c.oid
211211
AND d.classoid = 'pg_class'::regclass
212212
AND d.objsubid = 0
213-
WHERE c.relkind = 'r'
213+
WHERE c.relkind IN ('r', 'p')
214214
AND c.relispartition = false
215215
AND split_part(d.description, E'\\n', 1) = :marker
216216
AND NOT EXISTS (
@@ -241,7 +241,7 @@ async def list_partitions(self, table_name: str) -> list[PartitionInfo]:
241241
if not _is_addressable(part_schema, relname):
242242
continue
243243

244-
name = qualify(part_schema if want_qualified else None, relname)
244+
name = qualify(part_schema, relname)
245245

246246
boundaries = row.boundaries
247247
if isinstance(boundaries, bytes):
@@ -275,7 +275,7 @@ async def list_partitions(self, table_name: str) -> list[PartitionInfo]:
275275
if not _is_addressable(orphan_schema, orphan_relname):
276276
continue
277277

278-
name = qualify(orphan_schema if want_qualified else None, orphan_relname)
278+
name = qualify(orphan_schema, orphan_relname)
279279
partitions.append(
280280
PartitionInfo(
281281
name=name,
@@ -296,7 +296,8 @@ async def partition_exists(self, partition_name: str) -> bool:
296296
partition_name: Partition table name.
297297
298298
Returns:
299-
True if the table exists as a regular table.
299+
True if the table exists as a regular or partitioned table
300+
(a partition may itself be subpartitioned).
300301
"""
301302
async with self._engine.connect() as conn:
302303
result = await conn.execute(
@@ -306,7 +307,7 @@ async def partition_exists(self, partition_name: str) -> bool:
306307
SELECT 1
307308
FROM pg_class
308309
WHERE oid = to_regclass(:partition_name)
309-
AND relkind = 'r'
310+
AND relkind IN ('r', 'p')
310311
)
311312
"""
312313
),

‎pg_partsmith/aio/repositories/fk_manager.py‎

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,24 @@ def __init__(self, engine: AsyncEngine, ddl_timeout: float) -> None:
2323
async def list_constraints(self, partition_name: str) -> list[str]:
2424
"""List FK constraints defined ON the partition."""
2525
async with asyncio.timeout(self._ddl_timeout), self._engine.connect() as conn:
26-
result = await conn.execute(
27-
text(
28-
"""
29-
SELECT con.conname
30-
FROM pg_constraint con
31-
WHERE con.conrelid = to_regclass(:partition_name)
32-
AND con.contype = 'f'
33-
ORDER BY con.conname
34-
"""
35-
),
36-
{"partition_name": to_regclass_argument(partition_name)},
37-
)
38-
rows = result.fetchall()
26+
return await self.list_constraints_conn(conn, partition_name)
27+
28+
@staticmethod
29+
async def list_constraints_conn(conn: AsyncConnection, partition_name: str) -> list[str]:
30+
"""List FK constraints using an existing connection."""
31+
result = await conn.execute(
32+
text(
33+
"""
34+
SELECT con.conname
35+
FROM pg_constraint con
36+
WHERE con.conrelid = to_regclass(:partition_name)
37+
AND con.contype = 'f'
38+
ORDER BY con.conname
39+
"""
40+
),
41+
{"partition_name": to_regclass_argument(partition_name)},
42+
)
43+
rows = result.fetchall()
3944
names: list[str] = []
4045
for row in rows:
4146
conname = row[0]

‎pg_partsmith/aio/repositories/remover.py‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -213,15 +213,14 @@ async def drop(self, partition_name: str) -> None:
213213
if not await self._ensure_managed(conn, partition_name):
214214
return
215215

216-
fk_constraints = await self._fk_manager.list_constraints(partition_name)
217216
last_exc: BaseException | None = None
218217

219218
for attempt in range(self._drop_max_retries):
220219
if attempt > 0:
221220
await self._handle_retry_delay(attempt, last_exc, partition_name)
222221

223222
try:
224-
await self._execute_drop(partition_name, fk_constraints)
223+
await self._execute_drop(partition_name)
225224
except (SQLAlchemyError, OSError, TimeoutError) as exc:
226225
if isinstance(exc, SQLAlchemyError) and pg_sqlstate(exc) not in _RETRYABLE_PG_STATES:
227226
raise
@@ -231,12 +230,31 @@ async def drop(self, partition_name: str) -> None:
231230

232231
raise DropRetryExhaustedError(partition_name, self._drop_max_retries, last_exc) from last_exc
233232

234-
async def _execute_drop(self, partition_name: str, fk_constraints: list[str]) -> None:
233+
async def _execute_drop(self, partition_name: str) -> None:
234+
"""Lock, revalidate, and drop in one transaction.
235+
236+
The pre-checks in :meth:`drop` run on a different connection, so the
237+
relation could have been reattached or replaced since. Taking ACCESS
238+
EXCLUSIVE first and revalidating under it closes that window —
239+
PostgreSQL happily drops even an attached partition via DROP TABLE.
240+
"""
235241
async with asyncio.timeout(self._ddl_timeout), self._engine.begin() as conn:
236242
await conn.execute(
237243
text("SELECT set_config('lock_timeout', :timeout, true)"),
238244
{"timeout": str(self._drop_lock_timeout_ms)},
239245
)
246+
try:
247+
await conn.execute(
248+
build_ddl_statement("LOCK TABLE {partition} IN ACCESS EXCLUSIVE MODE", partition=partition_name)
249+
)
250+
except (SQLAlchemyError, OSError, TimeoutError) as exc:
251+
if pg_sqlstate(exc) == "42P01": # dropped concurrently — nothing left to do
252+
return
253+
raise
254+
await self._ensure_not_attached(conn, partition_name)
255+
if not await self._ensure_managed(conn, partition_name):
256+
return
257+
fk_constraints = await self._fk_manager.list_constraints_conn(conn, partition_name)
240258
await self._fk_manager.drop_constraints(conn, partition_name, fk_constraints)
241259
await conn.execute(build_ddl_statement("DROP TABLE IF EXISTS {partition}", partition=partition_name))
242260

‎pg_partsmith/aio/repositories/resolver.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,19 @@ async def exists(self, name: str) -> bool:
2525

2626
@staticmethod
2727
async def exists_conn(conn: AsyncConnection, name: str) -> bool:
28-
"""Check existence using an existing connection."""
28+
"""Check existence using an existing connection.
29+
30+
Accepts regular and partitioned tables — a partition may itself be
31+
subpartitioned.
32+
"""
2933
result = await conn.execute(
3034
text(
3135
"""
3236
SELECT EXISTS (
3337
SELECT 1
3438
FROM pg_class
3539
WHERE oid = to_regclass(:partition_name)
36-
AND relkind = 'r'
40+
AND relkind IN ('r', 'p')
3741
)
3842
"""
3943
),

‎pg_partsmith/aio/services/creation.py‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,12 @@ async def _attach_with_reconcile(
204204
for attempt in range(1, _DEFAULT_CONFLICT_MAX_RETRIES + 1):
205205
try:
206206
await self._repo.attach_partition(qualified_parent, partition_name, from_value, to_value)
207+
except asyncio.CancelledError:
208+
# Shielded so the compensating move-back completes even mid-cancellation.
209+
await asyncio.shield(
210+
self._restore_reconciled_rows(reconciled_from, config, partition_name, from_value, to_value)
211+
)
212+
raise
207213
except (OSError, TimeoutError):
208214
await self._restore_reconciled_rows(reconciled_from, config, partition_name, from_value, to_value)
209215
raise
@@ -310,23 +316,38 @@ async def _handle_existing_partition(
310316
) -> None:
311317
"""Handle case where partition already exists in metadata."""
312318
if config.auto_attach_after_create and not existing.is_attached:
319+
qualified_parent = qualify(config.db_schema, config.table_name)
313320
try:
314321
await self._attach_with_reconcile(config, existing.name, from_value, to_value)
315322
except (OSError, TimeoutError):
316323
raise
317324
except SQLAlchemyError as e:
318-
state = pg_sqlstate(e)
319-
if state not in _ATTACH_CONFLICT_SQLSTATES:
325+
if not await self._is_attach_conflict_benign(qualified_parent, existing.name, e):
320326
raise
321327
logger.debug(
322328
"Partition already attached (race with another worker)",
323-
extra={"partition_name": existing.name, "sqlstate": state},
329+
extra={"partition_name": existing.name, "sqlstate": pg_sqlstate(e)},
324330
)
325331

332+
async def _is_attach_conflict_benign(
333+
self, qualified_parent: str, partition_name: str, exc: SQLAlchemyError
334+
) -> bool:
335+
"""A conflict SQLSTATE proves a lost race only if the postcondition holds.
336+
337+
42809 (wrong_object_type) also fires for typed tables, inheritance
338+
children, and attachments to a *different* parent — verify the
339+
partition is actually attached to our parent instead of trusting the
340+
error code alone.
341+
"""
342+
if pg_sqlstate(exc) not in _ATTACH_CONFLICT_SQLSTATES:
343+
return False
344+
return await self._metadata.is_partition_attached(qualified_parent, partition_name)
345+
326346
async def _create_and_attach_partition(
327347
self, config: TablePartitionConfig, partition_name: str, from_value: str, to_value: str
328348
) -> PartitionInfo | None:
329349
"""Create partition and optionally attach it to parent."""
350+
qualified_parent = qualify(config.db_schema, config.table_name)
330351
try:
331352
partition_info = await self._repo.create_partition(config, partition_name, from_value, to_value)
332353
except PartitionAlreadyExistsError:
@@ -336,7 +357,7 @@ async def _create_and_attach_partition(
336357
except (OSError, TimeoutError):
337358
raise
338359
except SQLAlchemyError as e:
339-
if pg_sqlstate(e) not in _ATTACH_CONFLICT_SQLSTATES:
360+
if not await self._is_attach_conflict_benign(qualified_parent, partition_name, e):
340361
raise
341362
logger.debug(
342363
"Partition already attached (race)",
@@ -350,7 +371,7 @@ async def _create_and_attach_partition(
350371
except (OSError, TimeoutError):
351372
raise
352373
except SQLAlchemyError as e:
353-
if pg_sqlstate(e) not in _ATTACH_CONFLICT_SQLSTATES:
374+
if not await self._is_attach_conflict_benign(qualified_parent, partition_name, e):
354375
raise
355376
logger.debug(
356377
"Partition already attached (race)",

‎pg_partsmith/aio/services/pruning.py‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020

2121
logger = logging.getLogger(__name__)
2222

23+
# Upper-bound spellings that mean "no upper limit" — such partitions hold
24+
# current data and must never be pruned.
25+
_UNBOUNDED_UPPER = frozenset({"MAXVALUE", "INFINITY", "+INFINITY"})
26+
2327

2428
class PartitionPruningService:
2529
"""Service for identifying partitions that should be pruned."""
@@ -54,12 +58,12 @@ async def identify_partitions_to_prune(
5458
if partition.is_default:
5559
continue
5660

57-
# A MAXVALUE upper bound means the partition holds current data no
58-
# matter what its name suggests — never prune it via name fallback.
59-
if partition.to_value is not None and partition.to_value.strip().upper() == "MAXVALUE":
61+
# An unbounded upper bound (MAXVALUE / infinity) means the partition
62+
# holds current data no matter what its name suggests — never prune it.
63+
if partition.to_value is not None and partition.to_value.strip().upper() in _UNBOUNDED_UPPER:
6064
logger.info(
61-
"Skipping partition with unbounded upper boundary (MAXVALUE)",
62-
extra={"partition_name": partition.name},
65+
"Skipping partition with unbounded upper boundary",
66+
extra={"partition_name": partition.name, "to_value": partition.to_value},
6367
)
6468
continue
6569

@@ -71,6 +75,16 @@ async def identify_partitions_to_prune(
7175
parsed_end_dt_by_name[partition.name] = end_dt
7276
continue
7377

78+
# An attached partition always carries a catalog boundary; if we
79+
# cannot interpret it while the cutoff is a real instant, guessing
80+
# by name risks dropping live data — fail closed instead.
81+
if partition.is_attached and cutoff_start_dt is not None:
82+
logger.warning(
83+
"Cannot interpret attached partition boundary; skipping to avoid unsafe pruning",
84+
extra={"partition_name": partition.name, "to_value": partition.to_value},
85+
)
86+
continue
87+
7488
# Fall back to name-based pruning
7589
period: Period | None = None
7690
try:

0 commit comments

Comments
 (0)