Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=`).
Expand Down
8 changes: 6 additions & 2 deletions docs/concepts/execution.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 4 additions & 4 deletions docs/getting-started/production.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down
11 changes: 7 additions & 4 deletions docs/guide/scheduling.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`.
2 changes: 2 additions & 0 deletions pg_partsmith/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
DropRetryExhaustedError,
InvalidPartitionConfigError,
LockAcquisitionError,
LockLostError,
PartitionAlreadyExistsError,
PartitionAttachedError,
PartitionDetachInProgressError,
Expand Down Expand Up @@ -167,6 +168,7 @@
"ListPartitioning",
"LocalLeaves",
"LockAcquisitionError",
"LockLostError",
"MaintenanceIssue",
"MaintenanceIssueStep",
"MaintenancePlan",
Expand Down
33 changes: 24 additions & 9 deletions pg_partsmith/aio/lock/redis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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(
Expand All @@ -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)
Expand All @@ -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:
Expand Down
15 changes: 8 additions & 7 deletions pg_partsmith/aio/maintainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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))

Expand Down
15 changes: 15 additions & 0 deletions pg_partsmith/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
13 changes: 6 additions & 7 deletions pg_partsmith/sync/maintainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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))

Expand Down
17 changes: 5 additions & 12 deletions tests/unit/sync/test_maintainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ─────────────────────────────────────────────────────────
Expand Down
50 changes: 49 additions & 1 deletion tests/unit/test_locks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ─────────────────────────────────────────────────────────────────────

Expand Down Expand Up @@ -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()
Expand Down
Loading
Loading