Skip to content

Commit d505fbb

Browse files
author
Alexey Shalaev
committed
fix: a refused detach no longer starts the drop grace
A refused DETACH ... CONCURRENTLY left its orphan marker, detached-at included, on a partition that stayed attached, and later detaches kept that instant, so DropAfter's grace counted from the first refusal. A refusal (55006, 23503) now takes the marker back off, keeping the table's own comment, and a detach of a still-attached partition always records its own instant. Closes #105
1 parent 153f6de commit d505fbb

6 files changed

Lines changed: 231 additions & 21 deletions

File tree

‎CHANGELOG.md‎

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

3434
* a backfilled window always attaches with writers held at the parent ([#89](https://github.com/bedrock-python/pg-partsmith/issues/89)) ([b1260c1](https://github.com/bedrock-python/pg-partsmith/commit/b1260c1a8bcdd6388c3836d57eb548f8fe5959bb))
3535

36+
## 1.8.3 — a refused detach no longer starts the drop grace
37+
38+
A `DETACH … CONCURRENTLY` writes the orphan marker, with its `detached-at` instant, in a
39+
transaction of its own before the statement runs. When PostgreSQL refused the statement — a
40+
partition still referenced through a foreign key, say — the marker stayed on a partition that
41+
was still attached, and every later detach kept its instant. The day the references went, the
42+
detach succeeded and the next run dropped the table at once, its grace counted from the first
43+
refusal ([#105](https://github.com/bedrock-python/pg-partsmith/issues/105)).
44+
45+
A refusal now takes the marker back off, keeping whatever comment the table had before, and a
46+
detach of a partition that is still attached always records its own instant, so a marker that
47+
was left behind anyway cannot shorten the grace either.
48+
3649
## 1.8.2 — cancellation stops a run_maintenance_safe
3750

3851
`run_maintenance_safe()` caught `asyncio.CancelledError`, `KeyboardInterrupt` and `SystemExit`

‎pg_partsmith/aio/repositories/remover.py‎

Lines changed: 70 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from pg_partsmith.utils import (
2525
build_ddl_statement,
2626
coerce_str,
27+
comment_without_markers,
2728
orphan_comment,
2829
parse_orphan_comment,
2930
pg_sqlstate,
@@ -298,6 +299,7 @@ async def _detach_concurrently(
298299
try:
299300
return await self._run_concurrent_detach(table_name, partition_name)
300301
except (SQLAlchemyError, OSError, TimeoutError) as exc:
302+
await self._unmark_if_refused(exc, partition_name, None)
301303
return self._classify_concurrent_failure(exc, table_name, partition_name, fallback=fallback)
302304

303305
async def _detach_concurrently_pinned(
@@ -327,6 +329,7 @@ async def statement() -> bool:
327329
statement_pid=lambda: pid_box[0],
328330
)
329331
except (SQLAlchemyError, OSError, TimeoutError) as exc:
332+
await self._unmark_if_refused(exc, partition_name, expected_oid)
330333
return self._classify_concurrent_failure(exc, table_name, partition_name, fallback=fallback)
331334

332335
async def _run_concurrent_detach(
@@ -343,17 +346,61 @@ async def _run_concurrent_detach(
343346
if pid_box is not None:
344347
backend = (await conn.execute(text("SELECT pg_backend_pid()"))).scalar()
345348
pid_box[0] = None if backend is None else int(backend)
346-
already_marked = (
347-
await conn.execute(
348-
text("SELECT obj_description(to_regclass(:partition_name), 'pg_class')"),
349-
{"partition_name": to_regclass_argument(partition_name)},
350-
)
351-
).scalar()
352-
if parse_orphan_comment(coerce_str(already_marked), marker_prefix=self._marker_prefix) is None:
353-
await self._mark_orphaned(conn, table_name, partition_name)
349+
await self._mark_orphaned(conn, table_name, partition_name)
354350
await conn.execute(stmt)
355351
return True
356352

353+
async def _unmark_if_refused(self, exc: Exception, partition_name: str, expected_oid: int | None) -> None:
354+
"""Take the marker back off a partition PostgreSQL refused to detach.
355+
356+
The marker went on in its own committed transaction before the
357+
statement, so a refusal leaves an attached partition saying it was
358+
detached. Only the marker lines go; the comment the table had before
359+
stays. Best effort: the refusal is what the caller reports, and a
360+
marker left behind is harmless because the next detach stamps its own
361+
instant (see :meth:`_mark_orphaned`).
362+
"""
363+
if pg_sqlstate(exc) not in {"55006", "23503"}:
364+
return
365+
try:
366+
async with asyncio.timeout(self._ddl_timeout), self._engine.begin() as conn:
367+
await conn.execute(text(SET_LOCK_TIMEOUT_SQL), {"timeout": str(self._lock_timeout_ms)})
368+
foreign = await _relkind(conn, partition_name) == "f"
369+
if not foreign:
370+
# What COMMENT takes anyway, taken first, so the checks below see one relation.
371+
await conn.execute(
372+
build_ddl_statement(
373+
"LOCK TABLE ONLY {partition} IN SHARE UPDATE EXCLUSIVE MODE", partition=partition_name
374+
)
375+
)
376+
await self._ensure_expected_oid(conn, partition_name, expected_oid)
377+
if not await _plainly_attached(conn, partition_name):
378+
return
379+
existing = coerce_str(
380+
(
381+
await conn.execute(
382+
text("SELECT obj_description(to_regclass(:partition_name), 'pg_class')"),
383+
{"partition_name": to_regclass_argument(partition_name)},
384+
)
385+
).scalar()
386+
)
387+
if parse_orphan_comment(existing, marker_prefix=self._marker_prefix) is None:
388+
return
389+
rest = comment_without_markers(existing, marker_prefix=self._marker_prefix)
390+
relation = "FOREIGN TABLE" if foreign else "TABLE"
391+
if rest:
392+
stmt = build_ddl_statement(
393+
f"COMMENT ON {relation} {{partition}} IS [comment]", partition=partition_name, comment=rest
394+
)
395+
else:
396+
stmt = build_ddl_statement(f"COMMENT ON {relation} {{partition}} IS NULL", partition=partition_name)
397+
await conn.execute(stmt)
398+
except (SQLAlchemyError, OSError, TimeoutError, PlanStaleError) as cleanup_exc:
399+
logger.warning(
400+
"Could not take the orphan marker back off a partition whose detach was refused",
401+
extra={"partition_name": partition_name, "error": str(cleanup_exc)},
402+
)
403+
357404
def _classify_concurrent_failure(
358405
self, exc: Exception, table_name: str, partition_name: str, *, fallback: bool
359406
) -> bool:
@@ -393,6 +440,11 @@ async def _mark_orphaned(
393440
Written *before* the DETACH so an interrupted run leaves a marked table
394441
rather than an unmarked one that orphan discovery would never see.
395442
443+
An instant the table already carries is kept while it is detached or its
444+
detach is pending. On a partition that is still plainly attached it is
445+
what a refused ``DETACH … CONCURRENTLY`` left behind, not a detach, so
446+
this detach records its own.
447+
396448
Args:
397449
stamp_now: Record the current instant as the detach time. Off for
398450
adoption, where the table was detached at an unknown time.
@@ -411,6 +463,7 @@ async def _mark_orphaned(
411463
detached_at=instant,
412464
existing_comment=existing_comment,
413465
marker_prefix=self._marker_prefix,
466+
keep_instant=not (stamp_now and await _plainly_attached(conn, partition_name)),
414467
)
415468
if new_comment == existing_comment:
416469
return
@@ -613,3 +666,12 @@ async def _handle_retry_delay(self, attempt: int, last_exc: BaseException | None
613666
async def _relkind(conn: AsyncConnection, name: str) -> str | None:
614667
"""``pg_class.relkind`` of the relation holding ``name``, or None when there is none."""
615668
return await relation_kind(conn, name)
669+
670+
671+
async def _plainly_attached(conn: AsyncConnection, name: str) -> bool:
672+
"""Whether the relation is attached to a parent with no detach pending."""
673+
result = await conn.execute(
674+
text("SELECT NOT inhdetachpending FROM pg_inherits WHERE inhrelid = to_regclass(:name)"),
675+
{"name": to_regclass_argument(name)},
676+
)
677+
return bool(result.scalar())

‎pg_partsmith/sync/repositories/remover.py‎

Lines changed: 70 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
from pg_partsmith.utils import (
2525
build_ddl_statement,
2626
coerce_str,
27+
comment_without_markers,
2728
orphan_comment,
2829
parse_orphan_comment,
2930
pg_sqlstate,
@@ -301,6 +302,7 @@ def _detach_concurrently(
301302
try:
302303
return self._run_concurrent_detach(table_name, partition_name)
303304
except (SQLAlchemyError, OSError, TimeoutError) as exc:
305+
self._unmark_if_refused(exc, partition_name, None)
304306
return self._classify_concurrent_failure(exc, table_name, partition_name, fallback=fallback)
305307

306308
def _detach_concurrently_pinned(
@@ -331,6 +333,7 @@ def statement() -> bool:
331333
statement_pid=lambda: pid_box[0],
332334
)
333335
except (SQLAlchemyError, OSError, TimeoutError) as exc:
336+
self._unmark_if_refused(exc, partition_name, expected_oid)
334337
return self._classify_concurrent_failure(exc, table_name, partition_name, fallback=fallback)
335338

336339
def _run_concurrent_detach(
@@ -348,16 +351,61 @@ def _run_concurrent_detach(
348351
if pid_box is not None:
349352
backend = (conn.execute(text("SELECT pg_backend_pid()"))).scalar()
350353
pid_box[0] = None if backend is None else int(backend)
351-
already_marked = (
354+
self._mark_orphaned(conn, table_name, partition_name)
355+
conn.execute(stmt)
356+
return True
357+
358+
def _unmark_if_refused(self, exc: Exception, partition_name: str, expected_oid: int | None) -> None:
359+
"""Take the marker back off a partition PostgreSQL refused to detach.
360+
361+
The marker went on in its own committed transaction before the
362+
statement, so a refusal leaves an attached partition saying it was
363+
detached. Only the marker lines go; the comment the table had before
364+
stays. Best effort: the refusal is what the caller reports, and a
365+
marker left behind is harmless because the next detach stamps its own
366+
instant (see :meth:`_mark_orphaned`).
367+
"""
368+
if pg_sqlstate(exc) not in {"55006", "23503"}:
369+
return
370+
try:
371+
with self._engine.begin() as conn:
372+
apply_local_statement_timeout(conn, self._ddl_timeout)
373+
conn.execute(text(SET_LOCK_TIMEOUT_SQL), {"timeout": str(self._lock_timeout_ms)})
374+
foreign = _relkind(conn, partition_name) == "f"
375+
if not foreign:
376+
# What COMMENT takes anyway, taken first, so the checks below see one relation.
352377
conn.execute(
353-
text("SELECT obj_description(to_regclass(:partition_name), 'pg_class')"),
354-
{"partition_name": to_regclass_argument(partition_name)},
378+
build_ddl_statement(
379+
"LOCK TABLE ONLY {partition} IN SHARE UPDATE EXCLUSIVE MODE", partition=partition_name
380+
)
355381
)
356-
).scalar()
357-
if parse_orphan_comment(coerce_str(already_marked), marker_prefix=self._marker_prefix) is None:
358-
self._mark_orphaned(conn, table_name, partition_name)
382+
self._ensure_expected_oid(conn, partition_name, expected_oid)
383+
if not _plainly_attached(conn, partition_name):
384+
return
385+
existing = coerce_str(
386+
(
387+
conn.execute(
388+
text("SELECT obj_description(to_regclass(:partition_name), 'pg_class')"),
389+
{"partition_name": to_regclass_argument(partition_name)},
390+
)
391+
).scalar()
392+
)
393+
if parse_orphan_comment(existing, marker_prefix=self._marker_prefix) is None:
394+
return
395+
rest = comment_without_markers(existing, marker_prefix=self._marker_prefix)
396+
relation = "FOREIGN TABLE" if foreign else "TABLE"
397+
if rest:
398+
stmt = build_ddl_statement(
399+
f"COMMENT ON {relation} {{partition}} IS [comment]", partition=partition_name, comment=rest
400+
)
401+
else:
402+
stmt = build_ddl_statement(f"COMMENT ON {relation} {{partition}} IS NULL", partition=partition_name)
359403
conn.execute(stmt)
360-
return True
404+
except (SQLAlchemyError, OSError, TimeoutError, PlanStaleError) as cleanup_exc:
405+
logger.warning(
406+
"Could not take the orphan marker back off a partition whose detach was refused",
407+
extra={"partition_name": partition_name, "error": str(cleanup_exc)},
408+
)
361409

362410
def _classify_concurrent_failure(
363411
self, exc: Exception, table_name: str, partition_name: str, *, fallback: bool
@@ -399,6 +447,11 @@ def _mark_orphaned(
399447
Written *before* the DETACH so an interrupted run leaves a marked table
400448
rather than an unmarked one that orphan discovery would never see.
401449
450+
An instant the table already carries is kept while it is detached or its
451+
detach is pending. On a partition that is still plainly attached it is
452+
what a refused ``DETACH … CONCURRENTLY`` left behind, not a detach, so
453+
this detach records its own.
454+
402455
Args:
403456
stamp_now: Record the current instant as the detach time. Off for
404457
adoption, where the table was detached at an unknown time.
@@ -417,6 +470,7 @@ def _mark_orphaned(
417470
detached_at=instant,
418471
existing_comment=existing_comment,
419472
marker_prefix=self._marker_prefix,
473+
keep_instant=not (stamp_now and _plainly_attached(conn, partition_name)),
420474
)
421475
if new_comment == existing_comment:
422476
return
@@ -619,3 +673,12 @@ def _handle_retry_delay(self, attempt: int, last_exc: BaseException | None, part
619673
def _relkind(conn: Connection, name: str) -> str | None:
620674
"""``pg_class.relkind`` of the relation holding ``name``, or None when there is none."""
621675
return relation_kind(conn, name)
676+
677+
678+
def _plainly_attached(conn: Connection, name: str) -> bool:
679+
"""Whether the relation is attached to a parent with no detach pending."""
680+
result = conn.execute(
681+
text("SELECT NOT inhdetachpending FROM pg_inherits WHERE inhrelid = to_regclass(:name)"),
682+
{"name": to_regclass_argument(name)},
683+
)
684+
return bool(result.scalar())

‎pg_partsmith/utils.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,20 +229,22 @@ def orphan_comment(
229229
detached_at: datetime | None,
230230
existing_comment: str | None,
231231
marker_prefix: str | None = None,
232+
keep_instant: bool = True,
232233
) -> str:
233234
"""Compose the whole COMMENT for a table this library detached.
234235
235236
Line one is the ownership marker :func:`orphan_table_comment` has always
236237
written; line two records the detach instant; whatever comment the table
237238
carried before is kept below them. Re-marking an already marked table keeps
238239
the instant it already carries, so a repeated detach does not restart a
239-
grace period.
240+
grace period -- unless ``keep_instant`` is off, for a marker whose instant
241+
records no detach at all.
240242
"""
241243
marker = orphan_table_comment(parent_table, marker_prefix=marker_prefix)
242244
lines = [marker]
243245

244246
parsed = parse_orphan_comment(existing_comment, marker_prefix=marker_prefix)
245-
if parsed is not None and parsed[1] is not None:
247+
if keep_instant and parsed is not None and parsed[1] is not None:
246248
detached_at = parsed[1]
247249
if detached_at is not None:
248250
lines.append(f"{DETACHED_AT_MARKER}{detached_at.astimezone(UTC).isoformat()}")

‎tests/integration/aio/test_foreign_keys.py‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,16 @@
88

99
from __future__ import annotations
1010

11-
from datetime import UTC, datetime
11+
from datetime import UTC, datetime, timedelta
1212
from typing import TYPE_CHECKING
1313

1414
import pytest
1515
import pytest_asyncio
1616

1717
from pg_partsmith.entities import MaintenanceIssueStep
18-
from pg_partsmith.lifecycle import AllOf, CreateAhead, ExpireIf, KeepNewest, LifecyclePolicy, Unreferenced
18+
from pg_partsmith.lifecycle import AllOf, CreateAhead, DropAfter, ExpireIf, KeepNewest, LifecyclePolicy, Unreferenced
1919
from pg_partsmith.topology import FactKind
20+
from pg_partsmith.utils import parse_orphan_comment
2021
from tests.integration.aio.support import (
2122
exec_sql,
2223
is_attached,
@@ -25,6 +26,7 @@
2526
range_children_of,
2627
run_maintenance,
2728
scalar,
29+
table_comment,
2830
)
2931
from tests.integration.nested_support import MONTHLY_TABLE_DDL, monthly_config
3032

@@ -158,3 +160,36 @@ async def test__without_unreferenced__refused_detach_is_an_issue_and_the_run_goe
158160
assert not await is_attached(db_engine, f"{events}__2026_07")
159161
assert set(await range_children_of(db_engine, events)) == {f"{events}__2026_06", f"{events}__2026_08"}
160162
assert await scalar(db_engine, f'SELECT count(*) FROM "{refs}"') == 1 # noqa: S608
163+
164+
165+
async def test__refused_detach__leaves_no_marker_and_the_later_detach_stamps_its_own_instant(
166+
db_engine: AsyncEngine, events: str, refs: str
167+
) -> None:
168+
"""A refused detach records no detach, so the drop grace counts from the detach that happens."""
169+
# Arrange -- June is referenced and carries a comment of its own; detached tables wait a month
170+
await _seed(db_engine, events, refs)
171+
june = f"{events}__2026_06"
172+
await exec_sql(db_engine, f"COMMENT ON TABLE \"{june}\" IS 'june archive'")
173+
config = monthly_config(
174+
events,
175+
lifecycle=LifecyclePolicy(
176+
creation=CreateAhead(count=1), retention=KeepNewest(count=1), drop=DropAfter(grace=timedelta(days=30))
177+
),
178+
)
179+
refused = await run_maintenance(db_engine, config, at_time="2026-08-26")
180+
comment_after_refusal = await table_comment(db_engine, june)
181+
182+
# Act -- the reference goes, and a run two days later detaches June
183+
await exec_sql(db_engine, f'DELETE FROM "{refs}"') # noqa: S608
184+
detached = await run_maintenance(db_engine, config, at_time="2026-08-28")
185+
186+
# Assert
187+
assert [issue.step for issue in refused.issues] == [MaintenanceIssueStep.DETACH]
188+
assert comment_after_refusal == "june archive"
189+
assert detached.detached_count == 1
190+
assert not await is_attached(db_engine, june)
191+
comment = await table_comment(db_engine, june)
192+
marker = parse_orphan_comment(comment)
193+
assert marker is not None
194+
assert marker[1] == datetime(2026, 8, 28, tzinfo=UTC)
195+
assert (comment or "").endswith("june archive")

0 commit comments

Comments
 (0)