Modes and fixtures
How Viewport Evals records model traffic at the HTTP boundary and replays it, the five modes, CI strictness, staleness and redaction.
Five modes
| Mode | Agent code | Model responses | Use it for |
|---|---|---|---|
auto | runs | replayed when recorded, recorded when missing | local default |
replay | runs | only from the fixture; a missing fixture or an unmatched request is an error | CI (the default when CI is set) |
record | runs | real calls; the fixture is rewritten | after an intentional behavior change |
rescore | does not run | none: stored trajectories are evaluated again | new expectations on old runs, imported traces |
live | runs | real calls; nothing is written | nightly or pre-deploy gates with runs and thresholds |
The mode comes from, highest first: --mode (CLI) or --viewport-mode / --rerecord (pytest), the
VIEWPORT_EVALS_MODE environment variable, mode in config, then the default: replay in CI, otherwise auto. A
run is in CI when CI is set to anything but false or 0, or, with CI unset, when a CI system's own variable is
set (Jenkins, Azure Pipelines, AWS CodeBuild, TeamCity, Buildkite and more; the CI guide lists them).
An explicit CI=false wins. Pass --mode replay in CI jobs anyway, so the gate does not depend on detection. In code, trace(mode=...) / trace(fn, { mode }) overrides it for one scope, and
trace(replay=...) / trace(fn, { replay }) takes the same replay options as config.
In CI, a config mode that can call models (auto, record, live) is ignored: the run uses replay and
prints one warning naming the ignored mode. To run that mode in CI on purpose, set ci_override = true (Python) or
ciOverride: true (TypeScript) next to it, or pass --mode or VIEWPORT_EVALS_MODE. Each of those still prints
one warning that model calls can reach the network. A config replay or rescore applies silently.
auto only spends money on a test or case that has no recording yet, which is exactly when you expect it to. Runs
that called a real model are reported as recorded, so you always know.
Replay at the HTTP boundary
Replay intercepts HTTP requests to model providers, not a framework API, so one mechanism covers every stack that calls a provider in-process: the provider SDKs, LangGraph, the OpenAI Agents SDK, the AI SDK and your own loops.
- Python records and replays through the default
httpxandhttpx2transports for the duration of atrace()scope.requests,urllib3,aiohttpandboto3are not recorded: record model calls through an httpx-based client (the OpenAI, Anthropic and most provider SDKs are). The scope followsawaitand tasks, but not threads you start yourself; run those withcontextvars.copy_context().run. - Node records and replays
fetch, undici, andnode:http/node:https(what@aws-sdkuses) for the scope, using AsyncLocalStorage, so concurrent tests replay independently. Anode:httpprovider request goes through a loopback proxy the scope owns. - Subprocess stacks (the Claude Agent SDK runs Claude Code as a child process) are pointed at a local replay
proxy on 127.0.0.1 through
ANTHROPIC_BASE_URL. The adapter wires this. Other traffic from the child process is outside the scope and is not blocked.
Recorded hosts are the hosted providers plus any you add with replay.hosts: OpenAI, Anthropic, Gemini
(generativelanguage.googleapis.com), Azure OpenAI and Azure AI Foundry (*.openai.azure.com,
*.services.ai.azure.com, *.cognitiveservices.azure.com, *.models.ai.azure.com,
models.inference.ai.azure.com), Bedrock (bedrock-runtime.* and bedrock-runtime-fips.* on amazonaws.com),
Vertex AI (aiplatform.googleapis.com and *-aiplatform.googleapis.com), OpenRouter, Portkey (api.portkey.ai, aigw.portkey.ai),
Groq, Mistral, Together, Fireworks, DeepSeek, xAI and Cerebras. A client wrapped with wrap() also registers its
base URL host, so a gateway such as LiteLLM or a self-hosted Portkey records and replays with no config. Otherwise
add the gateway's host to replay.hosts.
Replay fails closed
In replay (CI's mode, and what auto does for a case that has a recording), a connection without a recording is
refused. What is enforced, exactly:
- The scope's own traffic is checked at the lowest layer each language exposes:
fetch, undici,node:http,node:https,netandtlssockets in Node;httpx,httpx2and the socket layer underrequests,urllib3,aiohttpandboto3in Python. A provider request through a client replay cannot serve (boto3,requests) is blocked rather than going live. - Traffic with no scope, while any strict scope is open anywhere in the process, is held to the union of the
open scopes'
replay.allow_hostsat the same layers: a thread orThreadPoolExecutoryou start, a timer armed before the scope, a library's background callback. It is never served, and a refused attempt counts on every open strict scope, so every running replay case errors. - Worker threads (Node) created while strict replay governs the caller start with a socket guard that refuses
every host not in
allow_hostsand reports it to the parent. Recorded responses are never served in a worker. - Child processes started while strict replay governs the caller (
child_processin Node;subprocessandasynciosubprocesses in Python) getHTTP_PROXY,HTTPS_PROXYandALL_PROXY, both cases, pointing at a closed loopback port, andNO_PROXYfromallow_hosts. That stops clients that honor proxy variables, such as curl and most HTTP libraries. A Node child started from a TypeScript harness also preloads the socket guard throughNODE_OPTIONS(added after any options already there), because Node's own fetch ignores proxy variables: its connections are refused like a worker's. Its refusals are counted when the scope ends, from a report file; that counting is best effort (a child still running at scope end is refused but not counted). While a scope's replay proxy runs (the Claude Agent SDK adapter),127.0.0.1stays allowed so the child can reach it.
A refused connection fails with ReplayBlockedError in the caller, and the case errors with
evals.replay_blocked, naming each host, port and transport, even when the agent catches the error. The verdict
carries blocked, the report sums it, and the reporters print it next to recorded. A request a scope makes after
it ended (a timer that outlived it) is refused the same way, with a message saying so, and no replay proxy is
started for it.
Not enforced: a non-Node child process that ignores proxy variables or opens raw sockets; a Node child started
from a Python harness (it gets the proxy variables only) or with NODE_OPTIONS cleared; os.system and the os.exec* /
os.spawn* family in Python; Node workers created before the scope opened, or through a Worker captured with
require before the interceptors installed; DNS lookups (they resolve, but nothing connects); and processes the
agent does not start. The harness's own calls (recording upstream, judges) are exempt by design.
Loopback is blocked too. To let a case reach your own services, list their hosts in replay.allow_hosts (config)
or replay: { allow_hosts: [...] } (case). Patterns are host names, * matches one label, host:port limits the
port. localhost also covers 127.0.0.0/8 and ::1, but an address does not alias: 127.0.0.1 covers neither
localhost nor ::1, so prefer localhost. Anything not listed must be faked or given a world.
record, live and passthrough traffic is never blocked.
Services that commonly need an entry:
| Service | Typical host | allow_hosts entry |
|---|---|---|
| An OpenTelemetry collector your agent exports to | localhost:4318 (HTTP) or localhost:4317 (gRPC) | localhost:4318, localhost:4317 |
| Phoenix, self-hosted | localhost:6006 | localhost:6006 |
| Langfuse or another tracing backend in Docker | localhost:3000 | localhost:3000 |
| Testcontainers HTTP services (an API, a queue's HTTP admin) | localhost on a random port, plus the Docker socket | localhost (the Docker socket is a Unix path and is never blocked) |
| A tool server on your network | tools.internal:8443 | tools.internal:8443 |
Database drivers are a different case. In Node, a driver on net or tls (node-postgres, mysql2) is blocked like
any socket and needs an entry. In Python, drivers with their own C sockets (libpq through psycopg, grpcio) are not
intercepted, so strict replay does not block their connections and they need no entry; see the known limits in
SECURITY.md.
# a case
replay:
allow_hosts: ["localhost:4318", "tools.internal:8443"]A request is matched by method, host, path and its canonical body, minus volatile fields (user,
stream_options, metadata.user_id, and any you add with replay.ignore). Tool definitions and messages are part
of the key, so a prompt change is a miss, not a silent stale answer. Identical requests replay in recorded order.
Streaming responses are stored as event lists and replayed chunk by chunk, so streaming code paths run too.
Recording never changes what the agent receives: the recording run gets the provider's exact bytes and headers, and
only the stored copy is normalized and masked. A JSON body is stored as JSON when every number prints back
unchanged; a body with 1.0, exponents or integers past 2^53 is stored as its raw text and replayed byte for byte.
A binary body (a non-text content type, or bytes that are not UTF-8, such as audio/mpeg) is stored as base64 with
"encoding": "base64" and replayed as the exact bytes.
A miss in replay fails the test with evals.recording_miss and a diff against the closest recorded request, for
example messages[3].content changed.
Tools run for real during replay. Pure tools need nothing. For tools with side effects, give the agent a
world to act on, or fake them (fake_tool / fakeTool from the testing helpers record their calls and
land in the trajectory). To serve tool results from a production trace instead, see
production replay.
Record, replay and rescore, end to end
This example records a YAML case against a model server, stops the server, replays the case offline, then rescores the stored trajectory with a stricter expectation. The "provider" is a scripted model served on 127.0.0.1 so the example needs no keys; with a real provider nothing changes except that no extra host is needed.
server = script(
tool_call("lookup_order", order_id="A-1001"),
tool_call("issue_refund", order_id="A-1001", amount=42.5),
reply("Refund R-1001 for $42.50 is on its way."),
model="claude-sonnet-4-6",
).serve()
client = Anthropic(api_key="fake", base_url=server.url, max_retries=0)
cases = parse_case_file(
"""
id: refund-happy-path
input: "My order A-1001 arrived damaged."
expect:
tools: { exactly: [lookup_order, issue_refund] }
model_calls: 3
output: { contains: R-1001 }
""",
"evals/refund-happy-path.yaml",
)
config = resolve_config(
agent=lambda case_input: support_agent(client, case_input.prompt),
# Model provider hosts are recorded by default. The local stand-in is not one, so add it.
replay={"hosts": ["127.0.0.1"]},
)
store = MemoryFixtureStore() # the default store writes evals/__fixtures__/<id>.fixture.jsonconst server = await serveScript(
script(
toolCall("lookup_order", { order_id: "A-1001" }),
toolCall("issue_refund", { order_id: "A-1001", amount: 42.5 }),
reply("Refund R-1001 for $42.50 is on its way."),
{ model: "claude-sonnet-4-6" },
),
);
const client = new Anthropic({ apiKey: "fake", baseURL: server.url, maxRetries: 0 });
const cases = parseCaseFile(
`
id: refund-happy-path
input: "My order A-1001 arrived damaged."
expect:
tools: { exactly: [lookup_order, issue_refund] }
model_calls: 3
output: { contains: R-1001 }
`,
"evals/refund-happy-path.yaml",
);
const config = resolveConfig({
agent: (input) => supportAgent(client, input.prompt),
// Model provider hosts are recorded by default. The local stand-in is not one, so add it.
replay: { hosts: ["127.0.0.1"] },
});
const store = memoryFixtureStore(); // the default store writes evals/__fixtures__/<id>.fixture.jsonRecord: three model round trips become three stored HTTP exchanges.
recorded = run_cases(cases, config=config, store=store, mode="record")
assert recorded["verdicts"][0]["status"] == "pass"
assert recorded["recorded"] == 1
[(path, fixture)] = store.files.items()
assert path == "evals/__fixtures__/refund-happy-path.fixture.json"
assert len(fixture["runs"][0]["exchanges"]) == 3 # three model round trips, stored as HTTP exchangesconst recorded = await runCases(cases, { config, store, mode: "record" });
assert.equal(recorded.verdicts[0]?.status, "pass");
assert.equal(recorded.recorded, 1);
const [path, fixture] = [...store.files][0] ?? [];
assert.equal(path, "evals/__fixtures__/refund-happy-path.fixture.json");
assert.equal(fixture?.runs[0]?.exchanges?.length, 3); // three model round trips, stored as HTTP exchangesReplay with nothing listening: the agent code runs, the responses come from the fixture.
server.close() # nothing answers on that port any more
replayed = run_cases(cases, config=config, store=store, mode="replay", ci=True)
assert replayed["verdicts"][0]["status"] == "pass" # the agent ran for real; the model was the recording
assert replayed["recorded"] == 0await server.close(); // nothing answers on that port any more
const replayed = await runCases(cases, { config, store, mode: "replay", ci: true });
assert.equal(replayed.verdicts[0]?.status, "pass"); // the agent ran for real; the model was the recording
assert.equal(replayed.recorded, 0);Rescore: new expectations against the stored trajectory, without running anything.
# New expectations on the stored trajectory, without running the agent at all.
stricter = parse_case_file(
"""
id: refund-happy-path
input: "My order A-1001 arrived damaged."
expect:
model_calls: { max: 2 }
""",
"evals/refund-happy-path.yaml",
)
rescored = run_cases(stricter, config=config, store=store, mode="rescore")
assert rescored["verdicts"][0]["status"] == "fail"
print("\n".join(f"{a['name']}: {a['message']}" for a in rescored["verdicts"][0]["runs"][0]["assertions"]))
# model_calls: expected <= 2 model calls; got 3// New expectations on the stored trajectory, without running the agent at all.
const stricter = parseCaseFile(
`
id: refund-happy-path
input: "My order A-1001 arrived damaged."
expect:
model_calls: { max: 2 }
`,
"evals/refund-happy-path.yaml",
);
const rescored = await runCases(stricter, { config, store, mode: "rescore" });
assert.equal(rescored.verdicts[0]?.status, "fail");
console.log(rescored.verdicts[0]?.runs[0]?.assertions.map((a) => `${a.name}: ${a.message}`).join("\n"));
// model_calls: expected <= 2 model calls; got 3Scripted fakes from script(...) answer in process and are never recorded: recordings hold real traffic only.
Fixtures
One fixture per YAML case, at <case dir>/__fixtures__/<id>.fixture.json (or under fixtures_dir / fixturesDir
from config, or the case's own fixture: path), and one per test function, at
<test dir>/__fixtures__/<test file stem>/<test name>.fixture.json. Several trace() scopes in one test are runs 0,
1, 2 of the same fixture. Commit them.
A fixture (evals/fixture/v1) holds, per run, the recorded exchanges (for replay) and the trajectory (for
rescore), plus judgments, the cached judge verdicts, and case_hash. It is written as
canonical JSON (sorted keys, two-space indent) and atomically, so diffs are small and parallel workers never
corrupt a file. viewport-evals show <fixture> prints a recorded run as a tree of agents, model calls, tools and
cost.
FixtureStore (read, write) is pluggable; files are the default and an in-memory store ships for tests.
The file store keeps writes inside the project (the config's root directory, else the working directory): a fixture
path inside the project whose directory resolves outside it, through a symlinked directory, is refused with
evals.fixture_invalid before anything is created. A path you point outside the project yourself is written as
given. fileFixtureStoreAt(root) (TypeScript) and FileFixtureStore(root) (Python) set the root explicitly.
Staleness
case_hash covers the case's input, agent and runs. When it no longer matches, or the fixture has fewer runs
than the case asks for, the fixture is stale: evals.fixture_stale is an error in CI, auto re-records, and a
local replay proceeds. Changing only expect never invalidates a recording; that is what rescore is for.
CI strictness
Under CI, with the default mode, the case's own code cannot call a model or reach an unlisted host through any
layer listed under Replay fails closed:
- A missing fixture is
evals.fixture_missing, a stale oneevals.fixture_stale, an unmatched requestevals.recording_miss, and a connection without a recordingevals.replay_blocked. Each fails the case as an error, not a pass or a fail. - A config
modethat calls models is ignored unlessci_override/ciOverrideis set (see above). - A judge verdict missing from the cache is
evals.judgment_missinginreplayandrescore, which never call a judge.auto,recordandlivecall it, in CI too. - A run that asserts on the trajectory but captured no model call is
evals.nothing_captured, with a diagnosis, unless the case setsallow_empty: true.
Statuses are pass, fail, error, skip, xfail and xpass. Exit code 0 means everything passed, skipped or
xfailed; 1 means a fail, error or xpass; 2 means a usage or spec error.
Redaction
Request headers are not stored, so Authorization, x-api-key and friends never reach a fixture. In every mode,
credential shapes are masked wherever they appear in stored exchange bodies, in the trajectories written to
fixtures, in the results directory, in reporter output (pretty, json, junit, markdown, GitHub annotations and step
summary) and in exporter payloads:
- credentials in URLs (
scheme://user:pass@, the scheme and host are kept) - OpenAI and Anthropic keys (
sk-...,sk-proj-...,sk-ant-...) - Stripe secret and restricted keys, live and test (
sk_live_,sk_test_,rk_live_,rk_test_), and webhook signing secrets (whsec_). A test key still unlocks test-mode data, so it is masked too - GitHub tokens (
ghp_,gho_,ghu_,ghs_,ghr_,github_pat_) - Slack tokens (
xoxa-,xoxb-,xoxp-,xoxr-) - Groq (
gsk_), xAI (xai-) and Hugging Face (hf_) keys - Google OAuth access tokens (
ya29.) and Google API keys (AIza...) - JSON Web Tokens (
eyJ...header, payload and signature) Bearertokens- AWS access key ids (
AKIA...,ASIA...), and AWS secret access keys (40 characters) where they are named as one (secret_access_key,SecretAccessKey,secretAccessKey,SECRET_ACCESS_KEY, with=or:) or follow an access key id after 1 to 8 separator characters (,,:, a space, quotes). Other 40-character strings, such as commit hashes, stay readable
Obvious placeholders stay readable so examples keep working: a Stripe key, webhook secret or AWS secret containing
YOUR, EXAMPLE, example or xxxx, and Bearer YOUR_... or Bearer <...>. Secret query parameters (key,
api_key, api-key, apikey, access_token, token, compared case-insensitively) are masked in stored URLs.
Masking applies to what is stored, reported or sent, never to what the agent receives. Assertions read the masked
trajectory in every mode, so a run is judged on what it stores and a record run passes or fails exactly as its replay
will. For anything else, replay.redact runs on every exchange and replay.redact_trajectory (redactTrajectory in
TypeScript) on every trajectory before it is written or reported; events streamed while a run is in progress reach
the hook one at a time, as a trajectory with one event. Binary bodies are stored as base64 and are not masked.
A streamed response is checked per content block before it is stored: the text, tool argument and reasoning deltas
of each block (Anthropic text_delta, input_json_delta and thinking_delta; OpenAI Chat Completions
delta.content, delta.refusal, delta.reasoning_content and delta.tool_calls[].function.arguments; every OpenAI
Responses response.*.delta event) are joined, and when the joined text holds a credential shape, that block is
stored merged: its first delta carries the whole masked text, the later deltas are empty, and their logprobs are
dropped. A key streamed in 4-character pieces is masked like one sent whole, and replay serves a stream the SDKs
accept.
Tool arguments marked writeOnly: true are masked by core in trajectories (see
secret arguments), not in exchanges. A stored exchange keeps the request and response
bodies the provider saw and sent, so a secret argument the model wrote (tool_use.input,
tool_calls[].function.arguments) or that a later request repeats in its messages is stored as it is, unless it has
a credential shape listed above or replay.redact removes it.
Rescore and imported traces
rescore evaluates runs[].trajectory only, so it also works for runs that replay cannot reach and for traces from
production. viewport-evals import <file> --case <id> writes a trajectory (JSON or JSONL) or OTLP JSON GenAI spans
into a case's fixture; then viewport-evals run --mode rescore asserts on it.
Next: matchers.