Skip to main content

Chapter 4. Evaluation Harnesses and Safe Environments

Environments, Simulators, and Harnesses

The evaluation contract tells us what to observe; now consider where that observation happens. During a test, Juniper issues a refund. The trace shows success, but which order database changed? An unintended production write could cause harm, while a mock with no policy checks may make the task unrealistically easy. An appropriately isolated environment, with behavior faithful to the question under test, can provide useful evidence without accepting either extreme.

An evaluation harness supplies tasks and initial state, connects tools, captures traces, enforces limits, and restores the environment. Its setup affects the result: a stale tool mock, a permissive sandbox, or a user simulator that always gives the needed clue can make a weak agent look strong. The environment must therefore control the risk while still reflecting the behavior your evaluation needs to measure.

After this chapter you will be able to:

  • distinguish sandboxing from mocking and know what each does not guarantee;
  • choose mock, replay, sandbox or live tools based on risk and fidelity needs;
  • record and replay tool interactions without silently hiding behavioral changes;
  • design user simulators that test realistic conversational behavior;
  • isolate state across tasks and parallel workers;
  • make runs reproducible while tracking latency, resource limits and cost.

Illustrative material. Harbor & Pine, Juniper and the environments in this chapter are fictional. The lab uses in-memory tools and a scripted user; it does not connect to a real service or provide a security boundary for arbitrary code.

4.1 Sandboxing: containers, VMs, browsers

Before selecting tools, the team needs a boundary around what Juniper can reach. A sandbox is an isolated execution environment intended to limit what an agent or its tools can access or change. It is especially important when an agent can execute code, browse websites, write files, install packages or call services with side effects.

Environment Typical use Isolation strength and limitations
In-process mock Unit tests for policy and tool logic Fast; not a security boundary if the tested code can access the host
Temporary directory / restricted process File operations and simple CLI tasks Useful containment; OS permissions and subprocess behavior matter
Container Reproducible command-line or code tasks Separate filesystem/process space; configuration, privileges, mounts and network determine actual isolation
Virtual machine Higher-risk code or browser tasks Stronger boundary than a shared process in many deployments; more resource intensive
Browser profile / browser VM Web and computer-use agents Must isolate cookies, accounts, downloads, extensions and network access
Staging service Realistic integration with non-production data Still has side effects and credentials; reset and access controls are required

A container is not automatically safe. Avoid privileged mode, host socket mounts, production credentials and unrestricted host mounts. Decide explicitly whether the sandbox can access the internet; when it can, use egress controls and allowlists where appropriate. Set CPU, memory, process, time and disk limits. Use disposable environments and least-privilege service identities. Security teams should review the design for the threat model; the evaluation harness is not a substitute for production security controls.

Inspect AI supports sandboxed tool execution, including Docker-backed environments, when tools need a filesystem or command execution [1]. The sandbox must be configured at the sample, task or evaluation level for tools that use it. Treat the environment definition, image and resource limits as versioned inputs to the evaluation, not invisible infrastructure.

4.2 Mock vs. live tools

Isolation controls exposure; it does not determine whether the tool behaves realistically. That is a separate choice. The right tool mode depends on the question:

Mode What happens Good for Main risk
Mock A local implementation returns controlled results Fast unit tests, edge cases, deterministic failures Mock behavior may not match the real API
Recorded replay A prior request receives its captured response Regression testing on fixed traces Does not model new states or live timing
Sandbox service A real service or faithful clone runs with disposable data Integration behavior and state transitions Reset cost, fidelity gaps, resource overhead
Staging / live-like Agent calls a non-production service End-to-end compatibility Side effects, shared state and credentials
Production/live Real systems and users Carefully governed online experiments Highest risk; consent, controls and rollback needed

Use the cheapest mode that can answer the question, then move outward as the evidence requires: mock tool contract → replay → isolated integration → staging → tightly controlled production. A mock establishes how the agent behaves against the mock, so compare its schema, errors, latency, and permissions with the real API before extending that result to the service.

Maintain a fidelity contract for each mocked tool: operations supported, state transition rules, error behavior, known omissions, and last comparison with the real service. For write operations, the mock should represent preconditions and invariants, not just return {"status": "ok"}. Use contract tests to compare mock and real-service schemas in a safe staging environment.

Never point a general-purpose eval suite at production by default. If a live experiment is justified, use a small allowlisted cohort, read-only or reversible operations where possible, explicit approvals for irreversible actions, monitoring and a stop/rollback plan.

4.3 Deterministic replay and record/replay

When the team wants to revisit a particular interaction, record/replay can capture the boundary between the agent and an external dependency, then supply the captured response in later runs. This makes some regression tests faster and more reproducible without repeating network calls.

A useful recording includes:

  • request/tool name and normalized arguments;
  • response body, status and relevant headers;
  • task and trace IDs, tool/API version and timestamp;
  • redaction and privacy metadata;
  • environment state or state diff when a tool has side effects.

Replay should match both tool name and arguments: if the agent changes a refund from order HP-1001 to HP-1002, returning the old response would hide the changed behavior. Fail loudly on a mismatch, or configure fuzzy matching explicitly and report what was normalized. This chapter’s lab implements strict matching.

Each recording captures one response at one point in time and state. It gives no evidence about unseen states, new API versions, concurrency, or timing-sensitive failures. Version replay fixtures and pair them with integration tests against a controlled service.

4.4 User simulators

Tools are not the only dependencies that affect a run. Juniper may also need a user to reply over several turns, especially when an order detail is missing. A user simulator supplies those turns, either as a fixed script, a state machine, or a model that generates context-aware responses. τ-bench, for example, evaluates tool-using agents with simulated users and compares task outcomes in a controlled domain [2].

Use a scripted user when the conversation path is known and repeatability matters, while a state machine handles branching goals, such as answering a clarification only if asked. A model-based user adds language variation, along with another stochastic system whose behavior and bias need evaluation.

A useful simulator has:

  • a hidden goal and a state machine for what it knows and will reveal;
  • explicit response conditions (for example, disclose shipping status only after a relevant question);
  • realistic but bounded language variation;
  • a stop condition and maximum turns;
  • checks for whether the agent reached the goal and respected constraints;
  • simulator version, seed and prompt recorded with each run.

Check that the simulator neither rescues the agent with unsolicited information nor behaves adversarially without cause. When permitted, calibrate its behavior against real conversations or SME-written scripts, and report simulator quality separately from agent quality.

4.5 State reset, isolation, and parallelism

Even a well-designed simulator and faithful tool mock can mislead if one case changes the next one’s starting conditions. If task A refunds an order and task B reuses that order, B’s result depends on execution order. This state leakage makes scores flaky and parallel runs interfere with one another, so every test needs a known initial state.

Choose a reset strategy:

  • create a fresh database/container/browser profile per sample;
  • restore a known snapshot or fixture before each run;
  • namespace records by run ID and clean up afterward;
  • use transaction rollback only when all relevant services participate;
  • for immutable tests, use read-only fixtures and verify no writes occurred.

Parallelism requires more than separate Python objects: workers must not share database rows, accounts, browser cookies, temporary filenames, rate-limit quotas or a single mutable simulator. Include the run ID in resource names and cleanup in finally blocks. A reset test should intentionally run tasks in different orders and concurrently, then verify each starts from the same initial state.

4.6 Reproducibility and cost control

Resetting state is only one part of reproducibility. If a later run uses a different tool schema or model version, the same case may lead to a different result even when the initial order is identical. Record the full experiment envelope:

  • dataset and case hashes, split, initial state and environment snapshot;
  • agent, system prompt, tool schemas, model/provider version and decoding settings;
  • harness, sandbox image/configuration, tool mock or replay fixture version;
  • user simulator and grader versions, seeds and all randomness sources;
  • limits, retries, timeouts, hardware and concurrency;
  • raw traces, final state, token usage, latency, failures and spend.

A seed cannot freeze provider models, API behavior, dynamic tool data, or concurrency timing. When an exact rerun is impossible, keep the inputs reproducible and the variation auditable. Record which parts of each run are deterministic.

Cost controls should not distort the question. Set maximum turns, wall time, token budget, tool calls and sandbox resources, and count timeouts and budget exhaustion as outcomes rather than missing rows. For early iteration, use a small smoke suite; for release, run the full suite and the repeated trials required by the risk. Report the cost and completion rate alongside quality.

Chapter summary

The environment is part of that evidence, not merely a place to run the test:

  • The harness determines what the agent can see and change, so it is part of the measurement.
  • Sandboxing contains execution; mocking replaces dependencies. Neither guarantees fidelity or safety on its own.
  • Progress from mocks to replay to isolated integration and staging as the question requires. Avoid production side effects by default.
  • Record/replay must validate request arguments and be versioned; otherwise it can hide behavior changes.
  • Scripted, stateful and model-based users have different fidelity and reproducibility trade-offs.
  • Reset every sample to a known state and isolate mutable resources before parallelizing.
  • Record the complete run envelope, not only a seed. Track timeouts, limits and cost as part of the result.

For product managers. Before approving an agent evaluation, ask: (1) What systems can the agent change? (2) Is any test pointed at production? (3) What does the mock omit? (4) How is state reset between runs? (5) Which results can be replayed exactly? (6) Who owns the stop and rollback plan?

Hands-on lab: Environments and harnesses

The runnable lab is code/ch06/lab_harness.py. It uses an in-memory tool gateway and a two-turn scripted user, while keeping the agent policy fixed to focus on harness behavior. The lab is not a security sandbox and makes no live calls.

Run one scenario, checking behavior and state:

gateway = MockGateway()
result = run_scenario(SCENARIO, gateway)
print(result["scenario_id"], result["final_state"], result["invariants"])
print("tool events:", gateway.world.events)
address-change-01 {'shipped': False, 'address': '42 Cedar Avenue'} {'only_allowed_actions': True, 'expected_turn_actions': True, 'address_updated': True}
tool events: [{'tool': 'update_address', 'result': '{"address": "42 Cedar Avenue", "status": "updated"}'}]

The task begins with a request missing shipping status. The scripted user provides that detail on the next turn; the fixed policy asks for it before changing the address. This is a fixed script, not a simulation that checks whether the user would respond appropriately to a different question. Now reset and check that state and events are clean:

gateway.reset()
assert gateway.world.address == "1 Pine Street"
assert gateway.world.events == []
print("after reset:", gateway.world.address, gateway.world.events)
after reset: 1 Pine Street []

Wrap the gateway to record calls and responses. Then replay them strictly, without calling the tool implementation again:

recording = RecordingGateway(MockGateway())
recorded_run = run_scenario(SCENARIO, recording)
print("recorded tool calls:", len(recording.records))
print("first record:", recording.records[0])

replay = ReplayGateway(recording.records, final_state={
    "shipped": recording.world.shipped,
    "address": recording.world.address,
})
replayed_run = run_scenario(SCENARIO, replay)
assert replay.index == len(recording.records)
assert replayed_run == recorded_run
print("replay matches original:", replayed_run == recorded_run)
recorded tool calls: 1
first record: {'name': 'update_address', 'arguments': {'address': '42 Cedar Avenue'}, 'result': {'status': 'updated', 'address': '42 Cedar Avenue'}}
replay matches original: True

This toy replay initializes its world with a supplied final state; it does not reconstruct state transitions from recorded calls or independently verify that final state. A production replay must account for those side effects separately. If the arguments change, the toy replay refuses to pretend the old result applies:

try:
    ReplayGateway(recording.records, final_state={
        "shipped": recording.world.shipped,
        "address": recording.world.address,
    }).call("update_address", {"address": "Wrong address"})
except ValueError as exc:
    print(type(exc).__name__ + ":", str(exc))
ValueError: replay mismatch at call 1: expected update_address({'address': '42 Cedar Avenue'}), got update_address({'address': 'Wrong address'})

Finally, the fixture is hashed and a fixed seed reproduces the same pseudo-random draws:

fixture SHA-256: fd004c9b05aaa84df8351531183a7a6f1baa4d0e05c77fdf208289b22e3bd10b
fixed seed reproduces draws: True

The generated fixture and result are repeatable because the tool behavior and user turns are fixed, whereas a production tool may differ in latency, errors and state transitions. Use replay for stable regression tests, then run isolated integration tests to check the mock still reflects the real service.

Exercises

  1. (Conceptual) A container has outbound internet access and a mounted home directory. Which risks remain, and what would you change before running an agent that can execute shell commands?
  2. (Conceptual) For a refund workflow, list one behavior a mock can test well and one behavior that requires a real staging integration.
  3. (Hands-on) Add a lookup_order tool call to the scenario. Record/replay it, then change its arguments and verify strict replay fails.
  4. (Hands-on) Add a second scenario that reuses the same order. Run it before and after the address-change test; demonstrate that reset removes order dependence.
  5. (Hands-on) Add a branching scripted user that provides a shipping status only if the agent asks. Add a turn limit and a grader for successful clarification.
  6. (Hands-on) Run two scenarios concurrently using separate gateways, then intentionally share one gateway. What state leaks, and how would you detect it automatically?
  7. (Discussion) A staging tool is expensive but more faithful than a mock. Propose a tiered test plan that allocates mock, replay and staging runs while controlling risk and cost.

Further reading

  • Inspect AI sandboxing documentation, including sandbox environments for tool execution [1].
  • Inspect AI agent documentation, including limits, interventions and checkpointing [1].
  • τ-bench, for simulated-user interaction in a controlled tool-use benchmark [2].
  • Model Context Protocol specification, for the boundaries between hosts, clients and tool servers [3].
[1]
UK AI Security Institute, “Inspect: A framework for large language model evaluations.” Accessed: Nov. 10, 2026. [Online]. Available: https://inspect.aisi.org.uk/
[2]
S. Yao, N. Shinn, P. Razavi, and K. Narasimhan, “\(\tau\)-bench: A benchmark for tool-agent-user interaction in real-world domains.” 2024. Available: https://arxiv.org/abs/2406.12045
[3]
Model Context Protocol contributors, “Model context protocol specification, version 2025-06-18.” Accessed: Nov. 10, 2026. [Online]. Available: https://modelcontextprotocol.io/specification/2025-06-18