---
title: Record a real conversation once, replay it forever
description: 'Wrap a real provider in wefttest.Record to write one JSON fixture per model request, then replay the fixtures with wefttest.Replay in CI: offline, deterministic, no key.'
url: https://weftgo.dev/docs/testing/record-replay/
type: how-to
sources:
  - weft/core/wefttest/replay.go:23 (ErrNoFixture), 25-46 (Record godoc and the WEFT_RECORD pattern), 48-66 (Replay godoc), 68-117 (the key, canonical, FNV-64a), 119-152 (the file and its event envelope), 194-206 (dir/<test>/<seq:05d>-<key>.json), 228-296 (the recorder replaces the directory, a write failure fails the stream), 298-327 (abandoned streams), 344-368 (load once, a corrupt file fails construction), 378-424 (miss, recorded order), 428-445 (sentinels re-wrapped)
  - weft/core/wefttest/golden.go:13-66 (Golden, -update)
  - weft/wefttest/facade.go:35-50 (Golden), 125 (ErrNoFixture), 148 (Record), 164 (Replay)
  - weft/core/wefttest/example_test.go:73 (ExampleReplay)
  - weft/docs/adr/0017-testing-conventions.md (the replay seam, the key table, the file, misses are loud, T1-T13, C1-C6, the ToolChoice amendment)
  - weft/docs/adr/0017-record-replay.md (the five-digit sequence pad)
  - 'weft/docs/adr/0013-adapter-contract.md (Fixtures and live runs: wire fixtures stay the adapter proof)'
  - weft/AGENTS.md:637-641 (replay a recorded real transcript; parsing proven by conformance)
  - weft/README.md:1046-1064 (record once and replay forever; fixtures are pretty JSON; re-recording is the review)
  - weft/CHANGELOG.md:6126-6142 (0.2.0 Record and Replay)
  - weft/core/wefttest/replay.go:222-226, 372-376 (Requests on the recorder and the replayer); weft/core/wefttest/replay_test.go:507 (TestReplayRecordsRequests)
  - weft/core/wefttest/replay_test.go:231 (TestReplayPlaysRecordedEvents), 274 (TestReplayKeyIgnoresSystem), 306 (TestReplayKeyDistinguishes), 350 (TestReplayRepeatedRequestsInOrder), 378 (TestReplayMissIsLoud), 458 (TestReplaySubagent), 496 (TestReplayMissingDir), 557 (TestReplayKeyToolChoice)
  - docs-site/examples/testing/replay_test.go (TestWhereIsOrder, TestGolden), testdata/replay/TestWhereIsOrder/, testdata/provider/where-is-1234.sse
---

# Record a real conversation once, replay it forever

[`wefttest.Record`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Record) wraps a real model and writes every request it receives, with the stream the model answered, as one JSON [fixture](https://weftgo.dev/docs/reference/glossary/#fixture) file. [`wefttest.Replay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Replay) is a model that answers each request from those files. Record once on your machine, with a key; commit the fixtures; replay in CI with no key and no network. Your agent's tools, prompts, middleware and loop configuration run unchanged above either one.

The suite's switch, from `testing/replay_test.go`:

```go title="testing/replay_test.go"
// model is the suite's recording switch: WEFT_RECORD=1 records against
// the provider, anything else replays the committed fixtures.
func model(t *testing.T) weft.Model {
	if os.Getenv("WEFT_RECORD") != "" {
		return wefttest.Record(t, "testdata/replay", provider(t))
	}
	return wefttest.Replay(t, "testdata/replay")
}
```

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

## Record once, replay forever

Both functions take the `*testing.T` and a directory; the fixtures live in `<dir>/<t.Name()>/`, so each test, and each subtest, has its own. The test itself does not know which model it got:

```go title="testing/replay_test.go"
func TestWhereIsOrder(t *testing.T) {
	ctx := context.Background()
	res, err := support.New(model(t)).Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		t.Fatal(err)
	}
	if got, want := res.Text(), "Order 1234 shipped yesterday."; got != want {
		t.Errorf("answer = %q, want %q", got, want)
	}
	if len(res.Steps) != 2 || res.Steps[0].ToolCalls[0].Name != "lookup_order" {
		t.Errorf("steps = %+v, want a lookup_order call, then the answer", res.Steps)
	}
```

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

`provider(t)` is the real model. On this page it is the OpenAI adapter over a local server that serves two recorded streams, so the docs run offline; in your suite it holds your key:

```go title="testing/replay_test.go"
// provider is the real model a recording calls. Here it is the OpenAI
// adapter over a local stand-in that serves two recorded streams, so the
// docs run offline. In your suite it holds the key:
// openai.Model("gpt-5", openai.APIKey(os.Getenv("OPENAI_API_KEY"))).
func provider(t *testing.T) weft.Model {
	srv := conformance.FixtureServer(t, "testdata/provider/where-is-1234.sse")
	c := openaisdk.NewClient(option.WithBaseURL(srv.URL), option.WithAPIKey("test"))
	return openai.Model("gpt-5", openai.Client(&c))
}
```

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

Record once, from `docs-site/examples`:

```sh
WEFT_RECORD=1 go test ./testing -run TestWhereIsOrder -v
```

```text
=== RUN   TestWhereIsOrder
--- PASS: TestWhereIsOrder (0.00s)
PASS
ok  	weftgo.dev/docs/examples/testing	0.005s
```

The run wrote one file per model call, in conversation order:

```text
testing/testdata/replay/TestWhereIsOrder/
├── 00001-58a3644d032e0bef.json
└── 00002-1fa524c48314c90e.json
```

Commit them. Every later `go test` replays them; no request leaves the process, and `Replay` ignores `WEFT_MODEL_REQUESTS`, so the test passes under deny too.

`WEFT_RECORD` is a name the godoc suggests, not one weft reads: wefttest reads no recording flag and no variable (its one flag is `Golden`'s `-update`). A golden file's `-update` only rewrites a comparison, while recording spends money, so the switch belongs to the suite that holds the key. `Record` itself never checks `WEFT_MODEL_REQUESTS`: the inner model does, so a recording made under deny stores the denial and the diff shows it.

## What a fixture holds

The file name is `<seq>-<key>.json`: a five-digit, 1-based sequence number, so a listing reads in order and two identical requests never collide, and the 16-hex-digit request key `Replay` matches on. The second request of the recording above, `00002-1fa524c48314c90e.json`:

```json title="testing/testdata/replay/TestWhereIsOrder/00002-1fa524c48314c90e.json"
{
  "model": {
    "provider": "openai",
    "name": "gpt-5"
  },
  "request": {
    "system": "You are a support agent. Look an order up before you answer.",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "Where is order 1234?"
          }
        ]
      },
      {
        "role": "assistant",
        "content": [
          {
            "type": "tool_call",
            "id": "call_8f2a",
            "name": "lookup_order",
            "args": {
              "order_id": "1234"
            }
          }
        ]
      },
      {
        "role": "tool",
        "content": [
          {
            "type": "tool_result",
            "call_id": "call_8f2a",
            "name": "lookup_order",
            "content": "order 1234 shipped yesterday",
            "is_error": false
          }
        ]
      }
    ],
    "tools": [
      "lookup_order"
    ]
  },
  "events": [
    {
      "type": "text",
      "text": "Order 1234 shipped "
    },
    {
      "type": "text",
      "text": "yesterday."
    },
    {
      "type": "finish",
      "reason": "stop",
      "usage": {
        "input_tokens": 97,
        "output_tokens": 9
      }
    }
  ],
  "error": ""
}
```

[testing/testdata/replay/TestWhereIsOrder/00002-1fa524c48314c90e.json on GitHub](https://github.com/weftgo/weftgo.dev/blob/main/docs-site/examples/testing/testdata/replay/TestWhereIsOrder/00002-1fa524c48314c90e.json)

- `model` is the inner model's `Info`. `Replay`'s own `Info` is the first fixture's.
- `request` is what the agent sent: the system prompt, for the reviewer, and the keyed fields.
- `events` are the model's stream in wefttest's own envelope: `text`, `reasoning` (with its signature), `tool_call` (arguments as a JSON value), `tool_call_delta` and `finish` (reason, raw reason, usage).
- `error` is the stream error's text, `""` when there was none. A caller that broke out of the stream still leaves a file, with `"error": "wefttest: stream abandoned by the caller"`.

`Record` replaces the test's directory on its first request; it never merges, because merging is how stale entries survive a prompt change. A fixture that cannot be written fails the stream, so a half-written recording is loud.

## Replay

`Replay` reads the test's directory once, when you call it. Each request is hashed (FNV-64a) over its canonical JSON and answered by the fixture with that key:

| Request field | Keyed? |
|---|---|
| Messages | Yes, verbatim, call ids included |
| Tool names | Yes, sorted; descriptions and schemas are not |
| Thinking (level and budget) | Yes, omitted when zero |
| Tool choice | Yes, omitted when zero |
| Sequential flag | Yes, omitted when false |
| System prompt | No: recorded for the reviewer, so a wording change does not invalidate every fixture |
| Params (temperature, max tokens, …) | No |

Identical requests, a retry or a re-ask, replay in recorded order. A recorded stream error replays as an error with the same text; when the text starts with one of weft's sentinels (`weft.ErrModelRequestsDenied`, `weft.ErrStreamIdle`, …), it is wrapped so `errors.Is` still holds. A vendor's error type is not kept.

The models `Record` and `Replay` return also implement `Requests() []weft.ModelRequest`, as a script does, so a replayed test can assert on what the agent asked: `m.(interface{ Requests() []weft.ModelRequest }).Requests()`.

The godoc example [`ExampleReplay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#example-Replay) shows the same switch as a comment: an example has no `*testing.T` to pass.

## When a request misses

A request no fixture answers fails the stream with [`wefttest.ErrNoFixture`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ErrNoFixture), and the run fails with it. Change the prompt and replay the same fixtures:

```go title="testing/replay_test.go"
// The same fixtures, a changed prompt: no fixture answers the request.
_, err = support.New(wefttest.Replay(t, "testdata/replay")).Generate(ctx, weft.Prompt("Where is order 5678?"))
if !errors.Is(err, wefttest.ErrNoFixture) {
	t.Fatalf("err = %v, want ErrNoFixture", err)
}
t.Log(err)
```

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

```sh
go test ./testing -run TestWhereIsOrder -v
```

```text
=== RUN   TestWhereIsOrder
    replay_test.go:55: weft: run failed at step 0: model stream: wefttest: no replay fixture for this request: testdata/replay/TestWhereIsOrder key 7154df7a9769d657 (first user text "Where is order 5678?")
--- PASS: TestWhereIsOrder (0.00s)
```

The error names the fixture directory, the key that was wanted and the first user message's opening words. The causes are a request that changed since the recording (a new tool, a changed transcript, a different thinking level), a test that was renamed, or a fresh checkout without the fixtures. A missing directory is not an error until the first request; a file that does not decode fails `Replay` at once, as corruption.

A replayed transcript cannot drift from its recording; what the key leaves out (the system prompt, `Params`, tool descriptions and schemas) can change and the run still replays. A [steer](https://weftgo.dev/docs/guides/steering/#steer-deterministically-in-tests) delivered with `wefttest.NewSteers` is part of the next request's transcript, so a steer that differs from the recorded one misses its fixture.

## Fixtures are reviewed

Fixtures are pretty-printed JSON written to be read in a diff: a changed prompt shows as changed request messages, a changed answer as changed events. Re-recording is the review.

To refresh a test's fixtures, record it again and read the diff before you commit:

```sh
WEFT_RECORD=1 go test ./testing -run TestWhereIsOrder
git diff --stat testing/testdata/replay
```

A request that changed gets a new key, so its file is renamed; a file that is gone is a request the agent no longer makes. There is no normalisation of timestamps or ids in the key: keep prompts deterministic, and the miss error tells you which request drifted.

## What replay does not prove

Replay sits at the `weft.Model` seam, where `Record` saw the adapter's output as model events. It tests your application against what a model said; the fixture replays the same whichever adapter recorded it. It does not test the adapter. Whether `weft/openai` parses OpenAI's wire format is proven by the [conformance suite](https://weftgo.dev/docs/testing/conformance/) against recorded `.sse` bytes ([ADR 0013](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0013-adapter-contract.md)), and replay replaces nothing there ([ADR 0017](https://github.com/weftgo/weft/blob/v0.20.2/docs/adr/0017-testing-conventions.md)).

## Golden files

[`wefttest.Golden`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Golden) compares bytes with a committed file. Use it for output your agent produces: a transcript, a manifest, a rendered report. From `testing/replay_test.go`:

```go title="testing/replay_test.go"
b, err := json.MarshalIndent(res.Messages, "", "  ")
if err != nil {
	t.Fatal(err)
}
wefttest.Golden(t, filepath.Join("testdata", "transcript.golden.json"), append(b, '\n'))
```

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

`go test ./testing -update` writes the file and logs which files it created or rewrote; an up-to-date file is left alone. Without `-update`, a mismatch fails with a line diff:

```text
--- FAIL: TestGolden (0.00s)
    facade.go:50: golden file testdata/transcript.golden.json is stale; regenerate with `go test ./... -update` and commit the result.
        diff (- committed, + generated):
        -         "text": "Order 1234 shipped on Monday."
        +         "text": "Order 1234 shipped yesterday."
```

Put `-update` after the package list: placed before it, the go tool hands it to the wrong test binary.

## Complete example

`testing/replay_test.go` holds the switch, the provider stand-in, the miss and the golden test:

```go title="testing/replay_test.go"
package main

import (
	"context"
	"encoding/json"
	"errors"
	"os"
	"path/filepath"
	"testing"

	openaisdk "github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
	"github.com/weftgo/weft"
	"github.com/weftgo/weft/openai"
	"github.com/weftgo/weft/wefttest"
	"github.com/weftgo/weft/wefttest/conformance"
	"weftgo.dev/docs/examples/testing/support"
)

// model is the suite's recording switch: WEFT_RECORD=1 records against
// the provider, anything else replays the committed fixtures.
func model(t *testing.T) weft.Model {
	if os.Getenv("WEFT_RECORD") != "" {
		return wefttest.Record(t, "testdata/replay", provider(t))
	}
	return wefttest.Replay(t, "testdata/replay")
}

func TestWhereIsOrder(t *testing.T) {
	ctx := context.Background()
	res, err := support.New(model(t)).Generate(ctx, weft.Prompt("Where is order 1234?"))
	if err != nil {
		t.Fatal(err)
	}
	if got, want := res.Text(), "Order 1234 shipped yesterday."; got != want {
		t.Errorf("answer = %q, want %q", got, want)
	}
	if len(res.Steps) != 2 || res.Steps[0].ToolCalls[0].Name != "lookup_order" {
		t.Errorf("steps = %+v, want a lookup_order call, then the answer", res.Steps)
	}
	if os.Getenv("WEFT_RECORD") != "" {
		return
	}
	// The same fixtures, a changed prompt: no fixture answers the request.
	_, err = support.New(wefttest.Replay(t, "testdata/replay")).Generate(ctx, weft.Prompt("Where is order 5678?"))
	if !errors.Is(err, wefttest.ErrNoFixture) {
		t.Fatalf("err = %v, want ErrNoFixture", err)
	}
	t.Log(err)
}

// provider is the real model a recording calls. Here it is the OpenAI
// adapter over a local stand-in that serves two recorded streams, so the
// docs run offline. In your suite it holds the key:
// openai.Model("gpt-5", openai.APIKey(os.Getenv("OPENAI_API_KEY"))).
func provider(t *testing.T) weft.Model {
	srv := conformance.FixtureServer(t, "testdata/provider/where-is-1234.sse")
	c := openaisdk.NewClient(option.WithBaseURL(srv.URL), option.WithAPIKey("test"))
	return openai.Model("gpt-5", openai.Client(&c))
}

// TestGolden compares the scripted run's transcript with a committed file.
// Regenerate it with: go test ./testing -run TestGolden -update
func TestGolden(t *testing.T) {
	model := wefttest.Script(
		wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}),
		wefttest.Say("Order 1234 shipped yesterday."),
	)
	res, err := support.New(model).Generate(context.Background(), weft.Prompt("Where is order 1234?"))
	if err != nil {
		t.Fatal(err)
	}
	b, err := json.MarshalIndent(res.Messages, "", "  ")
	if err != nil {
		t.Fatal(err)
	}
	wefttest.Golden(t, filepath.Join("testdata", "transcript.golden.json"), append(b, '\n'))
}
```

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

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

```sh
WEFT_MODEL_REQUESTS=deny go test ./testing -run 'TestWhereIsOrder|TestGolden' -v
```

```text
=== RUN   TestWhereIsOrder
    replay_test.go:55: weft: run failed at step 0: model stream: wefttest: no replay fixture for this request: testdata/replay/TestWhereIsOrder key 7154df7a9769d657 (first user text "Where is order 5678?")
--- PASS: TestWhereIsOrder (0.00s)
=== RUN   TestGolden
--- PASS: TestGolden (0.00s)
PASS
ok  	weftgo.dev/docs/examples/testing	0.003s
```

## Best practices & gotchas

- **Never record in CI.** `Record` makes paid requests with your key; CI replays. (Source: `weft/core/wefttest/replay.go:28-31`, ADR 0017 T8)
- **Renaming a test orphans its fixtures.** The directory is `t.Name()`; rename the directory with the test, or re-record. (Source: `weft/core/wefttest/replay.go:194-195`, ADR 0017 T2)
- **Keep prompts deterministic.** A date or a random id in a message changes the key on every run; the key has no normalisation by design. (Source: ADR 0017, "No volatile-substring normalisation")
- **Prompt wording and sampling do not invalidate fixtures.** The system prompt and `Params` are not keyed; a test that must catch a prompt change compares the fixture's `request.system` or uses `Golden`. (Source: `weft/core/wefttest/replay.go:68-104`, `TestReplayKeyIgnoresSystem`)
- **Assert on error types from the adapter's tests, not from replay.** A recorded vendor error replays as text; only weft's sentinels keep `errors.Is`. (Source: `weft/core/wefttest/replay.go:420-445`, ADR 0017 T7)
- **Give a subagent the same model to replay it.** When the parent and the child agent share the recorded model, their requests record and replay through one directory; the key, not the sequence number, tells them apart. (Source: `TestReplaySubagent`)

## See also

- [Turn a Studio run into a test](https://weftgo.dev/docs/testing/studio-runs-as-tests/)
- [Test an agent with a scripted model](https://weftgo.dev/docs/testing/scripted-models/)
- [Prove a provider adapter with the conformance suite](https://weftgo.dev/docs/testing/conformance/)
- [What is a Model?](https://weftgo.dev/docs/concepts/models/)

Symbols used: [`wefttest.Record`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Record) · [`wefttest.Replay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Replay) · [`wefttest.ErrNoFixture`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#ErrNoFixture) · [`wefttest.Golden`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#Golden) · [`wefttest.NewSteers`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#NewSteers) · [`ExampleReplay`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest#example-Replay) · [`conformance.FixtureServer`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/wefttest/conformance#FixtureServer) · [`openai.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Model) · [`openai.Client`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2/openai#Client) · [`weft.Model`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#Model) · [`weft.ErrModelRequestsDenied`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrModelRequestsDenied) · [`weft.ErrStreamIdle`](https://pkg.go.dev/github.com/weftgo/weft@v0.20.2#ErrStreamIdle)
