Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
39 changes: 39 additions & 0 deletions docs/task-behaviors.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,45 @@ 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 each hour, 30 seconds apart
await sync_external_data()
```

Exhausted retries never stop the cycle. A task that should stop rescheduling itself calls `perpetual.cancel()`. For an automatic task that 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 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`.

## Task Timeouts

Prevent tasks from running too long with the `Timeout` dependency:
Expand Down
27 changes: 17 additions & 10 deletions python/src/docket/dependencies/_retry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -31,6 +32,13 @@ 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 copy of the declared instance, so state a
subclass sets in its constructor is kept.

Examples:

```python
Expand Down Expand Up @@ -72,9 +80,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

Expand Down Expand Up @@ -220,15 +232,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
Expand Down
98 changes: 98 additions & 0 deletions python/tests/fundamentals/test_retries.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import pytest

from docket import Docket, ExponentialRetry, Retry, Worker
from docket.dependencies import TaskOutcome
from docket.execution import Execution


async def test_errors_are_logged(
Expand Down Expand Up @@ -336,3 +338,99 @@ async def the_task(
assert total_delay >= timedelta(milliseconds=25 + 50 + 100 + 100)

assert calls == 5


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_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_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)]


async def test_forced_retry_delay_applies_to_one_attempt_only(
Comment thread
chrisguidry marked this conversation as resolved.
Resolved
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)
3 changes: 3 additions & 0 deletions rust/docket/src/behaviors/retry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down
24 changes: 23 additions & 1 deletion rust/docket/tests/docket/perpetual.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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 {
Expand Down