From 008457d2ced46cb1ba9a7ed3579f4bc8af7055fa Mon Sep 17 00:00:00 2001 From: Alexey Shalaev Date: Fri, 16 Oct 2026 18:37:31 +0400 Subject: [PATCH] fix: cancellation propagates from run_maintenance_safe run_maintenance_safe caught CancelledError, KeyboardInterrupt and SystemExit and returned them on result.error, so asyncio.timeout() never fired, a cancelled task did not end cancelled, and Ctrl+C in the sync mirror was swallowed. They now propagate from both mirrors; every Exception still lands on result.error. The Redis lock stops a run whose lease it lost by cancelling it. It now takes that cancellation back and raises LockLostError, so a lost lease is still reported on the result; a cancellation from outside at the same time still propagates. Closes #107 --- CHANGELOG.md | 15 ++++++++ docs/agents.md | 6 ++- docs/concepts/execution.md | 8 +++- docs/getting-started/production.md | 8 ++-- docs/guide/scheduling.md | 11 ++++-- pg_partsmith/__init__.py | 2 + pg_partsmith/aio/lock/redis.py | 33 ++++++++++++----- pg_partsmith/aio/maintainer.py | 15 ++++---- pg_partsmith/exceptions.py | 15 ++++++++ pg_partsmith/sync/maintainer.py | 13 +++---- tests/unit/sync/test_maintainer.py | 17 +++------ tests/unit/test_locks.py | 50 ++++++++++++++++++++++++- tests/unit/test_maintainer.py | 59 +++++++++++++++++++----------- 13 files changed, 183 insertions(+), 69 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b01e830..1bebd38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * 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)) +## 1.8.2 — cancellation stops a run_maintenance_safe + +`run_maintenance_safe()` caught `asyncio.CancelledError`, `KeyboardInterrupt` and `SystemExit` +and returned them on `result.error`, so the tools asyncio stops work with did nothing to it: +`asyncio.timeout()` never raised, a cancelled task did not end cancelled, and a shutdown that +cancels its tasks saw a completed run +([#107](https://github.com/bedrock-python/pg-partsmith/issues/107)). They now propagate from +both mirrors, after `run_maintenance()` has logged them; every `Exception` still lands on +`result.error`. + +A Redis lock whose lease is lost mid-run used to stop the run by cancelling it, and that +cancellation was what reached `result.error`. The lock now takes its own cancellation back and +raises `LockLostError`, a `PartitionError`, so a lost lease is still reported on the result. If +the task was cancelled from outside at the same moment, the cancellation wins. + ## 1.8.1 — the two findings survive a policy that reads facts `unattached_rows` (1.7.0) and `rows_in_default` (1.8.0) went missing whenever the lifecycle diff --git a/docs/agents.md b/docs/agents.md index 0b7ff70..57f9ce0 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -283,8 +283,10 @@ Every method takes the `TablePartitionConfig` as its first argument. | `drop_detached_partitions(config, partition_names)` | no | yes | `int` | `maintain_lifecycle` is the same method as `maintain`. `PartitionMaintainer(service)` adds -`run_maintenance(...)` and `run_maintenance_safe(...)` — same keywords; the *safe* one never -raises and reports the failure on `result.error` instead, which is what a scheduler wants. +`run_maintenance(...)` and `run_maintenance_safe(...)` — same keywords; the *safe* one does +not raise errors and reports them on `result.error` instead, which is what a scheduler wants. +Cancellation, `KeyboardInterrupt` and `SystemExit` propagate from both; a lost Redis lease is an +error (`LockLostError`). `PlanMode` is `MAINTAIN` (the tick), `RECONCILE` (converge only, create nothing ahead) or `EXPLICIT` (only the windows named in `windows=`). diff --git a/docs/concepts/execution.md b/docs/concepts/execution.md index 02a0d07..df03c0e 100644 --- a/docs/concepts/execution.md +++ b/docs/concepts/execution.md @@ -172,8 +172,12 @@ it takes on `op.capabilities`. | any other error — a connection drop, a permission denied, a `before_*` hook raising | aborts the run, unless `continue_on_error`, in which case it is recorded and the next operation runs | | validation or lock failure | fatal, always | -`PartitionMaintainer.run_maintenance_safe()` catches everything, cancellation included, -and reports it on `result.error`. +`PartitionMaintainer.run_maintenance_safe()` catches every error and reports it on +`result.error`. A request to stop is not an error: `asyncio.CancelledError`, +`KeyboardInterrupt` and `SystemExit` propagate, so `asyncio.timeout()`, `task.cancel()` and +a shutdown that cancels its tasks behave as they do everywhere else. A Redis lock whose lease +is lost mid-run stops the run with `LockLostError`, which is an error and lands on +`result.error`. ## What an interruption leaves behind diff --git a/docs/getting-started/production.md b/docs/getting-started/production.md index 0f1456f..c22b863 100644 --- a/docs/getting-started/production.md +++ b/docs/getting-started/production.md @@ -8,8 +8,8 @@ replicas from colliding, and a result you can alert on. ## 1. The maintainer `PartitionMaintainer` wraps the service for schedulers: `run_maintenance_safe()` plans and -applies under the table's lock, times the run, and **never raises** — whatever happens -comes back in the result. +applies under the table's lock, times the run, and **does not raise errors** — whatever goes +wrong comes back in the result. Cancellation is not an error and propagates. ```python from pg_partsmith.aio import PartitionMaintainer @@ -225,8 +225,8 @@ assert not plan.actionable_findings, plan.describe() ## What you have learned -- `PartitionMaintainer.run_maintenance_safe()` is the entry point for a scheduler: it never - raises, and everything is on the result. +- `PartitionMaintainer.run_maintenance_safe()` is the entry point for a scheduler: errors come + back on the result, and cancellation propagates. - One tick per table per replica; the loser of the lock skips, and that is fine. - `error` is the run, `issues` is what needs a human, `plan.findings` is the full account. diff --git a/docs/guide/scheduling.md b/docs/guide/scheduling.md index 0a6443a..747ca8e 100644 --- a/docs/guide/scheduling.md +++ b/docs/guide/scheduling.md @@ -6,8 +6,8 @@ many places, and how to keep replicas from colliding. ## What to call `PartitionMaintainer.run_maintenance_safe(config)` is the entry point for anything -scheduled: it plans and applies under the table's lock and **never raises** — a failure -comes back on `result.error`. +scheduled: it plans and applies under the table's lock and **does not raise errors** — a +failure comes back on `result.error`. Cancellation propagates (see [Cancellation](#cancellation)). ```python from pg_partsmith.aio import PartitionMaintainer @@ -175,5 +175,8 @@ drop is revalidated against the catalog before it runs. The lock saves wasted wo A run cancelled mid-way — a pod killed, a task cancelled — leaves at most a detached, unattached table (attach is the last step) or a marked, half-detached partition; the next -tick converges both. `run_maintenance_safe()` reports the cancellation on `result.error` -and returns normally; `run_maintenance()` re-raises it. +tick converges both. Both `run_maintenance()` and `run_maintenance_safe()` let the +cancellation propagate, after logging it, so a timeout around a run raises `TimeoutError` +and a cancelled task ends cancelled. A lost Redis lease is the exception: the lock stops +the run itself and reports it as `LockLostError`, which `run_maintenance_safe()` returns on +`result.error`. diff --git a/pg_partsmith/__init__.py b/pg_partsmith/__init__.py index d5ea51b..2a70367 100644 --- a/pg_partsmith/__init__.py +++ b/pg_partsmith/__init__.py @@ -37,6 +37,7 @@ DropRetryExhaustedError, InvalidPartitionConfigError, LockAcquisitionError, + LockLostError, PartitionAlreadyExistsError, PartitionAttachedError, PartitionDetachInProgressError, @@ -167,6 +168,7 @@ "ListPartitioning", "LocalLeaves", "LockAcquisitionError", + "LockLostError", "MaintenanceIssue", "MaintenanceIssueStep", "MaintenancePlan", diff --git a/pg_partsmith/aio/lock/redis.py b/pg_partsmith/aio/lock/redis.py index 2f18e85..57213a0 100644 --- a/pg_partsmith/aio/lock/redis.py +++ b/pg_partsmith/aio/lock/redis.py @@ -16,7 +16,7 @@ from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable from pg_partsmith.constants import DEFAULT_LOCK_PREFIX -from pg_partsmith.exceptions import LockAcquisitionError +from pg_partsmith.exceptions import LockAcquisitionError, LockLostError if TYPE_CHECKING: from collections.abc import AsyncIterator @@ -77,7 +77,10 @@ class RedisDistributedLockManager: The renewal interval is ``ttl_seconds // 3`` (with random jitter to avoid thundering herds). If renewal fails — e.g. Redis is unreachable or another holder takes over — the watchdog logs a warning and cancels the holder - task, forcing the maintenance run to stop (fail-safe). + task, forcing the maintenance run to stop (fail-safe). The lock scope turns + that cancellation into :class:`~pg_partsmith.exceptions.LockLostError`, so + the run ends with an error rather than as if someone had cancelled it; a + cancellation from outside still propagates as one. For production use you may want to subclass and override ``acquire_lock`` to use Redlock or another algorithm with stronger guarantees. @@ -186,11 +189,20 @@ async def _lock_scope(self, table_name: str) -> AsyncIterator[None]: if holder_task is None: raise RuntimeError("Could not determine current asyncio task") + lost: list[str] = [] watchdog = asyncio.create_task( - self._renewal_watchdog(key, token, table_name, holder_task), + self._renewal_watchdog(key, token, table_name, holder_task, lost), name=f"redis-lock-watchdog:{key}", ) - yield + try: + yield + except asyncio.CancelledError: + # The watchdog cancelled us because the lease went. When that is + # the only cancellation pending, it is an error of the run, not a + # request to stop: take it back and say what happened. + if lost and holder_task.uncancel() == 0: + raise LockLostError(table_name, lost[0]) from None + raise finally: try: if watchdog is not None: @@ -221,8 +233,9 @@ async def _renewal_watchdog( token: str, table_name: str, holder_task: asyncio.Task[Any], + lost: list[str], ) -> None: - """Periodically extend the lock TTL until cancelled or renewal fails.""" + """Periodically extend the lock TTL until cancelled or renewal fails; ``lost`` gets the reason.""" while True: jitter = random.uniform(*_RENEW_JITTER_RANGE) # noqa: S311 await asyncio.sleep(self._renew_interval * jitter) @@ -231,14 +244,14 @@ async def _renewal_watchdog( except (asyncio.CancelledError, KeyboardInterrupt, SystemExit): raise except (OSError, ConnectionError, TimeoutError, RuntimeError) as exc: - self._fail_holder(holder_task, key, table_name, "recoverable error", exc) + self._fail_holder(holder_task, key, table_name, "recoverable error", exc, lost) return except Exception as exc: - self._fail_holder(holder_task, key, table_name, "unexpected exception", exc) + self._fail_holder(holder_task, key, table_name, "unexpected exception", exc, lost) return if not renewed: - self._fail_holder(holder_task, key, table_name, "lock lost", None) + self._fail_holder(holder_task, key, table_name, "lock lost", None, lost) return def _fail_holder( @@ -248,8 +261,9 @@ def _fail_holder( table_name: str, reason: str, exc: Exception | None, + lost: list[str], ) -> None: - """Log the renewal failure and cancel the holder task (fail-safe).""" + """Log the renewal failure, record why, and cancel the holder task (fail-safe).""" extra: dict[str, str] = {"table_name": table_name, "key": key, "reason": reason} if exc is not None: extra["error"] = str(exc) @@ -264,6 +278,7 @@ def _fail_holder( extra=extra, ) if not holder_task.done(): + lost.append(reason) holder_task.cancel() async def _cancel_watchdog(self, watchdog: asyncio.Task[None]) -> None: diff --git a/pg_partsmith/aio/maintainer.py b/pg_partsmith/aio/maintainer.py index 1dde736..22dcd0c 100644 --- a/pg_partsmith/aio/maintainer.py +++ b/pg_partsmith/aio/maintainer.py @@ -152,12 +152,15 @@ async def run_maintenance_safe( skip_drop: bool = False, continue_on_error: bool = False, ) -> MaintenanceResult: - """Run maintenance and always return ``MaintenanceResult``, never raise. + """Run maintenance and return ``MaintenanceResult`` instead of raising an error. - Scheduler-friendly wrapper around :meth:`run_maintenance`. Any exception - — including ``asyncio.CancelledError`` — is captured and reported via - ``result.error``; the ``duration_ms`` field always reflects the elapsed - time even on failure. + Scheduler-friendly wrapper around :meth:`run_maintenance`. Every + ``Exception`` is captured and reported via ``result.error``, a lost + Redis lock included (``LockLostError``); ``duration_ms`` reflects the + elapsed time even on failure. A request to stop is not an error: + ``asyncio.CancelledError``, ``KeyboardInterrupt`` and ``SystemExit`` + propagate, so ``asyncio.timeout()``, ``task.cancel()`` and a shutdown + that cancels its tasks work as they do anywhere else. Args: config: Table partitioning configuration. @@ -179,8 +182,6 @@ async def run_maintenance_safe( skip_drop=skip_drop, continue_on_error=continue_on_error, ) - except (asyncio.CancelledError, KeyboardInterrupt, SystemExit) as e: - return MaintenanceResult(duration_ms=elapsed_ms(start_time), error=describe_exception(e)) except Exception as e: return MaintenanceResult(duration_ms=elapsed_ms(start_time), error=describe_exception(e)) diff --git a/pg_partsmith/exceptions.py b/pg_partsmith/exceptions.py index bbf49b1..13f8477 100644 --- a/pg_partsmith/exceptions.py +++ b/pg_partsmith/exceptions.py @@ -115,6 +115,21 @@ def __init__(self, table_name: str, reason: str | None = None) -> None: self.reason = reason +class LockLostError(PartitionError): + """Raised when a held lock is lost mid-run and the run is stopped because of it. + + The Redis lock renews its lease while a run holds it; when a renewal fails + or finds another holder, the run cannot go on safely and is stopped. This + is that stop, reported as an error of the run rather than as a cancellation + nobody asked for. + """ + + def __init__(self, table_name: str, reason: str) -> None: + super().__init__(f"Lost the lock for table {table_name} mid-run: {reason}") + self.table_name = table_name + self.reason = reason + + class DropRetryExhaustedError(PartitionError): """Raised when all drop_partition retry attempts are exhausted. diff --git a/pg_partsmith/sync/maintainer.py b/pg_partsmith/sync/maintainer.py index 59292cb..36091e8 100644 --- a/pg_partsmith/sync/maintainer.py +++ b/pg_partsmith/sync/maintainer.py @@ -151,12 +151,13 @@ def run_maintenance_safe( skip_drop: bool = False, continue_on_error: bool = False, ) -> MaintenanceResult: - """Run maintenance and always return ``MaintenanceResult``, never raise. + """Run maintenance and return ``MaintenanceResult`` instead of raising an error. - Scheduler-friendly wrapper around :meth:`run_maintenance`. Any exception - — including ``KeyboardInterrupt`` — is captured and reported via - ``result.error``; the ``duration_ms`` field always reflects the elapsed - time even on failure. + Scheduler-friendly wrapper around :meth:`run_maintenance`. Every + ``Exception`` is captured and reported via ``result.error``; + ``duration_ms`` reflects the elapsed time even on failure. A request to + stop is not an error: ``KeyboardInterrupt`` and ``SystemExit`` + propagate, so Ctrl+C and ``sys.exit()`` end the process as usual. Args: config: Table partitioning configuration. @@ -178,8 +179,6 @@ def run_maintenance_safe( skip_drop=skip_drop, continue_on_error=continue_on_error, ) - except (KeyboardInterrupt, SystemExit) as e: - return MaintenanceResult(duration_ms=elapsed_ms(start_time), error=describe_exception(e)) except Exception as e: return MaintenanceResult(duration_ms=elapsed_ms(start_time), error=describe_exception(e)) diff --git a/tests/unit/sync/test_maintainer.py b/tests/unit/sync/test_maintainer.py index 5d10c39..2d82a2d 100644 --- a/tests/unit/sync/test_maintainer.py +++ b/tests/unit/sync/test_maintainer.py @@ -284,21 +284,14 @@ def test__run_maintenance_safe__service_raises__returns_failure_result(config: T @pytest.mark.parametrize("error", [KeyboardInterrupt("operator interrupted run"), SystemExit(1)]) -def test__run_maintenance_safe__system_signal__returns_failure_result( - config: TablePartitionConfig, error: BaseException -) -> None: - # Arrange -- the sync analog of a cancelled task: captured into ``result.error`` +def test__run_maintenance_safe__request_to_stop__propagates(config: TablePartitionConfig, error: BaseException) -> None: + # Arrange service = _make_service(side_effect=error) maintainer = PartitionMaintainer(service) - # Act - result = maintainer.run_maintenance_safe(config) - - # Assert - assert result.success is False - assert result.error is not None - assert type(error).__name__ in result.error - assert result.duration_ms >= 0 + # Act / Assert + with pytest.raises(type(error)): + maintainer.run_maintenance_safe(config) # ── maintain_partitions ───────────────────────────────────────────────────────── diff --git a/tests/unit/test_locks.py b/tests/unit/test_locks.py index 8ed4fa4..a9762dd 100644 --- a/tests/unit/test_locks.py +++ b/tests/unit/test_locks.py @@ -7,7 +7,7 @@ from pg_partsmith.aio.lock.postgres import PostgresAdvisoryLockManager from pg_partsmith.aio.lock.redis import RedisDistributedLockManager -from pg_partsmith.exceptions import LockAcquisitionError +from pg_partsmith.exceptions import LockAcquisitionError, LockLostError # ── helpers ───────────────────────────────────────────────────────────────────── @@ -527,6 +527,54 @@ async def task_body() -> str: assert logger.warning.call_args.kwargs["extra"]["table_name"] == "test" +def _lease_lost_manager() -> RedisDistributedLockManager: + redis = MagicMock() + redis.set = AsyncMock(return_value=True) + redis.register_script.side_effect = [AsyncMock(return_value=1), AsyncMock(return_value=0)] # unlock, renew + with patch("pg_partsmith.aio.lock.redis._redis_available", True): + return RedisDistributedLockManager(redis, ttl_seconds=3) + + +async def test__redis_lock__lease_lost__the_run_ends_with_lock_lost_error_not_a_cancellation() -> None: + # Arrange + manager = _lease_lost_manager() + + # Act + with pytest.raises(LockLostError, match="lock lost"): + async with manager.acquire_lock("test"): + await asyncio.sleep(5) + + # Assert -- the cancellation the lock caused was taken back + task = asyncio.current_task() + assert task is not None + assert task.cancelling() == 0 + + +async def test__redis_lock__lease_lost_and_cancelled_from_outside__the_cancellation_wins() -> None: + # Arrange -- someone else cancels the task in the same moment the lease goes + manager = _lease_lost_manager() + original = RedisDistributedLockManager._fail_holder + + def fail_and_cancel_from_outside( + self: RedisDistributedLockManager, holder_task: asyncio.Task[object], *args: object + ) -> None: + original(self, holder_task, *args) # type: ignore[arg-type] + holder_task.cancel() + + async def hold() -> None: + async with manager.acquire_lock("test"): + await asyncio.sleep(5) + + # Act + with patch.object(RedisDistributedLockManager, "_fail_holder", fail_and_cancel_from_outside): + task = asyncio.create_task(hold()) + with pytest.raises(asyncio.CancelledError): + await task + + # Assert + assert task.cancelled() + + async def test__redis_lock__unlock_raises__logs_warning_without_reraise() -> None: # Arrange redis = MagicMock() diff --git a/tests/unit/test_maintainer.py b/tests/unit/test_maintainer.py index febcc49..ac1fe14 100644 --- a/tests/unit/test_maintainer.py +++ b/tests/unit/test_maintainer.py @@ -281,36 +281,53 @@ async def test__run_maintenance_safe__service_raises__returns_failure_result(con assert result.duration_ms >= 0 -async def test__run_maintenance_safe__cancelled_error__returns_failure_result(config: TablePartitionConfig) -> None: +@pytest.mark.parametrize( + "error", [asyncio.CancelledError("stop"), KeyboardInterrupt("operator interrupted"), SystemExit(1)] +) +async def test__run_maintenance_safe__request_to_stop__propagates( + config: TablePartitionConfig, error: BaseException +) -> None: # Arrange - service = _make_service(side_effect=asyncio.CancelledError("lock watchdog cancelled run")) + service = _make_service(side_effect=error) maintainer = PartitionMaintainer(service) - # Act - result = await maintainer.run_maintenance_safe(config) + # Act / Assert + with pytest.raises(type(error)): + await maintainer.run_maintenance_safe(config) - # Assert - assert result.success is False - assert result.error is not None - assert "CancelledError" in result.error - assert result.duration_ms >= 0 +def _slow_service() -> MagicMock: + async def maintain_lifecycle(*_args: object, **_kwargs: object) -> MaintenanceResult: + await asyncio.sleep(5) + return MaintenanceResult() -@pytest.mark.parametrize("error", [KeyboardInterrupt("operator interrupted"), SystemExit(1)]) -async def test__run_maintenance_safe__system_signal__returns_failure_result( - config: TablePartitionConfig, error: BaseException -) -> None: + service = MagicMock() + service.maintain_lifecycle = maintain_lifecycle + return service + + +async def test__run_maintenance_safe__inside_asyncio_timeout__the_timeout_fires(config: TablePartitionConfig) -> None: # Arrange - service = _make_service(side_effect=error) - maintainer = PartitionMaintainer(service) + maintainer = PartitionMaintainer(_slow_service()) + + # Act / Assert + with pytest.raises(TimeoutError): + async with asyncio.timeout(0.05): + await maintainer.run_maintenance_safe(config) + + +async def test__run_maintenance_safe__task_cancelled__the_task_ends_cancelled(config: TablePartitionConfig) -> None: + # Arrange + task = asyncio.create_task(PartitionMaintainer(_slow_service()).run_maintenance_safe(config)) + await asyncio.sleep(0.05) # Act - result = await maintainer.run_maintenance_safe(config) + task.cancel() # Assert - assert result.success is False - assert result.error is not None - assert type(error).__name__ in result.error + with pytest.raises(asyncio.CancelledError): + await task + assert task.cancelled() async def test__run_maintenance_safe__redis_watchdog_cancels_task__returns_failure_result( @@ -337,10 +354,10 @@ async def maintain_lifecycle(self, *_args: object, **_kwargs: object) -> Mainten # Act result = await maintainer.run_maintenance_safe(config) - # Assert + # Assert -- the lost lease ends the run as an error of the run, not as a cancellation assert result.success is False assert result.error is not None - assert "CancelledError" in result.error + assert result.error.startswith("LockLostError") assert unlock_script.called