diff --git a/docs/dependency-injection.md b/docs/dependency-injection.md index d92f3bc4..6bf3907b 100644 --- a/docs/dependency-injection.md +++ b/docs/dependency-injection.md @@ -581,6 +581,12 @@ async def audited_task( ``` +### Subclassing the built-in behaviors + +You can also subclass a built-in behavior to change one part of it: override `handle_failure` on `Retry`, `on_complete` on `Perpetual` or `Cron`, or `run` on `Timeout`. The task receives an instance of your subclass, and the worker calls your overrides. See [Custom Retry Policies](task-behaviors.md#custom-retry-policies) for an example. + +Each execution works with a shallow copy of the instance you declared, so your subclass's constructor may take any arguments, and attributes it sets are available on the copy. `ConcurrencyLimit`, `Cooldown`, `RateLimit`, and `Debounce` are copied the same way when they are bound to a parameter through `Annotated`. + ## Worker-level dependencies Sometimes you want a dependency to run around **every** task a worker diff --git a/docs/task-behaviors.md b/docs/task-behaviors.md index 96e6fe2e..644ec748 100644 --- a/docs/task-behaviors.md +++ b/docs/task-behaviors.md @@ -256,6 +256,61 @@ async def call_flaky_api( You can also pass `attempts=None` directly, which is equivalent. +### Retries with Perpetual and Cron + +A task can declare a retry alongside `Perpetual` or `Cron`. The retry applies within one run: a run that fails is retried until it succeeds or its attempts are used up, and only then is the next run scheduled. Each run starts again at attempt 1, so a task that always fails makes `attempts` attempts in every run. + +```python +async def hourly_sync( + perpetual: Perpetual = Perpetual(every=timedelta(hours=1)), + retry: Retry = Retry(attempts=3, delay=timedelta(seconds=30)), +) -> None: + # Up to 3 attempts per run, 30 seconds apart; the next run is scheduled + # an hour after the last attempt started + await sync_external_data() +``` + +Exhausted retries never stop the cycle. A task that should stop rescheduling itself once its retries run out calls `perpetual.cancel()` on its last attempt: + +```python +async def sync_until_it_fails( + perpetual: Perpetual = Perpetual(every=timedelta(hours=1)), + retry: Retry = Retry(attempts=3, delay=timedelta(seconds=30)), +) -> None: + try: + await sync_external_data() + except Exception: + if retry.attempt == retry.attempts: + perpetual.cancel() + raise +``` + +Each attempt receives its own `Perpetual`, so `cancel()`, `perpetuate()`, `after()`, and `at()` take effect only on the attempt that ends the run; a call on an attempt that is retried is discarded. For an automatic task `cancel()` only pauses it until a worker next adds it, so use `docket.strike()` to stop one durably. + +### Custom Retry Policies + +To decide for yourself which failures are retried, subclass `Retry` or `ExponentialRetry` and override `handle_failure`. Return `False` to let the task fail, or call the base method to retry as usual: + +```python +from docket import Retry +from docket.dependencies import TaskOutcome +from docket.execution import Execution + +class RetryUnlessInvalid(Retry): + async def handle_failure(self, execution: Execution, outcome: TaskOutcome) -> bool: + if isinstance(outcome.exception, ValueError): + return False + return await super().handle_failure(execution, outcome) + +async def import_record( + record_id: str, + retry: Retry = RetryUnlessInvalid(attempts=5), +) -> None: + await import_from_source(record_id) +``` + +Each attempt receives a shallow copy of the retry the task declared, with `attempt` set, so attributes a subclass sets in its constructor are available in the task and in `handle_failure`. An attribute that an attempt assigns on its copy is not carried to the next attempt, which may run on another worker; keep a count that must outlast one attempt in Redis or another store. A mutable attribute such as a list is the same object in every copy, so do not use one for per-attempt state. + ## Task Timeouts Prevent tasks from running too long with the `Timeout` dependency: diff --git a/python/src/docket/dependencies/_concurrency.py b/python/src/docket/dependencies/_concurrency.py index 8d253c52..281a0c2a 100644 --- a/python/src/docket/dependencies/_concurrency.py +++ b/python/src/docket/dependencies/_concurrency.py @@ -3,11 +3,12 @@ from __future__ import annotations import asyncio +import copy import json import logging from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone -from typing import TYPE_CHECKING, Any, AsyncIterator, overload +from typing import TYPE_CHECKING, Any, AsyncIterator, Self, overload from opentelemetry import propagate @@ -199,16 +200,14 @@ def __init__( self._renewal_task: asyncio.Task[None] | None = None self._redelivery_timeout: timedelta | None = None - def bind_to_parameter(self, name: str, value: Any) -> ConcurrencyLimit: + def bind_to_parameter(self, name: str, value: Any) -> Self: """Bind to an ``Annotated`` parameter, inferring argument_name if not set.""" - argument_name = self.argument_name if self.argument_name is not None else name - return ConcurrencyLimit( - argument_name, - max_concurrent=self.max_concurrent, - scope=self.scope, - ) + bound = copy.copy(self) + if bound.argument_name is None: + bound.argument_name = name + return bound - async def __aenter__(self) -> ConcurrencyLimit: + async def __aenter__(self) -> Self: from ._functional import _Depends execution = current_execution.get() @@ -245,10 +244,11 @@ async def __aenter__(self) -> ConcurrencyLimit: else: concurrency_key = f"{scope}:concurrency:{execution.function_name}" - # Create a NEW instance for this specific task execution. The - # original (the default parameter value) is shared across all calls, - # so its attributes must not be mutated. - limit = ConcurrencyLimit(self.argument_name, self.max_concurrent, self.scope) + # Copy the instance for this specific task execution. The original + # (the default parameter value) is shared across all calls, so its + # attributes must not be mutated. Copying keeps a subclass and its + # state without calling its constructor. + limit = copy.copy(self) limit._concurrency_key = concurrency_key limit._initialized = True limit._task_key = execution.key diff --git a/python/src/docket/dependencies/_cooldown.py b/python/src/docket/dependencies/_cooldown.py index b72d22c8..83001cfb 100644 --- a/python/src/docket/dependencies/_cooldown.py +++ b/python/src/docket/dependencies/_cooldown.py @@ -6,9 +6,10 @@ from __future__ import annotations +import copy from datetime import timedelta from types import TracebackType -from typing import Any +from typing import Any, Self from ._base import AdmissionBlocked, Dependency, current_docket, current_execution @@ -38,8 +39,8 @@ def __init__(self, window: timedelta, *, scope: str | None = None) -> None: self._argument_name: str | None = None self._argument_value: Any = None - def bind_to_parameter(self, name: str, value: Any) -> Cooldown: - bound = Cooldown(self.window, scope=self.scope) + def bind_to_parameter(self, name: str, value: Any) -> Self: + bound = copy.copy(self) bound._argument_name = name bound._argument_value = value return bound diff --git a/python/src/docket/dependencies/_cron.py b/python/src/docket/dependencies/_cron.py index 63c11b24..d44ce250 100644 --- a/python/src/docket/dependencies/_cron.py +++ b/python/src/docket/dependencies/_cron.py @@ -3,11 +3,10 @@ from __future__ import annotations from datetime import datetime, timezone, tzinfo -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Self from cronsim import CronSim -from ._base import current_execution from ._perpetual import Perpetual if TYPE_CHECKING: # pragma: no cover @@ -88,11 +87,12 @@ def __init__( self.tz = tz self._iterator = CronSim(self.expression, datetime.now(self.tz)) - async def __aenter__(self) -> Cron: - execution = current_execution.get() - cron = Cron(expression=self.expression, automatic=self.automatic, tz=self.tz) - cron.args = execution.args - cron.kwargs = execution.kwargs + async def __aenter__(self) -> Self: + cron = await super().__aenter__() + # The copy shares the declared instance's iterator, which counts from + # when the task was declared and advances on every read. Each run + # needs the next match after its own start. + cron._iterator = CronSim(self.expression, datetime.now(self.tz)) return cron def next_time(self) -> datetime: diff --git a/python/src/docket/dependencies/_debounce.py b/python/src/docket/dependencies/_debounce.py index 101fb8ca..437cca56 100644 --- a/python/src/docket/dependencies/_debounce.py +++ b/python/src/docket/dependencies/_debounce.py @@ -7,10 +7,11 @@ from __future__ import annotations +import copy import time from datetime import timedelta from types import TracebackType -from typing import Any +from typing import Any, Self from .._lua import Arg, Key, redis_script from .._redis import RedisClient @@ -62,8 +63,8 @@ def __init__(self, settle: timedelta, *, scope: str | None = None) -> None: self._argument_name: str | None = None self._argument_value: Any = None - def bind_to_parameter(self, name: str, value: Any) -> Debounce: - bound = Debounce(self.settle, scope=self.scope) + def bind_to_parameter(self, name: str, value: Any) -> Self: + bound = copy.copy(self) bound._argument_name = name bound._argument_value = value return bound diff --git a/python/src/docket/dependencies/_perpetual.py b/python/src/docket/dependencies/_perpetual.py index 1c456353..6b654498 100644 --- a/python/src/docket/dependencies/_perpetual.py +++ b/python/src/docket/dependencies/_perpetual.py @@ -2,9 +2,10 @@ from __future__ import annotations +import copy import logging from datetime import datetime, timedelta, timezone -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Self from ._base import ( CompletionHandler, @@ -85,9 +86,13 @@ def __init__( self.cancelled = False self._next_when = None - async def __aenter__(self) -> Perpetual: + async def __aenter__(self) -> Self: + # Each attempt gets a copy of the declared instance, so what the task + # asks of it (cancel, perpetuate, after, at) applies to that attempt + # alone. Copying keeps a subclass and its state without calling its + # constructor, whose arguments may differ from this class's. execution = current_execution.get() - perpetual = Perpetual(every=self.every, automatic=self.automatic) + perpetual = copy.copy(self) perpetual.args = execution.args perpetual.kwargs = execution.kwargs return perpetual diff --git a/python/src/docket/dependencies/_ratelimit.py b/python/src/docket/dependencies/_ratelimit.py index c932c1ab..ebe6297b 100644 --- a/python/src/docket/dependencies/_ratelimit.py +++ b/python/src/docket/dependencies/_ratelimit.py @@ -8,10 +8,11 @@ from __future__ import annotations +import copy import time from datetime import timedelta from types import TracebackType -from typing import Any +from typing import Any, Self from .._lua import Arg, Key, redis_script from .._redis import RedisClient @@ -74,8 +75,8 @@ def __init__( self._ratelimit_key: str | None = None self._member: str | None = None - def bind_to_parameter(self, name: str, value: Any) -> RateLimit: - bound = RateLimit(self.limit, per=self.per, drop=self.drop, scope=self.scope) + def bind_to_parameter(self, name: str, value: Any) -> Self: + bound = copy.copy(self) bound._argument_name = name bound._argument_value = value return bound diff --git a/python/src/docket/dependencies/_retry.py b/python/src/docket/dependencies/_retry.py index bf562f0a..6eca35e6 100644 --- a/python/src/docket/dependencies/_retry.py +++ b/python/src/docket/dependencies/_retry.py @@ -2,9 +2,10 @@ from __future__ import annotations +import copy import logging from datetime import datetime, timedelta, timezone -from typing import TYPE_CHECKING, NoReturn +from typing import TYPE_CHECKING, NoReturn, Self from ._base import ( FailureHandler, @@ -31,6 +32,14 @@ class Retry(FailureHandler["Retry"]): """Configures linear retries for a task. You can specify the total number of attempts (or `None` to retry indefinitely), and the delay between attempts. + With `Perpetual` or `Cron`, the attempts apply within one run, and each run + starts again at attempt 1. + + Subclasses can override `handle_failure` to decide which failures are + retried. Each attempt receives a shallow copy of the declared instance, so + state a subclass sets in its constructor is kept, and an attribute an + attempt assigns on its copy is not carried to the next attempt. + Examples: ```python @@ -60,7 +69,7 @@ def __init__( self.attempt = 1 @classmethod - def forever(cls, delay: timedelta = timedelta(0)) -> Retry: + def forever(cls, delay: timedelta = timedelta(0)) -> Self: """Create a retry that retries indefinitely until the task succeeds. Example: @@ -72,9 +81,13 @@ async def my_task(retry: Retry = Retry.forever(delay=timedelta(minutes=5))) -> N """ return cls(attempts=None, delay=delay) - async def __aenter__(self) -> Retry: + async def __aenter__(self) -> Self: + # Each attempt gets a copy of the retry the task declared, so a delay + # the task sets with after() or at() applies to that attempt alone. + # Copying keeps the subclass and its state without calling its + # constructor, whose arguments may differ from this class's. execution = current_execution.get() - retry = Retry(attempts=self.attempts, delay=self.delay) + retry = copy.copy(self) retry.attempt = execution.attempt return retry @@ -165,6 +178,9 @@ class ExponentialRetry(Retry): of attempts (or `None` to retry indefinitely), and the minimum and maximum delays between attempts. + With `Perpetual` or `Cron`, the attempts apply within one run, and each run + starts again at attempt 1. + Examples: ```python @@ -199,7 +215,7 @@ def forever( cls, delay: timedelta = timedelta(seconds=1), maximum_delay: timedelta = timedelta(seconds=64), - ) -> ExponentialRetry: + ) -> Self: """Create an exponential retry that retries indefinitely. Args: @@ -220,15 +236,10 @@ async def my_task( """ return cls(attempts=None, minimum_delay=delay, maximum_delay=maximum_delay) - async def __aenter__(self) -> ExponentialRetry: + async def __aenter__(self) -> Self: execution = current_execution.get() - retry = ExponentialRetry( - attempts=self.attempts, - minimum_delay=self.delay, - maximum_delay=self.maximum_delay, - ) - retry.attempt = execution.attempt + retry = await super().__aenter__() if execution.attempt > 1: exponent = execution.attempt - 1 diff --git a/python/src/docket/dependencies/_timeout.py b/python/src/docket/dependencies/_timeout.py index ab5b64cf..3894146b 100644 --- a/python/src/docket/dependencies/_timeout.py +++ b/python/src/docket/dependencies/_timeout.py @@ -3,9 +3,10 @@ from __future__ import annotations import asyncio +import copy import time from datetime import timedelta -from typing import TYPE_CHECKING, Any, Awaitable, Callable +from typing import TYPE_CHECKING, Any, Awaitable, Callable, Self if TYPE_CHECKING: # pragma: no cover from ..execution import Execution @@ -37,8 +38,11 @@ def __init__(self, base: timedelta) -> None: """ self.base = base - async def __aenter__(self) -> Timeout: - return Timeout(base=self.base) + async def __aenter__(self) -> Self: + # Each execution gets a copy of the declared instance, with its own + # deadline. Copying keeps a subclass and its state without calling + # its constructor, whose arguments may differ from this class's. + return copy.copy(self) def start(self) -> None: self._deadline = time.monotonic() + self.base.total_seconds() diff --git a/python/tests/test_dependency_subclasses.py b/python/tests/test_dependency_subclasses.py new file mode 100644 index 00000000..3531d2d5 --- /dev/null +++ b/python/tests/test_dependency_subclasses.py @@ -0,0 +1,258 @@ +"""Subclasses of docket's behavioral dependencies reach the task and the +worker as the subclass, with the state their constructors set.""" + +from datetime import timedelta +from typing import Any, Awaitable, Callable + +import pytest + +from docket import ( + ConcurrencyLimit, + Cooldown, + Cron, + Debounce, + Docket, + ExponentialRetry, + Perpetual, + RateLimit, + Retry, + Timeout, + Worker, +) +from docket.dependencies import Dependency, TaskOutcome +from docket.execution import Execution + + +class LabeledPerpetual(Perpetual): + def __init__(self, label: str) -> None: + super().__init__(every=timedelta(hours=1)) + self.label = label + + +class LabeledCron(Cron): + def __init__(self, label: str) -> None: + super().__init__("@yearly", automatic=False) + self.label = label + + +class LabeledTimeout(Timeout): + def __init__(self, label: str) -> None: + super().__init__(timedelta(seconds=10)) + self.label = label + + +class LabeledConcurrencyLimit(ConcurrencyLimit): + def __init__(self, label: str) -> None: + super().__init__(max_concurrent=1) + self.label = label + + +@pytest.mark.parametrize( + "declared", + [ + LabeledPerpetual("billing"), + LabeledCron("billing"), + LabeledTimeout("billing"), + LabeledConcurrencyLimit("billing"), + ], +) +async def test_task_receives_subclass_with_its_own_arguments( + docket: Docket, worker: Worker, declared: Any +): + """A task receives the subclass it declared, including state from a + constructor that takes different arguments than the base class.""" + + received: list[tuple[bool, str]] = [] + + async def the_task(dependency: Any = declared) -> None: + received.append((type(dependency) is type(declared), dependency.label)) + + execution = await docket.add(the_task)() + + await worker.run_at_most({execution.key: 1}) + + assert received == [(True, "billing")] + + +class PerpetualOnce(Perpetual): + async def on_complete(self, execution: Execution, outcome: TaskOutcome) -> bool: + return False + + +class CronOnce(Cron): + async def on_complete(self, execution: Execution, outcome: TaskOutcome) -> bool: + return False + + +@pytest.mark.parametrize( + "declared", + [ + PerpetualOnce(every=timedelta(milliseconds=10)), + CronOnce("* * * * * *", automatic=False), + ], +) +async def test_subclass_decides_whether_to_run_again( + docket: Docket, worker: Worker, declared: Perpetual +): + """A subclass's on_complete decides whether the task is rescheduled.""" + + calls = 0 + + async def the_task(perpetual: Perpetual = declared) -> None: + nonlocal calls + calls += 1 + + execution = await docket.add(the_task)() + + await worker.run_at_most({execution.key: 2}) + + assert calls == 1 + + +class RecordingTimeout(Timeout): + def __init__(self, base: timedelta, ran: list[str]) -> None: + super().__init__(base) + self.ran = ran + + async def run( + self, + execution: Execution, + function: Callable[..., Awaitable[Any]], + args: tuple[Any, ...], + kwargs: dict[str, Any], + ) -> Any: + self.ran.append(execution.key) + return await super().run(execution, function, args, kwargs) + + +async def test_timeout_subclass_runs_the_task(docket: Docket, worker: Worker): + """A Timeout subclass's run is what executes the task.""" + + ran: list[str] = [] + + async def the_task( + timeout: Timeout = RecordingTimeout(timedelta(seconds=10), ran), + ) -> None: ... + + execution = await docket.add(the_task)() + + await worker.run_until_finished() + + assert ran == [execution.key] + + +class LabeledCooldown(Cooldown): + def __init__(self, label: str) -> None: + super().__init__(timedelta(seconds=30)) + self.label = label + + +class LabeledRateLimit(RateLimit): + def __init__(self, label: str) -> None: + super().__init__(5, per=timedelta(minutes=1)) + self.label = label + + +class LabeledDebounce(Debounce): + def __init__(self, label: str) -> None: + super().__init__(timedelta(seconds=5)) + self.label = label + + +@pytest.mark.parametrize( + "declared", + [ + LabeledConcurrencyLimit("billing"), + LabeledCooldown("billing"), + LabeledRateLimit("billing"), + LabeledDebounce("billing"), + ], +) +def test_annotated_dependency_binds_as_its_subclass(declared: Dependency[Any]): + """A dependency in Annotated metadata is bound to its parameter as the + subclass that was declared, with its state.""" + + bound: Any = declared.bind_to_parameter("customer_id", 1) + + assert (type(bound), bound.label) == (type(declared), "billing") + + +class NeverRetry(Retry): + async def handle_failure(self, execution: Execution, outcome: TaskOutcome) -> bool: + return False + + +class NeverExponentialRetry(ExponentialRetry): + async def handle_failure(self, execution: Execution, outcome: TaskOutcome) -> bool: + return False + + +@pytest.mark.parametrize( + "retry", + [NeverRetry(attempts=3), NeverExponentialRetry(attempts=3)], +) +async def test_retry_subclass_decides_whether_to_retry( + docket: Docket, worker: Worker, retry: Retry +): + """A subclass's handle_failure decides whether a failed task is retried.""" + + calls = 0 + + async def the_task(retry: Retry = retry) -> None: + nonlocal calls + calls += 1 + raise Exception("Failed") + + await docket.add(the_task)() + + await worker.run_until_finished() + + assert calls == 1 + + +class LabeledRetry(Retry): + def __init__(self, label: str, attempts: int | None = 1) -> None: + super().__init__(attempts=attempts) + self.label = label + + +class LabeledExponentialRetry(ExponentialRetry): + def __init__(self, label: str, attempts: int | None = 1) -> None: + super().__init__(attempts=attempts, minimum_delay=timedelta(0)) + self.label = label + + +@pytest.mark.parametrize( + "retry", + [ + LabeledRetry("billing", attempts=2), + LabeledExponentialRetry("billing", attempts=2), + ], +) +async def test_task_receives_retry_subclass_with_its_own_arguments( + docket: Docket, worker: Worker, retry: LabeledRetry | LabeledExponentialRetry +): + """A task receives its retry subclass, including state from a constructor + that takes different arguments than the base class.""" + + received: list[tuple[type[Retry], str, int]] = [] + + async def the_task( + retry: LabeledRetry | LabeledExponentialRetry = retry, + ) -> None: + received.append((type(retry), retry.label, retry.attempt)) + raise Exception("Failed") + + await docket.add(the_task)() + + await worker.run_until_finished() + + assert received == [(type(retry), "billing", 1), (type(retry), "billing", 2)] + + +def test_forever_returns_the_subclass(): + """forever() on a subclass is typed as, and returns, that subclass.""" + retry: NeverRetry = NeverRetry.forever() + exponential: NeverExponentialRetry = NeverExponentialRetry.forever() + + assert (type(retry), type(exponential)) == (NeverRetry, NeverExponentialRetry) diff --git a/python/tests/test_handler_semantics.py b/python/tests/test_handler_semantics.py index 456ba471..a1327542 100644 --- a/python/tests/test_handler_semantics.py +++ b/python/tests/test_handler_semantics.py @@ -126,3 +126,49 @@ async def failing_task(perpetual: Perpetual = Perpetual()): delay = run_times[1] - run_times[0] # Should have waited ~100ms between runs assert delay >= timedelta(milliseconds=50) + + +async def test_cancel_on_the_final_attempt_stops_a_perpetual_task( + docket: Docket, worker: Worker +): + """A perpetual task with retries stops rescheduling itself when it cancels + on its last attempt.""" + attempts: list[int] = [] + + async def the_task( + retry: Retry = Retry(attempts=3), + perpetual: Perpetual = Perpetual(every=timedelta(milliseconds=10)), + ): + attempts.append(retry.attempt) + if retry.attempt == retry.attempts: + perpetual.cancel() + raise ValueError("failing every attempt") + + await docket.add(the_task)() + + await worker.run_until_finished() + + assert attempts == [1, 2, 3] + + +async def test_cancel_on_a_retried_attempt_does_not_stop_a_perpetual_task( + docket: Docket, worker: Worker +): + """Each attempt has its own Perpetual, so a cancel on an attempt that is + retried is not seen when the run finally completes.""" + attempts: list[int] = [] + + async def the_task( + retry: Retry = Retry(attempts=2), + perpetual: Perpetual = Perpetual(every=timedelta(milliseconds=10)), + ): + attempts.append(retry.attempt) + if retry.attempt == 1: + perpetual.cancel() + raise ValueError("failing every attempt") + + execution = await docket.add(the_task)() + + await worker.run_at_most({execution.key: 4}) + + assert attempts == [1, 2, 1, 2] diff --git a/python/tests/test_retry_attempt_copies.py b/python/tests/test_retry_attempt_copies.py new file mode 100644 index 00000000..1f66822c --- /dev/null +++ b/python/tests/test_retry_attempt_copies.py @@ -0,0 +1,60 @@ +"""Each attempt of a task works with its own copy of the retry the task +declared.""" + +from datetime import timedelta + +from docket import Docket, Retry, Worker +from docket.dependencies import TaskOutcome +from docket.execution import Execution + + +async def test_forced_retry_delay_applies_to_one_attempt_only( + docket: Docket, worker: Worker +): + """The delay a task passes to after() does not change the delay the task + declared for its later attempts.""" + + declared = Retry(attempts=3, delay=timedelta(milliseconds=5)) + delays: list[timedelta] = [] + + async def the_task(retry: Retry = declared) -> None: + delays.append(retry.delay) + if retry.attempt == 1: + retry.after(timedelta(milliseconds=10)) + raise Exception("Failed") + + await docket.add(the_task)() + + await worker.run_until_finished() + + assert delays == [timedelta(milliseconds=5)] * 3 + assert declared.delay == timedelta(milliseconds=5) + + +class CountingRetry(Retry): + def __init__(self, attempts: int | None = 1) -> None: + super().__init__(attempts=attempts) + self.failures = 0 + + async def handle_failure(self, execution: Execution, outcome: TaskOutcome) -> bool: + self.failures += 1 + return await super().handle_failure(execution, outcome) + + +async def test_each_attempt_starts_from_the_declared_state( + docket: Docket, worker: Worker +): + """What a subclass records on one attempt's copy is not carried to the next + attempt, which may run on another worker.""" + + failures: list[int] = [] + + async def the_task(retry: CountingRetry = CountingRetry(attempts=3)) -> None: + failures.append(retry.failures) + raise Exception("Failed") + + await docket.add(the_task)() + + await worker.run_until_finished() + + assert failures == [0, 0, 0] diff --git a/rust/docket/src/behaviors/retry.rs b/rust/docket/src/behaviors/retry.rs index bb5bac61..c6c2fbf9 100644 --- a/rust/docket/src/behaviors/retry.rs +++ b/rust/docket/src/behaviors/retry.rs @@ -10,6 +10,9 @@ use crate::task::Task; /// Retries a failed task after a fixed delay. `attempts` counts every run, /// the first included, so `Retry::attempts(1)` never retries. /// +/// With [`Perpetual`](super::Perpetual) or [`Cron`](super::Cron), the +/// attempts apply within one run, and each run starts again at attempt 1. +/// /// A handler can ask for a retry at a time it chooses by returning /// [`ForcedRetry`]; that spends an attempt like any failure. #[derive(Clone, Debug, PartialEq, Eq)] @@ -65,6 +68,9 @@ impl Failure for Retry { /// Retries a failed task with a delay that doubles each time: /// `minimum_delay`, then twice that, up to `maximum_delay`. +/// +/// With [`Perpetual`](super::Perpetual) or [`Cron`](super::Cron), the +/// attempts apply within one run, and each run starts again at attempt 1. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ExponentialRetry { attempts: Option, diff --git a/rust/docket/tests/docket/perpetual.rs b/rust/docket/tests/docket/perpetual.rs index 136535fb..72dcf31d 100644 --- a/rust/docket/tests/docket/perpetual.rs +++ b/rust/docket/tests/docket/perpetual.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::Duration; -use docket::{Event, Perpetual, State, Task}; +use docket::{Event, Perpetual, Retry, State, Task}; use futures::StreamExt; use serde::{Deserialize, Serialize}; @@ -165,6 +165,28 @@ async fn a_perpetual_task_runs_again_after_it_fails() { assert_eq!(*runs.lock().unwrap(), 2); } +#[tokio::test] +async fn each_run_of_a_perpetual_task_gets_its_own_retries() { + let docket = docket().await; + let attempts = Arc::new(Mutex::new(Vec::new())); + let recorded = Arc::clone(&attempts); + docket + .register(move |ctx: docket::Context, _: Noop| { + recorded.lock().unwrap().push(ctx.attempt()); + async { Err::<(), _>(std::io::Error::other("nope")) } + }) + .with(Retry::attempts(2)) + .with(Perpetual::every(Duration::from_millis(10))); + docket.add(Noop).key("stubborn").await.unwrap(); + + let limits = HashMap::from([("stubborn".to_owned(), 4)]); + within(10, worker(&docket).run_at_most(limits)) + .await + .unwrap(); + + assert_eq!(*attempts.lock().unwrap(), [1, 2, 1, 2]); +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Task)] #[task(name = "stopping")] struct Stopping {