Example

Cancel, retry and time out one request at a time

Run four reliability outcomes through one worker and check that every path releases its resources, including the failures.

A serving request can end in more than success. It can be cancelled by the client, fail and be retried, exceed a deadline, or exhaust its retry budget. Each path has to release resources and report which outcome occurred. “The process did not crash” is not a reliability result.

This example runs four controlled cases through a small worker: a clean success, an injected failure with one retry, a cancellation after step two, and a timeout. Every case releases its request id; the final resource set is empty. The page also exposes a boundary defect: with max_retries=0, an injected failure is not raised at all, so the worker reports recovery. That is a useful negative control, not a feature.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch30/reliability.py --json

Python 3.11 or later, standard library only. No model, network, GPU or credentials. It finishes immediately.

Implementation

The worker acquires a resource id, loops over steps, and raises on cancellation or timeout. An injected failure at a step triggers a retry only while the retry budget remains. The finally block releases the resource on every path.

class ReliableWorker:
    def __init__(self, max_retries: int = 2, timeout: int = 5) -> None:
        if max_retries < 0 or timeout < 1:
            raise ValueError("invalid worker configuration")
        self.max_retries = max_retries
        self.timeout = timeout
        self.resources: set[str] = set()

    def acquire(self, rid: str) -> None:
        self.resources.add(rid)

    def release(self, rid: str) -> None:
        self.resources.discard(rid)

    def run(self, rid: str, steps: int, fail_at: Optional[int] = None, cancel_after: Optional[int] = None) -> RecoveryResult:
        self.acquire(rid)
        retries = 0
        timed_out = False
        cancelled = False
        recovered = False
        try:
            for step in range(steps):
                if cancel_after is not None and step >= cancel_after:
                    cancelled = True
                    raise RuntimeError("cancelled")
                if fail_at is not None and step == fail_at and retries < self.max_retries:
                    retries += 1
                    # retry from start
                    continue
                if step >= self.timeout:
                    timed_out = True
                    raise TimeoutError("timeout")
            recovered = True
        except (RuntimeError, TimeoutError):
            recovered = False
        finally:
            self.release(rid)
        return RecoveryResult(
            request_id=rid,
            cancelled=cancelled,
            timed_out=timed_out,
            retries=retries,
            recovered=recovered,
            resources_released=rid not in self.resources,
            metadata={"steps": steps, "fail_at": fail_at, "cancel_after": cancel_after},
        )

Expected outcome

Observed with the command above (exit 0):

{
  "success": {
    "request_id": "r1",
    "cancelled": false,
    "timed_out": false,
    "retries": 0,
    "recovered": true,
    "resources_released": true,
    "metadata": {
      "steps": 4,
      "fail_at": null,
      "cancel_after": null
    }
  },
  "retried": {
    "request_id": "r2",
    "cancelled": false,
    "timed_out": false,
    "retries": 1,
    "recovered": true,
    "resources_released": true,
    "metadata": {
      "steps": 4,
      "fail_at": 1,
      "cancel_after": null
    }
  },
  "cancelled": {
    "request_id": "r3",
    "cancelled": true,
    "timed_out": false,
    "retries": 0,
    "recovered": false,
    "resources_released": true,
    "metadata": {
      "steps": 4,
      "fail_at": null,
      "cancel_after": 2
    }
  },
  "timed_out": {
    "request_id": "r4",
    "cancelled": false,
    "timed_out": true,
    "retries": 0,
    "recovered": false,
    "resources_released": true,
    "metadata": {
      "steps": 10,
      "fail_at": null,
      "cancel_after": null
    }
  },
  "resources_after": []
}

The retry case re-entered the loop once and then recovered. The cancellation and timeout cases did not recover but did release their resources. The final resources_after list is empty, which is the property the page is testing.

Mechanism and limitations

Documented: the worker rejects a negative retry count or non-positive timeout, acquires and releases a request id, and reports cancellation, timeout, retry count, recovery and resource release. The tests check success, retry, cancellation, timeout, cleanup, the demo and JSON serialisation.

Observed: the command exited 0 with the four outcomes above. Separately, a zero-retry worker with an injected failure at step 1 returned recovered: true, retries: 0; the retry guard does not raise when the budget is already zero. This is a boundary defect in the small module, not a property of the fuller reliability_lab.py or supervisor_lab.py. The targeted tests.test_ch30_reliability is part of the canonical suite; no independent test count is claimed here.

Not shown: idempotency, exactly-once execution, persistence across a process crash, worker loss, or recovery of partially generated output. A retry here restarts the loop; it does not resume a checkpoint. A released resource id does not prove that GPU memory or a network connection was reclaimed.

Challenge this result

Run ReliableWorker(max_retries=0).run("r", 4, fail_at=1). Predict the result, then explain why it reports recovery despite the injected failure. Fix the guard so that an exhausted retry budget raises an error, and add a test for it. Then state why a timeout after three generated tokens and a retry that regenerates all three are not the same operation to a client that already received the first two.

Source and verification

Canonical source: examples/ch30/reliability.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch30_reliability.py . Chapter: Reliability, Cancellation and Recovery . The run above is a fresh local execution on Windows 11 with Python 3.13.15; it uses an in-process simulated worker, not a failed server.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.