Browse documentation
Guides
View Markdown
On this page

Fan-out over items, with retries

This guide runs one piece of work for every item of a list (here, one refund per damaged order) and tries the failed ones again. At the end you have a workflow that refunds a batch a few orders at a time with a bounded number of attempts each, and a tool whose call is sent again when its service could not be reached.

  • You will be able to: run one child per item of a list that is known only when the run starts, limit how many run at once, try a failed item again, a bounded number of times, and retry a tool call whose service could not be reached.
  • Read first: Workflows (stages, FanOut, joins) and Errands (a batch of tool calls made by code, without a model).
  • Time: about 15 minutes.

The page does two independent jobs. Steps 1 to 5 retry an item of a fan-out, as a new child; Retrying a tool call retries one tool call inside a request, and can be read on its own. gvn has one class named Retry for each: gvn.harness.workflow.Retry for the item and gvn.harness.ports.Retry for the call. This page uses both, and imports the second as CallRetry.

Where this fits

In the big picture, the actor is the verified state machine the Governor drives. A workflow is an actor whose states hand work to child actors: each state that does work has a stage, the recipe for which children to start there and when the state is over. This guide adds one kind of stage, ForEach, which starts one child per item of a list and tries a failed item again:

flowchart LR
    workflow["<b>Workflow</b><br/>its own verified machine"]
    stage["<b>ForEach stage</b><br/>one child per item,<br/>at most <i>window</i> at once"]
    a1["child for A-1"]
    b2["child for B-2<br/>attempt 1: failed"]
    b2b["child for B-2<br/>attempt 2"]
    c3["child for C-3"]
    join["<b>join</b><br/>one final result per item"]
    workflow -- "state refunding" --> stage
    stage --> a1
    stage --> b2
    b2 -. "retry" .-> b2b
    stage --> c3
    a1 --> join
    b2b --> join
    c3 --> join
    join -- "refunded or not_refunded" --> workflow

The Governor, fulfillers and journal are unchanged: the children's tool calls go to the same fulfillers as any agent's, and every event is journaled as usual. A second, smaller retry lives with each tool, below the plan: a tool can declare that one of its calls is sent again, under the same key, when its service could not be reached, and the ToolFulfiller does so (Retrying a tool call).

The problem

The help desk has a batch of damaged orders to refund. The list comes with the request: three orders today, forty tomorrow. Each refund is one call to the payment service, and the payment service sometimes answers "busy, try again".

A FanOut (the stage from Workflows that starts several children at once) counts its children: it hands each child an index, and your code has to map indexes back to orders. It also has no notion of "try that one again": a failed child is simply a failed result. You could loop the whole stage and work out which orders are left, but then every retry is a new visit of the stage, and the bound on retries is code you wrote and have to get right.

ForEach is the stage for this. It takes the list itself, starts one child per item, keeps at most window of them running, and starts a failed item again, as a new child, up to a declared number of attempts. Its join (the rule that says when a stage is over, and with which answer) sees one final result per item.

Step 1: a payment service that is sometimes busy

First the outside world. This fake payment service refunds each order once per idempotency key (the key a tool call carries, the same each time that call is re-issued) and is busy the first time it is asked about order B-2. RefundOrder is the tool over it, written as in 4. Adding a tool:

import asyncio
import typing
from collections.abc import Iterable

from gvn.harness.events import Event
from gvn.harness.tools import VERDICTS, Invocation, Tool, Toolbox
from gvn.kernel.decision import Decision
from gvn.kernel.schema import Record, Text
from gvn.kernel.symbols import Alphabet, Symbol


class Payments:
    """Refunds once per key. Busy the first time it is asked about B-2."""

    def __init__(self) -> None:
        self.refunded = []
        self.keys = {}
        self._answers = {}
        self._busy_once = {"B-2"}

    def refund(self, order_id: str, key: str) -> dict[str, str]:
        self.keys.setdefault(order_id, []).append(key)
        if key not in self._answers:
            if order_id in self._busy_once:
                self._busy_once.discard(order_id)
                self._answers[key] = None
            else:
                self.refunded.append(order_id)
                self._answers[key] = {"refunded": order_id}
        if self._answers[key] is None:
            raise RuntimeError(f"the bank is busy; {order_id} was not refunded")
        return self._answers[key]


class RefundOrder(Tool):
    def __init__(self, payments: Payments) -> None:
        self._payments = payments

    def name(self) -> str:
        return "refund_order"

    def description(self) -> str:
        return "Refund one order in full."

    def arguments(self) -> Record:
        return Record({"order_id": Text()})

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        return self._payments.refund(arguments["order_id"], invocation.key())


class AllowEverything(Decision):
    def outcomes(self) -> Alphabet:
        return VERDICTS

    def judge(self, consultation: object) -> Symbol:
        return Symbol("cleared")


payments = Payments()
refund_order = RefundOrder(payments=payments)

The tool raises when the service is busy, so the call's status is failed. AllowEverything is a policy that clears every call, as in the tutorials. refund_order is the tool, built once: the errands below name it, the plan declares it and the runtime's toolbox holds it, always as this object (Tools explains why tools are passed as objects).

Step 2: the stage

Each item gets an Errand: a small ready-made actor that makes a fixed list of tool calls, without a model. It ends in its done state when every call succeeded, in failed when a call that ran failed, and in refused or declined when the policy or a person stopped a call. Here it makes one call to refund_order, a FixedCall of a call id, the tool and its arguments, so a busy payment service ends the errand in failed. ForEach calls make with the child's name, the item (here an order id) and the memo: the workflow's record of its input and of the results of its stages so far.

The join is AllOf: the stage succeeds when every item's child reached its done state, and then the workflow is fed refunded; otherwise it is fed not_refunded.

from gvn.harness.errand import Errand
from gvn.harness.tools import FixedCall
from gvn.harness.workflow import AllOf, ForEach, Retry


def refund_errand(name: str, order_id: str, memo: object) -> Errand:
    refund_call = FixedCall(call_id="refund", tool=refund_order, arguments={"order_id": order_id})
    return Errand(name=name, calls=[refund_call])


refunding = ForEach(
    actor_class=Errand,
    items=lambda memo: memo.input()["orders"],
    make=refund_errand,
    start=lambda order_id, memo: Event("started"),
    join=AllOf(success="done", reached="refunded", missed="not_refunded"),
    retry=Retry(attempts=3, on=["failed"]),
    window=2,
)
print(refunding)
ForEach(Errand, join=AllOf('done', reached='refunded', missed='not_refunded'), retry=Retry(attempts=3, on=['failed']), window=2)

Each parameter, in order:

  • actor_class: the class of every child.
  • items(memo): the list, read from trusted data: here the workflow's input; it could be an earlier stage's results. Never from text a model or a person wrote. It is called when the stage starts (and again if a stored run is revived during the stage, so it must depend only on the memo).
  • make(name, item, memo) and start(item, memo): build an item's child and its first event.
  • join: when the stage is over. It sees each item's final result: an attempt that is followed by another is never shown to it.
  • retry: Retry(attempts=3, on=["failed"]) says "an item whose child ended failed is tried again, at most three attempts in all". on names verdicts: final state names, or, with classify= (a Decision over the child's outcome), that decision's answers.
  • window: at most two children run at once. Items start in list order; when one is final, the next starts.

Step 3: the workflow

The workflow's own machine is an ordinary blueprint, as in the first tutorial. branch (from 2. Decisions and branching) declares the two answers the refunding state may receive and where each one goes. A Plan then joins the machine to its stages: stages maps a state name to the stage that runs there, and relay names events the workflow passes on to its running children instead of feeding them to its own machine (here, interrupting and resuming, so one event can pause the whole batch), and tools declares every tool its children call, so the runtime can check its toolbox before the run starts (Tools). The Workflow class returns that plan. Nothing about retries appears here: they happen inside the stage.

from gvn.harness.workflow import Plan, Workflow
from gvn.kernel.blueprint import MooreBlueprint

REFUNDS_MACHINE = (
    MooreBlueprint(name="refunds")
    .inputs("started", "refunded", "not_refunded")
    .outputs("idle", "refund", "done", "failed")
    .state(name="idle", output="idle")
    .state(name="refunding", output="refund")
    .state(name="done", output="done", final=True)
    .state(name="failed", output="failed", final=True)
    .initial(name="idle")
    .on(source="idle", input="started", target="refunding")
    .branch(
        source="refunding",
        outcomes=Alphabet.of("refunded", "not_refunded"),
        routes={"refunded": "done", "not_refunded": "failed"},
    )
    .otherwise_stay()
    .build()
)

REFUNDS = Plan(
    definition=REFUNDS_MACHINE,
    stages={"refunding": refunding},
    relay=["interrupted", "resumed"],
    tools=[refund_order],
)


class Refunds(Workflow):
    @classmethod
    def plan(cls) -> Plan:
        return REFUNDS

Building the plan checks it, as the verifier checks a machine. It checks the stage as it checks a FanOut: every join answer must have a declared transition, and Retry's verdicts must be verdicts the children can have. A Retry(on=["busy"]) here would be refused, because an Errand has no busy final state.

Step 4: run it

The Governor needs two fulfillers here, the policy and the tools: errands never call a model. After the run, Report reads the finished workflow's outcome: its final state and each stage's child results.

from gvn.harness.workflow import Report
from gvn.runtime.fulfillers import PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor, Result
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput

governor = Governor(
    fulfillers={
        "consult_policy": PolicyFulfiller(decision=AllowEverything()),
        "invoke_tools": ToolFulfiller(toolbox=Toolbox(tools=[refund_order])),
    },
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
result = asyncio.run(
    governor.deliver(
        actor=Refunds(name="batch-9"),
        event=Event("started", payload={"orders": ["A-1", "B-2", "C-3"]}),
    )
)
reading = Report(outcome=result.outcome())
print(reading.state())
for child in reading.results("refunding"):
    print(child.index(), child.name(), "attempt", child.attempt(), child.state().name())
print(sorted(payments.refunded))
State('done')
0 batch-9/refunding.1.0.1 attempt 1 done
1 batch-9/refunding.1.1.2 attempt 2 done
2 batch-9/refunding.1.2.1 attempt 1 done
['A-1', 'B-2', 'C-3']

What to notice:

  • Children are named <workflow>/<stage>.<visit>.<index>.<attempt>. index is the item's place in the list; attempt counts from 1. B-2's first child failed, so a second child, batch-9/refunding.1.1.2, took its place at once, and its result is the one kept.
  • Each order was refunded exactly once.

Step 5: a retry is a new key

Every request a child makes has an id that starts with the child's name, and a tool call's idempotency key comes from that id. A retry is a new child, so it asks with a new key:

for key in payments.keys["B-2"]:
    print(key.split("/")[1])
refunding.1.1.1
refunding.1.1.2

That is deliberate. The first attempt failed; the payment service must see the second as a new request, not as a repeat of the first (which it would answer, correctly, with the same failure). A request re-issued after a crash is different: the child is rebuilt from the journal with the same name, so it asks again with the same key, and the service acts once.

If an effect must happen at most once whatever happens, key it by what it is, from trusted data (here the order id), as Run context explains.

A second job: retrying one tool call

Everything up to here retried an item of a ForEach. The rest of the page is a separate job with its own class and its own rules: sending one tool call again. It applies to any tool, in any agent or errand, with or without a fan-out, and it reuses this page's payment service only as its example.

Retrying a tool call

The retry above belongs to the plan: the payment service answered B-2's first request, with a failure it remembers under that key, so only a new request with a new key can succeed. When a connection times out, the service might have applied the effect before the reply was lost. Retry the same call under the same key inside one invoke_tools request when the service can safely deduplicate it. A rate limit can also call for a retry with the same key after the wait the service asks for.

Whether that is safe depends on the tool, and only the tool knows. A search can be repeated five times without harm. A payment can be repeated under the same key only if the payment service honours the key; if it does not, a repeat may pay twice, and the call should be tried once. So the retry is a property of each tool: a tool declares it with retry(), and the ToolFulfiller (the fulfiller that runs tool calls) follows what each tool declares. One request can hold a call tried five times and one tried once.

flowchart LR
    errand["<b>Errand</b><br/>one refund_order call"]
    fulfiller["<b>ToolFulfiller</b><br/>asks the tool: retry()?"]
    tool["<b>refund_order</b><br/>declares a Retry"]
    service["payment service"]
    errand -- "invoke_tools" --> fulfiller
    fulfiller -. "reads" .-> tool
    fulfiller -- "attempt 1, key K: no answer" --> service
    fulfiller -- "attempt 2, key K, after a backoff" --> service
    fulfiller -- "tools_returned: one result,<br/>plus the retries" --> errand

The two retries side by side:

Retry of a ForEach (gvn.harness.workflow) Retry a tool declares (gvn.harness.ports)
Who decides the plan the tool, in Tool.retry()
What runs again the item, as a new child one tool call, inside the same request
Idempotency key new the same
When the child's verdict is one of on the tool raised ToolFailure(..., retryable=True)
Who sees the attempts the join sees the final one; Result.attempt() counts them the actor sees one result; the journal's tools_returned lists the retries

The tool says the service could not be reached

The runtime retries only what the tool marks as worth retrying. A tool raises ToolFailure(reason, retryable=True) when the service could not be reached or asked to wait, and ToolFailure(reason) when the service answered and said no; any other exception is a defect in the tool (4. Adding a tool has the three kinds). This fake service drops the first requests it gets, whatever their key, and then refunds each order once per key (it honours the key, so a repeat is safe); it does not know order Z-0. The tool takes the retry it declares as a constructor argument. It keeps the short name refund_order and is defined in the same module as RefundOrder, so its identity is the same and the errands of Step 2 call it unchanged:

from gvn.harness.tools import ToolFailure


class PaymentsUnreachable(Exception):
    """No answer from the payment service: nothing was done."""


class UnknownOrder(Exception):
    """The payment service answered: it has no such order."""


class UnsteadyPayments:
    """Drops the first ``outages`` requests, then refunds each known order once per key."""

    def __init__(self, orders: Iterable[str], outages: int) -> None:
        self.keys = []
        self.refunded = []
        self._orders = set(orders)
        self._outages = outages
        self._answers = {}

    def refund(self, order_id: str, key: str) -> dict[str, str]:
        self.keys.append(key)
        if self._outages > 0:
            self._outages -= 1
            raise PaymentsUnreachable("the payment service did not answer")
        if order_id not in self._orders:
            raise UnknownOrder(f"the payment service has no order {order_id}")
        if key not in self._answers:
            self.refunded.append(order_id)
            self._answers[key] = {"refunded": order_id}
        return self._answers[key]


class RefundOrderWithFailureKinds(Tool):
    def __init__(self, payments: UnsteadyPayments, retry: object | None = None) -> None:
        self._payments = payments
        self._retry = retry

    def name(self) -> str:
        return "refund_order"

    def description(self) -> str:
        return "Refund one order in full."

    def arguments(self) -> Record:
        return Record({"order_id": Text()})

    def retry(self) -> object | None:
        return self._retry

    async def run(self, arguments: dict[str, typing.Any], invocation: Invocation) -> typing.Any:
        try:
            return self._payments.refund(arguments["order_id"], invocation.key())
        except PaymentsUnreachable as error:
            raise ToolFailure(str(error), retryable=True) from None
        except UnknownOrder as error:
            raise ToolFailure(str(error)) from None

When the service gives a Retry-After, pass its seconds as ToolFailure(..., retryable=True, retry_after=seconds).

retry() returns None (the default for every tool: one attempt) or a Retry, and must return the same thing for the tool's whole life. Anything else is a TypeError naming the tool when a call reaches it: a broken tool definition, not a failed call. A tool built with gvn.shortcuts.FunctionTool takes it as retry=; the tools of gvn_tools take it as retry= too, and give it only to the tools that are safe to repeat (Built-in tools).

Declare the retry

Retry from gvn.harness.ports (the same class the ModelFulfiller takes for model calls; imported here as CallRetry, since the guide already uses the workflow's Retry from gvn.harness.workflow) says how many attempts one call may make and how long to wait between them: first_delay seconds, doubling up to longest_delay, spread by jitter. It sleeps on the clock you give it, normally the Governor's. The example uses the real clock with tiny delays so it finishes at once; a test passes a ManualClock and advances it. The ToolFulfiller itself takes only the toolbox.

from gvn.adapters.clock import SystemClock
from gvn.harness.ports import Retry as CallRetry


def refund_once(
    payments: UnsteadyPayments, name: str, order_id: str
) -> tuple[Result, MemoryJournal]:
    """Run one refund errand whose tool declares three attempts; return its result and journal."""
    journal = MemoryJournal()
    clock = SystemClock()
    three_attempts = CallRetry(
        attempts=3, clock=clock, first_delay=0.01, longest_delay=1.0, jitter=lambda: 0.0
    )
    refund_order = RefundOrderWithFailureKinds(payments=payments, retry=three_attempts)
    governor = Governor(
        fulfillers={
            "consult_policy": PolicyFulfiller(decision=AllowEverything()),
            "invoke_tools": ToolFulfiller(toolbox=Toolbox(tools=[refund_order])),
        },
        journal=journal,
        output=RecordingOutput(),
        clock=clock,
    )
    errand = refund_errand(name, order_id, memo=None)
    return asyncio.run(governor.deliver(actor=errand, event=Event("started"))), journal


unsteady = UnsteadyPayments(orders=["A-1", "B-2", "C-3"], outages=2)
result, journal = refund_once(unsteady, "refund-b2", "B-2")
print(result.outcome().state().name())
print(unsteady.refunded, len(unsteady.keys), len(set(unsteady.keys)))
records = asyncio.run(journal.read("refund-b2"))
(returned,) = [r["event"]["payload"] for r in records if r["event"]["name"] == "tools_returned"]
print(returned["retries"])
done
['B-2'] 3 1
{'refund': [{'reason': 'the payment service did not answer', 'waited': 0.005}, {'reason': 'the payment service did not answer', 'waited': 0.01}]}

The errand saw one successful result: the two failed attempts never reached it. The service saw the same key three times and refunded once. The journal's tools_returned carries "retries", call id to one entry per attempt given up on: its reason, the seconds waited before the next attempt, and the retry_after the failure asked for, when it did.

What is retried, exactly:

  • Only a call whose tool raised ToolFailure(..., retryable=True), until it succeeds, fails another way, or the Retry gives up: attempts used up, or a retry_after longer than longest_delay (that failure is reported at once, with its retry_after, for a scheduler to act on).
  • Never a call the policy or a person refused, a call to an unknown tool, invalid arguments, a ToolFailure that is not retryable, any other exception, or a result that is not JSON.
  • Every attempt carries the same idempotency key. A tool already has to tolerate that: a request re-issued after a crash repeats its calls with the same keys. A tool should still declare a Retry only when a repeat under one key is harmless right away (a pure read, or a service that honours the key), since a retry follows the lost attempt within seconds.
  • Each call follows its own tool's retry(): in one request, a search may be tried five times while a payment is tried once.
  • Independent calls that run together (Tool.independent()) retry each on its own; the results stay in call order.
  • A crash during the retries loses them: recovery fulfils the request again from each call's first attempt.

When the retries run out, a judge reads tool_error

If the service stays down, the last failure answers the call as tool_unavailable, and the errand ends failed, as it does when the service refuses. A plan that should treat the two differently reads the kind of each failed call with tool_error, from gvn.harness.tools: given a failed call's content (or an attempt's "detail") it returns the kind, one of TOOL_ERRORS, or None for a refusal's text. This Decision classifies a refund errand's outcome:

from gvn.harness.tools import TOOL_UNAVAILABLE, tool_error


class ReadRefund(Decision):
    """done; unavailable (the service could not be reached); or rejected (anything else)."""

    def outcomes(self) -> Alphabet:
        return Alphabet.of("done", "unavailable", "rejected")

    def judge(self, outcome: object) -> Symbol:
        if outcome.state().name() == "done":
            return Symbol("done")
        kinds = [
            tool_error(entry["detail"])
            for entry in outcome.payload()["attempts"]
            if entry["status"] == "failed"
        ]
        return Symbol("unavailable" if TOOL_UNAVAILABLE in kinds else "rejected")


down, _ = refund_once(UnsteadyPayments(orders=["B-2"], outages=5), "refund-b2-down", "B-2")
unknown, _ = refund_once(UnsteadyPayments(orders=["B-2"], outages=0), "refund-z0", "Z-0")
for each in (down, unknown):
    detail = each.outcome().payload()["attempts"][0]["detail"]
    print(each.outcome().state().name(), tool_error(detail), ReadRefund().decide(each.outcome()).name())
failed tool_unavailable unavailable
failed tool_rejected rejected

With it, the ForEach from Step 2 tries an item again later, as a new child, only when the service could not be reached, and never after a refusal:

patient_refunding = ForEach(
    actor_class=Errand,
    items=lambda memo: memo.input()["orders"],
    make=refund_errand,
    start=lambda order_id, memo: Event("started"),
    join=AllOf(success="done", reached="refunded", missed="not_refunded", classify=ReadRefund()),
    retry=Retry(attempts=3, on=["unavailable"], classify=ReadRefund()),
    window=2,
)

The two retries now work together: the tool's own Retry rides out a short outage within one request, with the same key; the ForEach comes back to an item whose outage lasted longer, with a new child and a new key, which is safe because the service did nothing the first time.

What a ForEach stores

While the stage runs, the workflow's stored form holds its children, each finished item's result and attempt number, and a 64-character fingerprint of the item list (a code computed from the list, which changes whenever the list does): not the items themselves. When a stored run is revived during the stage, items is called again and must give a list with the same fingerprint; if your data changed, the run refuses to load rather than retry the wrong orders. Measured on a payload-free child, each finished item adds about 115 bytes besides the child's own outcome.

Two more settings:

  • limit (default 1,000) caps the number of items; a longer list is a plan error.
  • An empty list is a plan error unless you give empty="no_orders", a symbol the stage ends with at once (and that your machine routes).

ForEach also takes deadline/expired (a time limit for the stage, and the symbol it ends with when the time is up) and retain (how many finished visits of a looping stage keep their full outcomes), as Host and FanOut do. At the deadline the attempts still running are cut (and recorded as abandoned), items not started yet are never started, and finished items keep their results. Workflows in depth has the details.

Recap

  • ForEach runs one child per item of a list read from trusted data, at most window at once.
  • gvn.harness.workflow.Retry(attempts=..., on=[...]) starts a failed item again, as a new child with a new name and new keys, a bounded number of times; the join sees each item's final result.
  • Result.attempt() says which attempt each result was.
  • The stored form holds a fingerprint of the items, not the items.
  • A tool raises ToolFailure(..., retryable=True) when its service could not be reached. A tool whose calls are safe to repeat declares retry() returning a gvn.harness.ports.Retry; the ToolFulfiller runs that call again, with the same key, and the journal's tools_returned lists the retries. A tool that declares nothing is tried once.
  • A judge reads a failed call's kind with tool_error: tool_unavailable or tool_rejected, among TOOL_ERRORS.

Next: to refund a charge only when a later step fails, and have the plan checked for it, read Undo that the verifier checks; to run a batch like this one from several processes and finish it after a crash, read Running as a service.