GitHub

Exploring schedules and crashes

Run an effect under many fiber schedules, with interrupts at every step, and crash a workflow at every activity, to find the races and replay bugs one run never hits.

A test runs an effect once, in one order of its fibers. A race shows up only in some other order, and a replay bug only when the process stops at one particular point. pyfect.testing.explore runs the effect many ways and checks each run: explore.schedules tries the fiber schedules, and explore.activity_crashes stops a workflow at each activity and resumes it.

Fiber schedules

explore.schedules(effect, check) runs effect under up to runs distinct schedules (1000 by default) and calls check with each run's Exit. The check returns what went wrong, or None. Half the runs go to every schedule with few deviations from the first-come order, so a small effect is covered exhaustively (the report says so). The rest are random, from seed on. A fiber that never ends, such as a lost wake-up or a deadlock, fails the run as well.

A failure raises ScheduleFailure. It lists the problems and the last steps of the run, and names the schedule, which replay= runs again exactly. When a random run found it, it also names the seed, and exploring again with that seed finds it on the first random run. max_ops_before_yield=1 pauses a fiber after every step, so other fibers can run between any two of its steps, not only where it waits or yields.

test_explore_schedules.py
from collections.abc import Callable
from typing import Any

import pytest

import pyfect as fx
from pyfect.testing import explore


def read_then_write(balance: fx.Ref[int]) -> fx.Effect[None]:
    """A check-then-act across a yield."""

    @fx.gen
    def body():
        seen = yield from balance.get()
        yield from fx.yield_now()
        yield from balance.set(seen + 50)

    return body


def atomic(balance: fx.Ref[int]) -> fx.Effect[None]:
    return fx.yield_now().and_then(balance.update(lambda seen: seen + 50))


def deposit_twice(deposit: Callable[[fx.Ref[int]], fx.Effect[None]]) -> fx.Effect[int]:
    """Two deposits of 50 into one balance; the second starts a little later."""

    @fx.gen
    def body():
        balance = yield from fx.Ref.make(0)
        later = fx.yield_now().and_then(fx.yield_now()).and_then(deposit(balance))
        yield from fx.all([deposit(balance), later], concurrency="unbounded")
        return (yield from balance.get())

    return body


def is_100(ex: fx.Exit[int, Any]) -> str | None:
    return None if ex == fx.Success(100) else f"balance is {ex}"


def test_explore_finds_the_lost_deposit():
    # The first-come order happens to give 100; another order loses a deposit.
    with pytest.raises(explore.ScheduleFailure) as found:
        explore.schedules(deposit_twice(read_then_write), is_100)
    assert found.value.problems == ("balance is Success(value=50)",)
    # The failure prints its schedule; replay= runs exactly that one again.
    with pytest.raises(explore.ScheduleFailure):
        explore.schedules(deposit_twice(read_then_write), is_100, replay=found.value.schedule)


def test_an_atomic_update_passes_every_schedule():
    report = explore.schedules(deposit_twice(atomic), is_100)
    assert report.exhaustive


def leaky_lock() -> explore.Case[None, Any]:
    """A fresh lock and run each time; the check reads the lock afterwards."""
    lock = fx.Semaphore(1)
    effect = lock.take().and_then(fx.yield_now()).and_then(lock.release()).as_void()

    def check(_: fx.Exit[None, Any]) -> str | None:
        free = fx.run_sync(lock.available)
        return None if free == 1 else "the lock was never released"

    return effect, check


def test_an_interrupt_at_the_wrong_step_leaks_the_lock():
    explore.schedules(leaky_lock)  # passes: nothing interrupts it
    with pytest.raises(explore.ScheduleFailure) as found:
        explore.schedules(leaky_lock, interrupts=True)
    assert found.value.interrupted_at is not None  # use lock.with_permits(...) instead

With interrupts=True the effect's fiber is also interrupted, and the search lands the interrupt at each step of the run. The check then sees an interrupted exit, so it reads state the effect does not own. Pass a function that makes a fresh (effect, check) pair for each run, as leaky_lock does above. The failure's interrupted_at is the step the interrupt was sent at.

Activity crashes

Activities run at least once, not exactly once: when a process stops after an activity ran but before the engine stored its result, the resumed workflow runs it again. And a call in the workflow's body, outside any activity, runs again on every replay. explore.activity_crashes(workflow, payload, layer=..., check=...) runs the workflow once without a crash, then once per crash point: after each activity it executes, before the engine stored the result and after. At each point the run stops, the workflow is resumed, and check gets its exit and returns a problem or None. The first problem fails with CrashFailure, which names the point.

A long workflow has many crash points, and every one replays the run. at=range(1, 11) tries only the points after activities 1 to 10 (numbered in the order the run executes them) and skips the run without a crash, so a sweep can be split over several tests. stored=True or stored=False keeps only the crashes after, or before, each result was stored. The durable agents tests sweep a 100-turn run this way.

layer provides the engine with the workflow registered, and whatever check reads. It is built again for every run, so each one starts with an empty engine. It can be workflow_engine.layer_memory, or a cluster engine such as cluster_workflow_engine.layer on single_runner.layer with SQLite (":memory:" gives each build its own database). Run the cluster one under @testing.live: its runner polls on a timer.

test_explore_crashes.py
from typing import Any, TypedDict

import pyfect as fx
from pyfect import schema as S
from pyfect import testing
from pyfect.testing import explore
from pyfect.workflow import activity, workflow, workflow_engine


class Order(TypedDict):
    id: str
    amount: int


class Payments:
    """A payment provider that, like most, dedupes requests by an idempotency key."""

    def __init__(self) -> None:
        self.charged: list[int] = []
        self.keys: set[str] = set()

    def charge(self, amount: int, key: str | None) -> None:
        if key is not None and key in self.keys:
            return
        if key is not None:
            self.keys.add(key)
        self.charged.append(amount)


class PaymentsService(fx.Tag[Payments]): ...


Checkout = workflow.make(
    "Checkout", payload=S.Struct(Order), success=S.String, idempotency_key=lambda o: o["id"]
)


def checkout(*, with_key: bool):
    def run(order: Order, _execution_id: str) -> fx.Effect[str, Any, Any]:
        @fx.gen
        def charge():
            payments = yield from PaymentsService()
            key = yield from activity.idempotency_key("charge")
            payments.charge(order["amount"], key if with_key else None)

        @fx.gen
        def body():
            yield from activity.make(name="charge", execute=charge)
            yield from activity.make(name="ship", execute=fx.void)
            return f"order {order['id']} done"

        return body

    # Built afresh for every crash point: a new engine and a new provider.
    return (
        Checkout.to_layer(run)
        .pipe(fx.layer.provide_merge(workflow_engine.layer_memory))
        .pipe(fx.layer.provide_merge(fx.layer.sync(PaymentsService, Payments)))
    )


def paid_once(_: fx.Exit[str, Any]) -> fx.Effect[str | None, Any, PaymentsService]:
    def judge(payments: Payments) -> str | None:
        return None if payments.charged == [30] else f"charged {payments.charged}"

    return PaymentsService().map(judge)


@testing.effect
def test_a_charge_without_a_key_runs_twice_after_a_crash():
    order: Order = {"id": "o-1", "amount": 30}
    crashes = explore.activity_crashes(
        Checkout, order, layer=checkout(with_key=False), check=paid_once
    )
    failure = yield from crashes.flip()
    # The run stopped after the charge ran but before its result was stored,
    # so the resumed run charged again.
    assert failure.point == explore.CrashPoint(1, "charge", stored=False)
    assert failure.problem == "charged [30, 30]"


@testing.effect
def test_the_idempotency_key_survives_every_crash():
    order: Order = {"id": "o-1", "amount": 30}
    report = yield from explore.activity_crashes(
        Checkout, order, layer=checkout(with_key=True), check=paid_once
    )
    assert len(report.points) == 4  # charge and ship, each before and after it was stored

A crash stops the run as a suspension does: nothing after the boundary runs, the run's finalizers don't run, and what the engine stored stays. Resuming replays the run from the start, as a restarted runner would. The process and the layer aren't restarted, though, so state kept outside the engine, such as a module-level cache, survives the crash where a real restart would lose it.

What explore doesn't support

explore.schedules drives every fiber itself and runs timers on virtual time, so the effect must do all its work on fibers:

  • Work handed to another thread or process (fx.blocking, SQLite and the other SQL clients, HTTP clients, workers) finishes outside the schedule. Its order isn't explored, and the run usually fails with a fiber that never ended (parked), waiting for an answer the schedule can't deliver. Provide in-memory layers of those services instead.
  • A program that polls forever never goes idle: a cluster's sharding loops wake on every interval, so the run ends with "no end after 10000 steps". Test cluster workflows with activity_crashes under @testing.live instead.
  • The effect must do the same thing on every run, with no real time or randomness of its own, or a schedule doesn't replay.

Reference: pyfect.testing.explore.