Skip to content

Commit fd857b4

Browse files
AlexeyShalaevAlexey Shalaev
andauthored
fix: cancellation propagates from run_maintenance_safe (#110)
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 Co-authored-by: Alexey Shalaev <shalaevad.alexey@gmail.com>
1 parent dc79a7f commit fd857b4

13 files changed

Lines changed: 183 additions & 69 deletions

File tree

‎CHANGELOG.md‎

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

2727
* 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))
2828

29+
## 1.8.2 — cancellation stops a run_maintenance_safe
30+
31+
`run_maintenance_safe()` caught `asyncio.CancelledError`, `KeyboardInterrupt` and `SystemExit`
32+
and returned them on `result.error`, so the tools asyncio stops work with did nothing to it:
33+
`asyncio.timeout()` never raised, a cancelled task did not end cancelled, and a shutdown that
34+
cancels its tasks saw a completed run
35+
([#107](https://github.com/bedrock-python/pg-partsmith/issues/107)). They now propagate from
36+
both mirrors, after `run_maintenance()` has logged them; every `Exception` still lands on
37+
`result.error`.
38+
39+
A Redis lock whose lease is lost mid-run used to stop the run by cancelling it, and that
40+
cancellation was what reached `result.error`. The lock now takes its own cancellation back and
41+
raises `LockLostError`, a `PartitionError`, so a lost lease is still reported on the result. If
42+
the task was cancelled from outside at the same moment, the cancellation wins.
43+
2944
## 1.8.1 — the two findings survive a policy that reads facts
3045

3146
`unattached_rows` (1.7.0) and `rows_in_default` (1.8.0) went missing whenever the lifecycle

‎docs/agents.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -283,8 +283,10 @@ Every method takes the `TablePartitionConfig` as its first argument.
283283
| `drop_detached_partitions(config, partition_names)` | no | yes | `int` |
284284

285285
`maintain_lifecycle` is the same method as `maintain`. `PartitionMaintainer(service)` adds
286-
`run_maintenance(...)` and `run_maintenance_safe(...)` — same keywords; the *safe* one never
287-
raises and reports the failure on `result.error` instead, which is what a scheduler wants.
286+
`run_maintenance(...)` and `run_maintenance_safe(...)` — same keywords; the *safe* one does
287+
not raise errors and reports them on `result.error` instead, which is what a scheduler wants.
288+
Cancellation, `KeyboardInterrupt` and `SystemExit` propagate from both; a lost Redis lease is an
289+
error (`LockLostError`).
288290

289291
`PlanMode` is `MAINTAIN` (the tick), `RECONCILE` (converge only, create nothing ahead) or
290292
`EXPLICIT` (only the windows named in `windows=`).

‎docs/concepts/execution.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,12 @@ it takes on `op.capabilities`.
172172
| 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 |
173173
| validation or lock failure | fatal, always |
174174

175-
`PartitionMaintainer.run_maintenance_safe()` catches everything, cancellation included,
176-
and reports it on `result.error`.
175+
`PartitionMaintainer.run_maintenance_safe()` catches every error and reports it on
176+
`result.error`. A request to stop is not an error: `asyncio.CancelledError`,
177+
`KeyboardInterrupt` and `SystemExit` propagate, so `asyncio.timeout()`, `task.cancel()` and
178+
a shutdown that cancels its tasks behave as they do everywhere else. A Redis lock whose lease
179+
is lost mid-run stops the run with `LockLostError`, which is an error and lands on
180+
`result.error`.
177181

178182
## What an interruption leaves behind
179183

‎docs/getting-started/production.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ replicas from colliding, and a result you can alert on.
88
## 1. The maintainer
99

1010
`PartitionMaintainer` wraps the service for schedulers: `run_maintenance_safe()` plans and
11-
applies under the table's lock, times the run, and **never raises** — whatever happens
12-
comes back in the result.
11+
applies under the table's lock, times the run, and **does not raise errors** — whatever goes
12+
wrong comes back in the result. Cancellation is not an error and propagates.
1313

1414
```python
1515
from pg_partsmith.aio import PartitionMaintainer
@@ -225,8 +225,8 @@ assert not plan.actionable_findings, plan.describe()
225225

226226
## What you have learned
227227

228-
- `PartitionMaintainer.run_maintenance_safe()` is the entry point for a scheduler: it never
229-
raises, and everything is on the result.
228+
- `PartitionMaintainer.run_maintenance_safe()` is the entry point for a scheduler: errors come
229+
back on the result, and cancellation propagates.
230230
- One tick per table per replica; the loser of the lock skips, and that is fine.
231231
- `error` is the run, `issues` is what needs a human, `plan.findings` is the full account.
232232

‎docs/guide/scheduling.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ many places, and how to keep replicas from colliding.
66
## What to call
77

88
`PartitionMaintainer.run_maintenance_safe(config)` is the entry point for anything
9-
scheduled: it plans and applies under the table's lock and **never raises** — a failure
10-
comes back on `result.error`.
9+
scheduled: it plans and applies under the table's lock and **does not raise errors** — a
10+
failure comes back on `result.error`. Cancellation propagates (see [Cancellation](#cancellation)).
1111

1212
```python
1313
from pg_partsmith.aio import PartitionMaintainer
@@ -175,5 +175,8 @@ drop is revalidated against the catalog before it runs. The lock saves wasted wo
175175

176176
A run cancelled mid-way — a pod killed, a task cancelled — leaves at most a detached,
177177
unattached table (attach is the last step) or a marked, half-detached partition; the next
178-
tick converges both. `run_maintenance_safe()` reports the cancellation on `result.error`
179-
and returns normally; `run_maintenance()` re-raises it.
178+
tick converges both. Both `run_maintenance()` and `run_maintenance_safe()` let the
179+
cancellation propagate, after logging it, so a timeout around a run raises `TimeoutError`
180+
and a cancelled task ends cancelled. A lost Redis lease is the exception: the lock stops
181+
the run itself and reports it as `LockLostError`, which `run_maintenance_safe()` returns on
182+
`result.error`.

‎pg_partsmith/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
DropRetryExhaustedError,
3838
InvalidPartitionConfigError,
3939
LockAcquisitionError,
40+
LockLostError,
4041
PartitionAlreadyExistsError,
4142
PartitionAttachedError,
4243
PartitionDetachInProgressError,
@@ -167,6 +168,7 @@
167168
"ListPartitioning",
168169
"LocalLeaves",
169170
"LockAcquisitionError",
171+
"LockLostError",
170172
"MaintenanceIssue",
171173
"MaintenanceIssueStep",
172174
"MaintenancePlan",

‎pg_partsmith/aio/lock/redis.py‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
1717

1818
from pg_partsmith.constants import DEFAULT_LOCK_PREFIX
19-
from pg_partsmith.exceptions import LockAcquisitionError
19+
from pg_partsmith.exceptions import LockAcquisitionError, LockLostError
2020

2121
if TYPE_CHECKING:
2222
from collections.abc import AsyncIterator
@@ -77,7 +77,10 @@ class RedisDistributedLockManager:
7777
The renewal interval is ``ttl_seconds // 3`` (with random jitter to avoid
7878
thundering herds). If renewal fails — e.g. Redis is unreachable or another
7979
holder takes over — the watchdog logs a warning and cancels the holder
80-
task, forcing the maintenance run to stop (fail-safe).
80+
task, forcing the maintenance run to stop (fail-safe). The lock scope turns
81+
that cancellation into :class:`~pg_partsmith.exceptions.LockLostError`, so
82+
the run ends with an error rather than as if someone had cancelled it; a
83+
cancellation from outside still propagates as one.
8184
8285
For production use you may want to subclass and override ``acquire_lock``
8386
to use Redlock or another algorithm with stronger guarantees.
@@ -186,11 +189,20 @@ async def _lock_scope(self, table_name: str) -> AsyncIterator[None]:
186189
if holder_task is None:
187190
raise RuntimeError("Could not determine current asyncio task")
188191

192+
lost: list[str] = []
189193
watchdog = asyncio.create_task(
190-
self._renewal_watchdog(key, token, table_name, holder_task),
194+
self._renewal_watchdog(key, token, table_name, holder_task, lost),
191195
name=f"redis-lock-watchdog:{key}",
192196
)
193-
yield
197+
try:
198+
yield
199+
except asyncio.CancelledError:
200+
# The watchdog cancelled us because the lease went. When that is
201+
# the only cancellation pending, it is an error of the run, not a
202+
# request to stop: take it back and say what happened.
203+
if lost and holder_task.uncancel() == 0:
204+
raise LockLostError(table_name, lost[0]) from None
205+
raise
194206
finally:
195207
try:
196208
if watchdog is not None:
@@ -221,8 +233,9 @@ async def _renewal_watchdog(
221233
token: str,
222234
table_name: str,
223235
holder_task: asyncio.Task[Any],
236+
lost: list[str],
224237
) -> None:
225-
"""Periodically extend the lock TTL until cancelled or renewal fails."""
238+
"""Periodically extend the lock TTL until cancelled or renewal fails; ``lost`` gets the reason."""
226239
while True:
227240
jitter = random.uniform(*_RENEW_JITTER_RANGE) # noqa: S311
228241
await asyncio.sleep(self._renew_interval * jitter)
@@ -231,14 +244,14 @@ async def _renewal_watchdog(
231244
except (asyncio.CancelledError, KeyboardInterrupt, SystemExit):
232245
raise
233246
except (OSError, ConnectionError, TimeoutError, RuntimeError) as exc:
234-
self._fail_holder(holder_task, key, table_name, "recoverable error", exc)
247+
self._fail_holder(holder_task, key, table_name, "recoverable error", exc, lost)
235248
return
236249
except Exception as exc:
237-
self._fail_holder(holder_task, key, table_name, "unexpected exception", exc)
250+
self._fail_holder(holder_task, key, table_name, "unexpected exception", exc, lost)
238251
return
239252

240253
if not renewed:
241-
self._fail_holder(holder_task, key, table_name, "lock lost", None)
254+
self._fail_holder(holder_task, key, table_name, "lock lost", None, lost)
242255
return
243256

244257
def _fail_holder(
@@ -248,8 +261,9 @@ def _fail_holder(
248261
table_name: str,
249262
reason: str,
250263
exc: Exception | None,
264+
lost: list[str],
251265
) -> None:
252-
"""Log the renewal failure and cancel the holder task (fail-safe)."""
266+
"""Log the renewal failure, record why, and cancel the holder task (fail-safe)."""
253267
extra: dict[str, str] = {"table_name": table_name, "key": key, "reason": reason}
254268
if exc is not None:
255269
extra["error"] = str(exc)
@@ -264,6 +278,7 @@ def _fail_holder(
264278
extra=extra,
265279
)
266280
if not holder_task.done():
281+
lost.append(reason)
267282
holder_task.cancel()
268283

269284
async def _cancel_watchdog(self, watchdog: asyncio.Task[None]) -> None:

‎pg_partsmith/aio/maintainer.py‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -152,12 +152,15 @@ async def run_maintenance_safe(
152152
skip_drop: bool = False,
153153
continue_on_error: bool = False,
154154
) -> MaintenanceResult:
155-
"""Run maintenance and always return ``MaintenanceResult``, never raise.
155+
"""Run maintenance and return ``MaintenanceResult`` instead of raising an error.
156156
157-
Scheduler-friendly wrapper around :meth:`run_maintenance`. Any exception
158-
— including ``asyncio.CancelledError`` — is captured and reported via
159-
``result.error``; the ``duration_ms`` field always reflects the elapsed
160-
time even on failure.
157+
Scheduler-friendly wrapper around :meth:`run_maintenance`. Every
158+
``Exception`` is captured and reported via ``result.error``, a lost
159+
Redis lock included (``LockLostError``); ``duration_ms`` reflects the
160+
elapsed time even on failure. A request to stop is not an error:
161+
``asyncio.CancelledError``, ``KeyboardInterrupt`` and ``SystemExit``
162+
propagate, so ``asyncio.timeout()``, ``task.cancel()`` and a shutdown
163+
that cancels its tasks work as they do anywhere else.
161164
162165
Args:
163166
config: Table partitioning configuration.
@@ -179,8 +182,6 @@ async def run_maintenance_safe(
179182
skip_drop=skip_drop,
180183
continue_on_error=continue_on_error,
181184
)
182-
except (asyncio.CancelledError, KeyboardInterrupt, SystemExit) as e:
183-
return MaintenanceResult(duration_ms=elapsed_ms(start_time), error=describe_exception(e))
184185
except Exception as e:
185186
return MaintenanceResult(duration_ms=elapsed_ms(start_time), error=describe_exception(e))
186187

‎pg_partsmith/exceptions.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,21 @@ def __init__(self, table_name: str, reason: str | None = None) -> None:
115115
self.reason = reason
116116

117117

118+
class LockLostError(PartitionError):
119+
"""Raised when a held lock is lost mid-run and the run is stopped because of it.
120+
121+
The Redis lock renews its lease while a run holds it; when a renewal fails
122+
or finds another holder, the run cannot go on safely and is stopped. This
123+
is that stop, reported as an error of the run rather than as a cancellation
124+
nobody asked for.
125+
"""
126+
127+
def __init__(self, table_name: str, reason: str) -> None:
128+
super().__init__(f"Lost the lock for table {table_name} mid-run: {reason}")
129+
self.table_name = table_name
130+
self.reason = reason
131+
132+
118133
class DropRetryExhaustedError(PartitionError):
119134
"""Raised when all drop_partition retry attempts are exhausted.
120135

‎pg_partsmith/sync/maintainer.py‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -151,12 +151,13 @@ def run_maintenance_safe(
151151
skip_drop: bool = False,
152152
continue_on_error: bool = False,
153153
) -> MaintenanceResult:
154-
"""Run maintenance and always return ``MaintenanceResult``, never raise.
154+
"""Run maintenance and return ``MaintenanceResult`` instead of raising an error.
155155
156-
Scheduler-friendly wrapper around :meth:`run_maintenance`. Any exception
157-
— including ``KeyboardInterrupt`` — is captured and reported via
158-
``result.error``; the ``duration_ms`` field always reflects the elapsed
159-
time even on failure.
156+
Scheduler-friendly wrapper around :meth:`run_maintenance`. Every
157+
``Exception`` is captured and reported via ``result.error``;
158+
``duration_ms`` reflects the elapsed time even on failure. A request to
159+
stop is not an error: ``KeyboardInterrupt`` and ``SystemExit``
160+
propagate, so Ctrl+C and ``sys.exit()`` end the process as usual.
160161
161162
Args:
162163
config: Table partitioning configuration.
@@ -178,8 +179,6 @@ def run_maintenance_safe(
178179
skip_drop=skip_drop,
179180
continue_on_error=continue_on_error,
180181
)
181-
except (KeyboardInterrupt, SystemExit) as e:
182-
return MaintenanceResult(duration_ms=elapsed_ms(start_time), error=describe_exception(e))
183182
except Exception as e:
184183
return MaintenanceResult(duration_ms=elapsed_ms(start_time), error=describe_exception(e))
185184

0 commit comments

Comments
 (0)