Survive flaky infrastructure
A run survives broken backends because a tool’s failure is data, not a Go error (rule 1). 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 and mw.Fallback wrap the model and absorb them before the loop sees a run error.
The four misbehaving tools in 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}}How it works
Section titled “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
Section titled “Retry hints”weft.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: the 4th, under the default 3. This recipe sets it explicitly:
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...)The package example ExampleModelRetry shows the loop on its own: a date in the wrong format, the hint, and the corrected call.
Hung tools
Section titled “Hung tools”weft.Timeout on a tool sets that call’s deadline (rule 9). 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 is the same deadline in ten lines.
Panics and coded errors
Section titled “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 builds a *weft.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
Section titled “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.Retrytries 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, somw.Fallbackasks 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 for the defaults (3 retries, 500 ms doubling to 8 s) and the provider’s retry-after.
What to look at in Studio
Section titled “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.


- Attempts. Each step’s
chatspan carries anattemptspan per try. The four failed tries count as retried, the backup’s success as one fallback. - Tool errors.
RETRYresults are not counted: they are the intended repair loop. The timeout, the panic andRATE_LIMITEDare, 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; Read a run in Studio explains the page.
The weft features it combines
Section titled “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 |
weft.Timeout on a tool | turns a hang into an error result | Set per-tool policy |
| Panic containment | turns a panic into an error result | How do tools work? |
weft.Errorf | gives the model a code to branch on | Tool errors are data, run errors are yours |
mw.Retry, mw.Fallback | absorb the provider’s failures | Retry and fall back when a provider fails |
| Problem counters | count what went wrong inside a green run | Read a run in Studio |
The program
Section titled “The program”// 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) }}View on GitHub · run it from docs-site/examples:
go run ./cookbook/flakygo test ./cookbook/flakystep 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: 6hung handler saw ctx cancelled: truerecorded: status=succeeded attempts_retried=4 fallbacks=1 tool_errors=3The 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
Section titled “Best practices & gotchas”- Honour
ctxin every handler. A timed-out handler’s goroutine is abandoned, not killed; one that ignoresctxkeeps its connection and memory until it returns. (Source:weft/core/tool.go:499-507, AGENTS.md rule 9) - Use
ModelRetryonly for what the model can fix. A backend outage is not one: return a codedToolErrorand let the model report it, or the run spends its retries and fails. (Source:weft/core/errors.go:203-211) - Put
mw.Fallbackoutsidemw.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:34godoc) - 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.MapErrorshides an uncoded error behindINTERNAL: tool "x" failed. (Source:weft/core/mw/tool.go:104godoc)
See also
Section titled “See also”- Tool errors are data, run errors are yours: the error model these failures follow
- Retry and fall back when a provider fails
- Set per-tool policy: timeouts, caps, ordering and strict input
- Guard against runaway agents: the failures that do end a run
Symbols used: weft.ModelRetry · weft.MaxModelRetries · weft.ErrModelRetriesExceeded · weft.Timeout · weft.Errorf · weft.ToolError · weft.WrapModel · weft.ModelRequest · weft.ModelEvent · weft.ModelInfo · mw.Retry · mw.MaxRetries · mw.BaseDelay · mw.Classifier · mw.Fallback · mw.MapErrors · obsdb.Problems · otel.Install · otel.LocalDB · wefttest.Script