---
title: Survive flaky infrastructure
description: Keep an agent's run alive through a retry hint, a hanging backend, a panicking handler, a coded rate-limit error and a failing model provider, with every failure visible to the model and in Studio.
url: https://weftgo.dev/docs/examples/flaky-infrastructure/
type: how-to
sources:
  - 'weft/core/errors.go:135-157 (ToolError: Err stays out of the text), 163-172 (Errorf formats %w into Message), 203-214 (ModelRetry, MaxModelRetries, ErrModelRetriesExceeded)'
  - weft/core/tool.go:499-508 (Timeout)
  - weft/core/loop.go:1974-2002 (the timeout and panic texts)
  - weft/core/agent.go:196 (MaxModelRetries)
  - weft/core/loop.go:1104 (the run fails when a tool's RETRY count exceeds MaxModelRetries)
  - weft/mw/facade.go:73-97 (MaxRetries, BaseDelay, Classifier), 100-120 (Retry)
  - weft/core/mw/model.go:34 (Fallback)
  - weft/obsdb/problems.go:17-44 (AttemptsRetried, Fallbacks, ToolErrors)
  - weft/AGENTS.md:658-673 (rule 1), 698-700 (rule 9)
  - weft/example_test.go:252 (ExampleTimeout), 641 (ExampleModelRetry)
  - 'weft-arena/internal/suites/realworld.go: rwFlakyInfra; realworld_more.go: rwProviderFailures (inspiration only)'
  - docs-site/examples/cookbook/flaky/main.go, main_test.go TestFlaky, TestRetryHintsAreBounded, TestSiblingsKeepRunning
---

# Survive flaky infrastructure

A run survives broken backends because a tool's failure is data, not a Go error ([rule 1](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). A retry hint, a timeout, a panic and a coded error each become an error result the model reads, and the step's other calls keep running. Provider failures sit on the other seam: [`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry) and [`mw.Fallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Fallback) wrap the model and absorb them before the loop sees a run error.

The four misbehaving tools in `cookbook/flaky/main.go`:

```go title="cookbook/flaky/main.go"
func backends() []weft.Option {
	// A retry hint: the model sees "RETRY: <hint>" and calls again.
	inventory := weft.Tool("inventory_api", "Stock level for a SKU.",
		func(_ context.Context, in SKUInput) (string, error) {
			if in.SKU != strings.ToUpper(in.SKU) {
				return "", weft.ModelRetry("SKUs are uppercase, e.g. A-17: call inventory_api again")
			}
			return in.SKU + ": 42 units", nil
		})
	// A hang: the per-tool deadline turns it into an error result.
	shipping := weft.Tool("shipping_quote", "Shipping price to a city (slow upstream).",
		func(ctx context.Context, _ CityInput) (string, error) {
			start := time.Now()
			select {
			case <-time.After(time.Minute):
				return "12.50 EUR", nil
			case <-ctx.Done(): // honour ctx: the loop has already moved on
				select {
				case cancelled <- time.Since(start):
				default:
				}
				return "", ctx.Err()
			}
		},
		weft.Timeout(hangTimeout))
	// A panic: contained, reported as this call's error result.
	billing := weft.Tool("legacy_billing", "Balance of a billing account (legacy system).",
		func(_ context.Context, in AccountInput) (string, error) {
			var balances map[int]int
			balances[in.Account] = 0 // the legacy adapter's nil-map bug
			return "unreachable", nil
		})
	// A coded error: the model can branch on RATE_LIMITED.
	tax := weft.Tool("tax_service", "VAT rate for a region.",
		func(_ context.Context, in RegionInput) (string, error) {
			return "", weft.Errorf("RATE_LIMITED", "tax service quota exceeded for %s, retry after 60s", in.Region)
		})
	return []weft.Option{inventory, shipping, billing, tax}
}
```

[cookbook/flaky/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/flaky/main.go)

## How it works

The shape comes from the weft-arena scenarios `rw.flaky-infra` and `rw.provider-failures`. An ops agent asks four backends for stock, shipping, billing and tax in one step. Each fails the way production backends do. Meanwhile the model provider answers its first request with a 503, works for two calls, then goes down.

What the model sees for each call:

| Backend | Failure | Result the model reads |
|---|---|---|
| `inventory_api` | lowercase SKU | `RETRY: SKUs are uppercase, e.g. A-17: call inventory_api again` |
| `shipping_quote` | hangs for a minute | `tool "shipping_quote" timed out after 200ms` |
| `legacy_billing` | nil-map panic | `tool "legacy_billing" panicked: assignment to entry in nil map` |
| `tax_service` | quota exceeded | `RATE_LIMITED: tax service quota exceeded for EU, retry after 60s` |

All four are `ToolResultPart{IsError: true}`. In the next step the model calls `inventory_api` again with `A-17`, and that call succeeds.

## Retry hints

[`weft.ModelRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRetry) is for arguments that are well-formed but wrong in a way the model can fix. The model sees `RETRY: <hint>` and calls again. The loop counts `RETRY` results per tool name per run, and a successful result for that tool resets the count. A tool that keeps asking fails the run with `ErrModelRetriesExceeded` once its consecutive `RETRY` results exceed [`weft.MaxModelRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries): the 4th, under the default 3. This recipe sets it explicitly:

```go title="cookbook/flaky/main.go"
opts := append(backends(),
	weft.Name("ops-probe"),
	weft.MaxSteps(8),
	weft.MaxModelRetries(3), // RETRY results per tool before the run fails
	weft.WrapModel(
		mw.Fallback(backup), // outermost: when the retried primary still fails
		mw.Retry(mw.MaxRetries(2), mw.BaseDelay(10*time.Millisecond),
			mw.Classifier(func(err error) bool { return errors.Is(err, errOverloaded) })),
	),
)
agt := weft.New(primary, opts...)
```

[cookbook/flaky/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/flaky/main.go)

The package example [`ExampleModelRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-ModelRetry) shows the loop on its own: a date in the wrong format, the hint, and the corrected call.

## Hung tools

[`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) on a tool sets that call's deadline ([rule 9](https://github.com/weftgo/weft/blob/v0.20.2/AGENTS.md#the-rules-do-not-break-these-tests-pin-them)). When it expires the loop records `tool "shipping_quote" timed out after 200ms` and moves on; the run never waits for the minute-long upstream. The loop abandons the handler's goroutine, so the handler must honour `ctx` to release what it holds. `shipping_quote` returns on `ctx.Done()`, and the program checks that it did.

Without any `Timeout`, only the run's own `ctx` bounds a call. On the agent, `weft.Timeout` is the default for every tool without its own. The package example [`ExampleTimeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#example-Timeout) is the same deadline in ten lines.

## Panics and coded errors

A handler panic is contained: it becomes this call's error result, `tool "legacy_billing" panicked: …`, and its siblings finish normally. [`weft.Errorf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Errorf) builds a [`*weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError). The model sees `CODE: message` and can branch on `RATE_LIMITED`. With `weft.Errorf`, a `%w` cause's text is part of the message the model reads, and the cause stays reachable with `errors.Is` and `errors.As`. To keep a cause out of the model's text, build `&weft.ToolError{Code: …, Message: …, Err: cause}` directly.

## Retry, then fall back

`weft.WrapModel` lists model middleware outermost first. `mw.Retry` retries a call that fails before yielding any event; `mw.Classifier` names what counts as transient. `mw.Fallback` sits outside it and tries the backup model when the retried primary still fails:

- Attempt 1 fails with the 503, and `mw.Retry` tries again about 10 ms later (each delay carries ±25% jitter). Attempt 2 returns step 0's four calls.
- Attempt 3 returns step 1's corrected call.
- Attempts 4, 5 and 6 fail. With `MaxRetries(2)` that exhausts the retries, so `mw.Fallback` asks the backup, which writes the answer.

A failure after the model yielded events is never retried or fallen back: part of the reply already reached the loop. See [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/) for the defaults (3 retries, 500 ms doubling to 8 s) and the provider's retry-after.

## What to look at in Studio

The run succeeds, so Studio shows a green run with problems inside it. The program reads the run page's problem counters back from the local sink: `attempts_retried=4`, `fallbacks=1`, `tool_errors=3`.

![The ops-probe run of rw.flaky-infra on the waterfall: inventory_api marked retry 1/3, tax_service RATE_LIMITED, shipping_quote timed out at 300 ms and legacy_billing panicked, with the selected call's details in the drawer](https://weftgo.dev/docs/_astro/studio-run-flaky.light.esXYYcMg.webp)

*weft-arena's rw.flaky-infra on the run page's waterfall: the retry hint, the RATE_LIMITED error, the timeout and the panic, each on its own call.*

- **Attempts.** Each step's `chat` span carries an `attempt` span per try. The four failed tries count as retried, the backup's success as one fallback.
- **Tool errors.** `RETRY` results are not counted: they are the intended repair loop. The timeout, the panic and `RATE_LIMITED` are, which makes 3.
- **The drawer.** Select a call on the waterfall to read its arguments and its error result.

The counters are defined on [`obsdb.Problems`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Problems); [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/) explains the page.

## The weft features it combines

| Feature | What it does here | Guide |
|---|---|---|
| `weft.ModelRetry`, `MaxModelRetries` | asks the model to fix its arguments, boundedly | [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/) |
| `weft.Timeout` on a tool | turns a hang into an error result | [Set per-tool policy](https://weftgo.dev/docs/guides/tool-policy/) |
| Panic containment | turns a panic into an error result | [How do tools work?](https://weftgo.dev/docs/concepts/tools/) |
| `weft.Errorf` | gives the model a code to branch on | [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/) |
| `mw.Retry`, `mw.Fallback` | absorb the provider's failures | [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/) |
| Problem counters | count what went wrong inside a green run | [Read a run in Studio](https://weftgo.dev/docs/observe/studio/run-page/) |

## The program

```go title="cookbook/flaky/main.go"
// Command flaky is the recipe "Survive flaky infrastructure":
// go run ./cookbook/flaky. Four backends misbehave in one step — a retry
// hint, a hang, a panic and a coded rate-limit error — while the model
// provider itself fails transiently and then goes down. The run
// succeeds: every tool failure reaches the model as an error result, and
// mw.Retry and mw.Fallback absorb the provider's. The models are scripted
// with wefttest, so it runs offline; the run is recorded to the local
// sink ($WEFT_DB, else ./.weft/weft.db).
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"iter"
	"os"
	"strings"
	"sync/atomic"
	"time"

	"github.com/weftgo/weft"
	"github.com/weftgo/weft/mw"
	"github.com/weftgo/weft/otel"
	"github.com/weftgo/weft/wefttest"
)

type SKUInput struct {
	SKU string `json:"sku" jsonschema:"the SKU, uppercase, e.g. A-17"`
}

type CityInput struct {
	City string `json:"city" jsonschema:"the destination city"`
}

type AccountInput struct {
	Account int `json:"account" jsonschema:"account number"`
}

type RegionInput struct {
	Region string `json:"region" jsonschema:"region code, e.g. EU"`
}

// hangTimeout is shipping_quote's deadline.
const hangTimeout = 200 * time.Millisecond

// cancelled receives how long the hung handler waited before its ctx
// was cancelled.
var cancelled = make(chan time.Duration, 1)

func backends() []weft.Option {
	// A retry hint: the model sees "RETRY: <hint>" and calls again.
	inventory := weft.Tool("inventory_api", "Stock level for a SKU.",
		func(_ context.Context, in SKUInput) (string, error) {
			if in.SKU != strings.ToUpper(in.SKU) {
				return "", weft.ModelRetry("SKUs are uppercase, e.g. A-17: call inventory_api again")
			}
			return in.SKU + ": 42 units", nil
		})
	// A hang: the per-tool deadline turns it into an error result.
	shipping := weft.Tool("shipping_quote", "Shipping price to a city (slow upstream).",
		func(ctx context.Context, _ CityInput) (string, error) {
			start := time.Now()
			select {
			case <-time.After(time.Minute):
				return "12.50 EUR", nil
			case <-ctx.Done(): // honour ctx: the loop has already moved on
				select {
				case cancelled <- time.Since(start):
				default:
				}
				return "", ctx.Err()
			}
		},
		weft.Timeout(hangTimeout))
	// A panic: contained, reported as this call's error result.
	billing := weft.Tool("legacy_billing", "Balance of a billing account (legacy system).",
		func(_ context.Context, in AccountInput) (string, error) {
			var balances map[int]int
			balances[in.Account] = 0 // the legacy adapter's nil-map bug
			return "unreachable", nil
		})
	// A coded error: the model can branch on RATE_LIMITED.
	tax := weft.Tool("tax_service", "VAT rate for a region.",
		func(_ context.Context, in RegionInput) (string, error) {
			return "", weft.Errorf("RATE_LIMITED", "tax service quota exceeded for %s, retry after 60s", in.Region)
		})
	return []weft.Option{inventory, shipping, billing, tax}
}

// errOverloaded stands in for a provider's HTTP 503.
var errOverloaded = errors.New("503: overloaded")

// flakyModel fails the attempts its schedule names before yielding any
// event, the way a provider outage does; the other attempts go through
// to the scripted model underneath.
type flakyModel struct {
	next     weft.Model
	attempts atomic.Int32
	fails    func(attempt int32) bool
}

func (m *flakyModel) Info() weft.ModelInfo { return weft.ModelInfo{Provider: "primary", Name: "flaky"} }

func (m *flakyModel) Stream(ctx context.Context, req weft.ModelRequest) iter.Seq2[weft.ModelEvent, error] {
	if m.fails(m.attempts.Add(1)) {
		return func(yield func(weft.ModelEvent, error) bool) { yield(nil, errOverloaded) }
	}
	return m.next.Stream(ctx, req)
}

// newAgent builds the ops agent over a primary model that fails its
// first attempt and is down from its fourth on.
func newAgent() (*weft.Agent, *flakyModel) {
	primary := &flakyModel{
		next: wefttest.Script(
			wefttest.ToolCalls(
				wefttest.Call{ID: "c1", Name: "inventory_api", Args: `{"sku":"a-17"}`},
				wefttest.Call{ID: "c2", Name: "shipping_quote", Args: `{"city":"Lima"}`},
				wefttest.Call{ID: "c3", Name: "legacy_billing", Args: `{"account":9}`},
				wefttest.Call{ID: "c4", Name: "tax_service", Args: `{"region":"EU"}`},
			),
			wefttest.ToolCalls(wefttest.Call{ID: "c5", Name: "inventory_api", Args: `{"sku":"A-17"}`}),
		),
		fails: func(n int32) bool { return n == 1 || n >= 4 },
	}
	backup := wefttest.Script(wefttest.Say("A-17: 42 units. Shipping timed out, billing crashed, tax is rate limited."))
	opts := append(backends(),
		weft.Name("ops-probe"),
		weft.MaxSteps(8),
		weft.MaxModelRetries(3), // RETRY results per tool before the run fails
		weft.WrapModel(
			mw.Fallback(backup), // outermost: when the retried primary still fails
			mw.Retry(mw.MaxRetries(2), mw.BaseDelay(10*time.Millisecond),
				mw.Classifier(func(err error) bool { return errors.Is(err, errOverloaded) })),
		),
	)
	agt := weft.New(primary, opts...)
	return agt, primary
}

func run(ctx context.Context, w io.Writer) error {
	defer otel.Install(otel.Local(""))()

	agt, primary := newAgent()
	res, err := agt.Generate(ctx, weft.Prompt("Check stock for a-17, a shipping quote to Lima, the balance of account 9 and the EU VAT rate."))
	if err != nil {
		return err // a run error: none of the failures above is one
	}
	for i, st := range res.Steps {
		for _, r := range st.Results {
			fmt.Fprintf(w, "step %d %s → %s (error: %t)\n", i, r.Name, r.Content, r.IsError)
		}
	}
	fmt.Fprintln(w, "answer:", res.Text())
	fmt.Fprintln(w, "primary attempts:", primary.attempts.Load())
	if d := <-cancelled; d < time.Second {
		fmt.Fprintln(w, "hung handler saw ctx cancelled: true")
	}

	// The run page's problem counters, from the recorded spans.
	row, err := otel.LocalDB().Run(ctx, res.ID)
	if err != nil {
		return err
	}
	p := row.Problems
	fmt.Fprintf(w, "recorded: status=%s attempts_retried=%d fallbacks=%d tool_errors=%d\n",
		row.Status, p.AttemptsRetried, p.Fallbacks, p.ToolErrors)
	return nil
}

func main() {
	if err := run(context.Background(), os.Stdout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
```

[cookbook/flaky/main.go on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/cookbook/flaky/main.go)

[View on GitHub](https://github.com/weftgo/weftgo.dev/tree/main/docs-site/examples/cookbook/flaky) · run it from `docs-site/examples`:

```sh
go run ./cookbook/flaky
go test ./cookbook/flaky
```

```text
step 0 inventory_api → RETRY: SKUs are uppercase, e.g. A-17: call inventory_api again (error: true)
step 0 shipping_quote → tool "shipping_quote" timed out after 200ms (error: true)
step 0 legacy_billing → tool "legacy_billing" panicked: assignment to entry in nil map (error: true)
step 0 tax_service → RATE_LIMITED: tax service quota exceeded for EU, retry after 60s (error: true)
step 1 inventory_api → A-17: 42 units (error: false)
answer: A-17: 42 units. Shipping timed out, billing crashed, tax is rate limited.
primary attempts: 6
hung handler saw ctx cancelled: true
recorded: status=succeeded attempts_retried=4 fallbacks=1 tool_errors=3
```

The tests also pin that a tool which keeps answering `RETRY` fails the run with `ErrModelRetriesExceeded`, and that the results stay in call order whatever order the calls finished in.

## Best practices & gotchas

- **Honour `ctx` in every handler.** A timed-out handler's goroutine is abandoned, not killed; one that ignores `ctx` keeps its connection and memory until it returns. (Source: `weft/core/tool.go:499-507`, AGENTS.md rule 9)
- **Use `ModelRetry` only for what the model can fix.** A backend outage is not one: return a coded `ToolError` and let the model report it, or the run spends its retries and fails. (Source: `weft/core/errors.go:203-211`)
- **Put `mw.Fallback` outside `mw.Retry`.** First listed is outermost, so the backup is tried only after the primary's retries are spent. (Source: AGENTS.md rule 10, `weft/core/mw/model.go:34` godoc)
- **Classify transient errors.** The default classifier retries 408, 409, 429, 5xx, idle streams and network errors; a provider error without a status needs `mw.Classifier`. (Source: `weft/mw/facade.go:91-97`)
- **Keep internal detail out of tool errors.** The error text is what the model reads; `mw.MapErrors` hides an uncoded error behind `INTERNAL: tool "x" failed`. (Source: `weft/core/mw/tool.go:104` godoc)

## See also

- [Tool errors are data, run errors are yours](https://weftgo.dev/docs/concepts/errors/): the error model these failures follow
- [Retry and fall back when a provider fails](https://weftgo.dev/docs/guides/retries-and-fallback/)
- [Set per-tool policy: timeouts, caps, ordering and strict input](https://weftgo.dev/docs/guides/tool-policy/)
- [Guard against runaway agents](https://weftgo.dev/docs/examples/budget-guards/): the failures that do end a run

Symbols used: [`weft.ModelRetry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRetry) · [`weft.MaxModelRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#MaxModelRetries) · [`weft.ErrModelRetriesExceeded`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRetriesExceeded) · [`weft.Timeout`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Timeout) · [`weft.Errorf`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Errorf) · [`weft.ToolError`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ToolError) · [`weft.WrapModel`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#WrapModel) · [`weft.ModelRequest`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelRequest) · [`weft.ModelEvent`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelEvent) · [`weft.ModelInfo`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ModelInfo) · [`mw.Retry`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Retry) · [`mw.MaxRetries`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MaxRetries) · [`mw.BaseDelay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#BaseDelay) · [`mw.Classifier`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Classifier) · [`mw.Fallback`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#Fallback) · [`mw.MapErrors`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/mw#MapErrors) · [`obsdb.Problems`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/obsdb#Problems) · [`otel.Install`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#Install) · [`otel.LocalDB`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/otel#LocalDB) · [`wefttest.Script`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Script)
