---
title: "Production Eval Release Pipeline"
domain: "Reliability & Evaluation"
summary: "A closed loop from CI evals to recorded traces, incident-derived cases, and canary rollouts with automatic rollback."
url: "https://agentic-patterns.com/packs/production-eval-release-pipeline"
markdown_url: "https://agentic-patterns.com/packs/production-eval-release-pipeline.md"
pattern_count: 5
---

# Production Eval Release Pipeline

> A closed loop from CI evals to recorded traces, incident-derived cases, and canary rollouts with automatic rollback.

**Domain:** Reliability & Evaluation

## How to apply this stack with a coding agent

```text
Apply the "Production Eval Release Pipeline" pattern pack to this repository.
Check each pattern's "Use when" and "Avoid when" conditions against our codebase,
identify gaps in order of risk, and list the files to update before making edits.
```

## Patterns in this pack

1. **Workflow Evals with Mocked Tools** — Runs complete agent workflows against mocked tools in CI and checks which tools were called plus agent-as-judge quality criteria ([page](https://agentic-patterns.com/patterns/workflow-evals-with-mocked-tools) | [.md](https://agentic-patterns.com/patterns/workflow-evals-with-mocked-tools.md))
2. **Deterministic Grader in the Loop** — Replace the LLM-as-judge in an agent's self-review loop with a deterministic scorer that returns the raw counts behind each sub-score, so the agent has something specific to fix. ([page](https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop) | [.md](https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop.md))
3. **Incident-to-Eval Synthesis** — Converts each production incident into executable eval cases with pass/fail criteria and gates future releases on them ([page](https://agentic-patterns.com/patterns/incident-to-eval-synthesis) | [.md](https://agentic-patterns.com/patterns/incident-to-eval-synthesis.md))
4. **Out-of-Process Provider-Boundary Replay** — Capture an agent run at the model-provider HTTP boundary from outside the process, then serve those bytes back so the agent re-executes its own logic with no provider call. ([page](https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay) | [.md](https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay.md))
5. **Canary Rollout and Automatic Rollback for Agent Policy Changes** — Ships agent policy changes to a small traffic slice first, monitors guardrail metrics, and rolls back to the last stable version automatically ([page](https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes) | [.md](https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes.md))

---

## Workflow Evals with Mocked Tools

- URL: https://agentic-patterns.com/patterns/workflow-evals-with-mocked-tools
- Markdown: https://agentic-patterns.com/patterns/workflow-evals-with-mocked-tools.md
- Category: Reliability & Eval | Status: production

> Runs complete agent workflows against mocked tools in CI and checks which tools were called plus agent-as-judge quality criteria

### Use when

- Agent tools have side effects such as API or database writes
- Unit tests pass but prompts and tools fail together
- Need regression tests for agent behavior on each PR

### Avoid when

- Results must act as a strict CI gate, since non-determinism makes them flaky
- Team cannot keep mocks in sync with real tools

<details>
<summary>Full pattern specification</summary>

---
title: "Workflow Evals with Mocked Tools"
summary: "Runs complete agent workflows against mocked tools in CI and checks which tools were called plus agent-as-judge quality criteria"
status: "production"
category: "Reliability & Eval"
url: "https://agentic-patterns.com/patterns/workflow-evals-with-mocked-tools"
source: "https://lethain.com/agents-evals/"
authors: ["Nikola Balic (@nibzard)"]
tags: ["evals","testing","ci-cd","mocked-tools","simulations","workflow-validation","end-to-end-testing"]
signals: ["Agent tools have side effects such as API or database writes","Unit tests pass but prompts and tools fail together","Need regression tests for agent behavior on each PR"]
anti_signals: ["Results must act as a strict CI gate, since non-determinism makes them flaky","Team cannot keep mocks in sync with real tools"]
updated_at: "2026-10-13"
---

# Workflow Evals with Mocked Tools

> Runs complete agent workflows against mocked tools in CI and checks which tools were called plus agent-as-judge quality criteria

## Use when

- Agent tools have side effects such as API or database writes
- Unit tests pass but prompts and tools fail together
- Need regression tests for agent behavior on each PR

## Avoid when

- Results must act as a strict CI gate, since non-determinism makes them flaky
- Team cannot keep mocks in sync with real tools

## Problem

Unit tests, linters, and typecheckers validate individual components but do not test agent workflows end to end. It is easy to create prompts that do not work well although every underlying piece is correct. You need to validate that prompts and tools work together effectively as a system.

## Solution

Implement **workflow evals (simulations)** that test complete agent workflows with mocked tools. The approach is Sierra-inspired and has four components.

**1. Dual tool implementations.** Every tool has both a `true` and a `mock` version:

```python
# True implementation: calls the real API
def search_knowledge_base_true(query: str) -> str:
    return kb_api.search(query)

# Mock implementation: returns static test data
def search_knowledge_base_mock(query: str) -> str:
    return TEST_KB_RESULTS.get(query, DEFAULT_RESULT)
```

**2. Simulation configuration.** Each eval defines the initial prompt, metadata (situation context available to the harness), and evaluation criteria:

```yaml
evals:
  - name: slack_reaction_jira_workflow
    initial_prompt: "Add a smiley reaction to the JIRA ticket in this Slack message"
    metadata:
      situation: "slack_message_with_jira_link"
    evaluation_criteria:
      objective:
        - tools_called: ["slack_get_message", "jira_get_ticket", "slack_add_reaction"]
        - tools_not_called: ["slack_send_message"]
      subjective:
        - agent_judge: "Response was helpful and accurate"
```

**3. Dual evaluation criteria.** Objective criteria check which tools were called, which tools were not called, and which tags or states the conversation gained (if applicable). Subjective criteria use agent-as-judge assessments (for example, "Was the response friendly?") and LLM evaluations of qualitative outcomes.

**4. CI/CD integration.** A run loads the eval configuration, swaps in the mock implementations for all tools, runs the agent with the prompt and metadata, and tracks the tool calls. It then evaluates the objective criteria, runs the agent-as-judge for the subjective criteria, and reports pass or fail with details. CI triggers the run on every PR.

## Evidence

- **Evidence Grade:** `medium` - Independent practitioner report plus vendor-published evaluation frameworks (2026)
- **Key Findings:**
  - Strong production use case: unit tests and linters don't validate prompt-tool integration effectively
  - Dual evaluation (objective + subjective) is standard across implementations
  - Anthropic's "Demystifying evals for AI agents" (January 2026) codifies the grading side: code-based, model-based, and human graders applied to the trajectory or the final answer, which is the trajectory-level extension of this pattern
  - Non-determinism remains the primary challenge; best used for directional guidance
- **Unclear:** Optimal mock fidelity requirements for valid evaluation

## How to use it

**Best for:** agent workflows where tools have side effects (APIs, databases), CI/CD pipelines that need workflow validation, prompt engineering and optimization, and regression testing for agent behavior changes.

**1. Create a mock layer for tools:**

```python
class MockToolRegistry:
    def __init__(self, mode: str = "mock"):
        self.mode = mode
        self.mocks = {"slack_send_message": mock_slack_send_message, "jira_create_ticket": mock_jira_create_ticket}

    def get_tool(self, tool_name: str):
        return self.mocks[tool_name] if self.mode == "mock" else self.real_tools[tool_name]
```

**2. Define eval cases:**

```python
evals = [{
    "name": "login_support_flow",
    "prompt": "User can't log in, help them",
    "expected_tools": ["user_lookup", "password_reset"],
    "forbidden_tools": ["account_delete"],
    "subjective_criteria": "Response was empathetic and helpful",
}]
```

**3. Run and evaluate:**

```python
def run_eval(eval_config, mock_registry):
    result = agent.run(prompt=eval_config["prompt"], tools=mock_registry)
    tools_called = result.tools_used

    # Objective: tool usage
    passed = all(t in tools_called for t in eval_config["expected_tools"])
    passed &= all(t not in tools_called for t in eval_config["forbidden_tools"])

    # Subjective: agent-as-judge, only if the objective checks passed
    if passed:
        criteria = eval_config['subjective_criteria']
        passed = llm_evaluator(f"Evaluate this agent response: {result.response}\nCriteria: {criteria}\nPass/fail?") == "PASS"

    return {"passed": passed, "details": result}
```

**4. Integrate with CI/CD and post the results as a PR comment:**

```yaml
# .github/workflows/agent_evals.yml
name: Agent Evals
on: pull_request
jobs:
  evals:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - run: python scripts/run_evals.py --format github   # writes eval_results.json
      - uses: actions/github-script@v6                   # then posts it as a PR comment
```

**Handling non-determinism:**

The article notes that the evals work "not nearly as well as I hoped it would" because of non-determinism:

- **Strong signal**: all pass or all fail
- **Weak signal**: mixed results
- **Mitigation**: retry failed evals (for example, "at least once in three tries")

## Trade-offs

**Pros:**

- **End-to-end validation**: tests prompts and tools together as a system
- **Fast feedback**: catches regressions before they reach production
- **Safe testing**: mocked tools avoid side effects during testing
- **Clear criteria**: objective (tool calls) and subjective (quality) measures
- **CI/CD integration**: automated validation on every PR

**Cons:**

- **Non-deterministic**: LLM variability makes flaky tests common
- **Mock maintenance and tuning overhead**: mocks must stay in sync with real tool behavior, and prompts and mock responses need continuous adjustment
- **Limited signal**: mixed pass/fail results provide ambiguous guidance

**Operational challenges:**

> "Ok, this is working well, but not nearly as well as I hoped it would... there's very strong signal when they all fail, and strong signal when they all pass, but most runs are in between."

> "Our reliance on prompt-driven workflows rather than code-driven workflows introduces a lot of non-determinism, which I don't have a way to solve without... prompt and mock tuning."

**Failure modes / gotchas:**

- **Hard CI gate:** non-determinism makes evals flaky, so a strict gate blocks PRs at random. Use the results as directional context, and retry failures ("at least once in three tries").
- **Prompt-driven fragility:** prompt-driven workflows are more flaky than code-driven ones. Move complex workflows from prompts into code.
- **Mock drift:** a mock that no longer matches the real tool passes evals that fail in production. Tune mocks to be realistic and keep them synced.
- **Judge noise:** a vague subjective criterion adds more variance. Tune eval prompts to be precise and deterministic.

## References

* [Building an internal agent: Evals to validate workflows](https://lethain.com/agents-evals/) - Will Larson (December 2025)
* [Demystifying evals for AI agents](https://www.anthropic.com/engineering/demystifying-evals-for-ai-agents) - Anthropic Engineering (January 2026); code-based, model-based, and human graders over trajectories or final answers
* Sierra platform: Simulations approach for agent testing
* [LangSmith Evaluation Platform](https://smith.langchain.com/) - Tool tracking and custom evaluators
* [Promptfoo](https://github.com/promptfoo/promptfoo) - Mock API responses and assertion-based testing
* Related: [Stop Hook Auto-Continue Pattern](stop-hook-auto-continue-pattern.md) - Post-execution testing
* Related: [Agent Reinforcement Fine-Tuning](agent-reinforcement-fine-tuning.md) - Training on agent workflows

</details>

---

## Deterministic Grader in the Loop

- URL: https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop
- Markdown: https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop.md
- Category: Feedback Loops | Status: proposed

> Replace the LLM-as-judge in an agent's self-review loop with a deterministic scorer that returns the raw counts behind each sub-score, so the agent has something specific to fix.

### Use when

- The agent must judge a quality attribute of its own output before shipping it
- You want the same input to always produce the same verdict
- You want the verdict to be assertable in a test or CI gate

### Avoid when

- The quality attribute genuinely requires semantic judgement (factual correctness, tone-for-this-audience)
- You have no way to enumerate observable features of 'good'

<details>
<summary>Full pattern specification</summary>

---
title: "Deterministic Grader in the Loop"
summary: "Replace the LLM-as-judge in an agent's self-review loop with a deterministic scorer that returns the raw counts behind each sub-score, so the agent has something specific to fix."
status: "proposed"
category: "Feedback Loops"
url: "https://agentic-patterns.com/patterns/deterministic-grader-in-the-loop"
source: "https://github.com/parweb/mcp-ai-slop-checker"
authors: ["parweb (@parweb)"]
tags: ["feedback-loop","self-critique","evaluation","determinism","llm-as-judge","reproducibility"]
signals: ["The agent must judge a quality attribute of its own output before shipping it","You want the same input to always produce the same verdict","You want the verdict to be assertable in a test or CI gate"]
anti_signals: ["The quality attribute genuinely requires semantic judgement (factual correctness, tone-for-this-audience)","You have no way to enumerate observable features of 'good'"]
updated_at: "2026-08-21"
---

# Deterministic Grader in the Loop

> Replace the LLM-as-judge in an agent's self-review loop with a deterministic scorer that returns the raw counts behind each sub-score, so the agent has something specific to fix.

## Use when

- The agent must judge a quality attribute of its own output before shipping it
- You want the same input to always produce the same verdict
- You want the verdict to be assertable in a test or CI gate

## Avoid when

- The quality attribute genuinely requires semantic judgement (factual correctness, tone-for-this-audience)
- You have no way to enumerate observable features of 'good'

## Problem

An agent that produces text is routinely asked to judge that text before shipping it: *is this argument sound, is this copy generic, does this read as machine-written?* The default move is to ask a model — LLM-as-judge, or an off-the-shelf classifier.

Both fail the agent in the same specific way: **the verdict is not actionable and not reproducible.**

- A classifier returns `87% likely AI-generated`. There is no next move encoded in that number. The agent's only recourse is to rewrite blindly and re-roll.
- An LLM judge returns a different score for the same input across runs, and drifts with model versions, so it cannot gate a pipeline or be asserted in a test.
- Both make an *authorship* claim from *style* evidence, and are wrong in both directions.

The loop stalls because the feedback has no gradient.

## Solution

Put a **deterministic scorer** in the loop instead of a judge. The scorer counts observable, enumerated features and returns **the raw counts alongside each sub-score** — not just the aggregate.

Core properties:

- **Deterministic** — same input, same output, always. No sampling, no model call.
- **Decomposed** — the aggregate is made of named sub-scores, each traceable to a count.
- **Local and free** — no API call, so it can run on every iteration without cost or latency pressure.
- **Honest about what it measures** — it reports a *style* measurement, never an authorship verdict.

The agent loop becomes a hill-climb with an actual gradient:

```pseudo
draft = generate()
loop until score >= threshold or budget exhausted:
    report = score(draft)          // deterministic, decomposed
    worst  = argmax(report.counts) // e.g. {"hype": 5, "em_dash": 9, "specifics": 0}
    draft  = revise(draft, target=worst)
```

```mermaid
graph TD
    A[Generate draft] --> B[Deterministic scorer]
    B --> C{Score >= threshold?}
    C -- No --> D[Read highest offending count]
    D --> E[Revise that specific feature]
    E --> B
    C -- Yes --> F[Ship / commit]
```

`"hype": 5` tells the agent to cut five specific words. `87% likely AI` tells it nothing. That difference is the whole pattern.

This is the same shape a coding agent already gets for free from a linter, a type checker, or a failing test — deterministic, decomposed, actionable. The pattern is simply noticing that non-code outputs deserve the same treatment, and that reaching for a model to grade them is usually a downgrade.

## Evidence

- **Evidence Grade:** `low`
- **Most Valuable Findings:**
  - Applying one such scorer to a corpus of 239 real product landing pages produced a stable distribution (median 79/100) and surfaced a counter-intuitive dominant feature: **82% (195/239) of hero sections contain no concrete number at all** — while the widely assumed "hype words" tell fired on only 7%, and em-dash density on a similarly small slice. A decomposed scorer finds this; a single opaque probability cannot. Open dataset and method: <https://gist.github.com/parweb/5ed569ba76c365f7b789a979ad6090e7>
  - The same corpus shows why the *style, not authorship* framing is load-bearing: `stripe.com` scores 61 and was plainly written by professionals. A low score means *reads generic*, never *was generated*.
- **Unverified / Unclear:** whether closing this loop measurably improves human-judged output quality, or mostly teaches the agent to satisfy the metric (see Goodhart risk below). No controlled comparison against an LLM-judge loop has been run.

## How to use it

1. **Enumerate the features** that make the attribute good or bad, in the narrowest domain you can get away with. This is the real work, and it is domain-specific.
2. **Write a pure function** from artifact to `{score, sub_scores, counts}`. No network, no model.
3. **Expose the counts**, not only the total. The counts are the actionable part; the total is only for gating.
4. **Expose it as a tool** the agent can call mid-task (an MCP server, a CLI, a library function) so the loop closes without a human.
5. **Gate on it** — because it is deterministic, a threshold can live in a test or a CI check.
6. **Calibrate against a real corpus** and publish the distribution, so a score has a referent. A bare 0-100 with no baseline is not interpretable.

Good fits: style and readability checks, format and schema conformance, jargon and hedging density, required-element presence, structural repetition. Poor fits: factual accuracy, novelty, and audience appropriateness — keep a model, or a human, for those.

## Trade-offs

**Pros**
- Reproducible: assertable in tests, usable as a CI gate, comparable across runs and over time.
- Actionable: names the specific thing to change, giving the revision loop a gradient.
- Cheap and offline: no token cost or latency, so it can run on every iteration.
- Auditable: anyone can read the rules and disagree with them explicitly.

**Cons**
- **Measures only what you thought to count.** Blind to failure modes outside the enumerated feature set.
- **Goodhart risk is real and direct.** An agent optimising a metric it can read will learn to satisfy the metric. Cap the iterations, and keep the threshold well below the maximum.
- Requires a calibration corpus to be interpretable, which is upfront work.
- Says nothing about meaning, truth, or fit for audience — a maximal score can still be worthless prose.
- Rules need maintenance as conventions shift.

## References

- Reference implementation, MIT, offline, no model call: <https://github.com/parweb/mcp-ai-slop-checker>
- Calibration corpus — 239 landing pages scored, open CSV plus method: <https://gist.github.com/parweb/5ed569ba76c365f7b789a979ad6090e7>
- Related in spirit: linters, type checkers and property-based tests as agent feedback — the same deterministic-signal argument, applied to code.

</details>

---

## Incident-to-Eval Synthesis

- URL: https://agentic-patterns.com/patterns/incident-to-eval-synthesis
- Markdown: https://agentic-patterns.com/patterns/incident-to-eval-synthesis.md
- Category: Feedback Loops | Status: proposed

> Converts each production incident into executable eval cases with pass/fail criteria and gates future releases on them

### Use when

- Production incidents recur after being fixed operationally
- The eval suite drifts away from failures seen in production
- Incident artifacts such as inputs, tool traces, and outputs can be captured

### Avoid when

- No production traffic or incident history exists yet
- Incident data cannot be captured or redacted safely
- The team cannot take on triage overhead for each incident

<details>
<summary>Full pattern specification</summary>

---
title: "Incident-to-Eval Synthesis"
summary: "Converts each production incident into executable eval cases with pass/fail criteria and gates future releases on them"
status: "proposed"
category: "Feedback Loops"
url: "https://agentic-patterns.com/patterns/incident-to-eval-synthesis"
source: "https://platform.claude.com/docs/en/test-and-evaluate/develop-tests"
authors: ["Codex (@openai)"]
tags: ["evals","incidents","reliability","feedback","continuous-improvement"]
signals: ["Production incidents recur after being fixed operationally","The eval suite drifts away from failures seen in production","Incident artifacts such as inputs, tool traces, and outputs can be captured"]
anti_signals: ["No production traffic or incident history exists yet","Incident data cannot be captured or redacted safely","The team cannot take on triage overhead for each incident"]
updated_at: "2026-10-13"
---

# Incident-to-Eval Synthesis

> Converts each production incident into executable eval cases with pass/fail criteria and gates future releases on them

## Use when

- Production incidents recur after being fixed operationally
- The eval suite drifts away from failures seen in production
- Incident artifacts such as inputs, tool traces, and outputs can be captured

## Avoid when

- No production traffic or incident history exists yet
- Incident data cannot be captured or redacted safely
- The team cannot take on triage overhead for each incident

## Problem

Many teams run agent evaluations, but the eval suite drifts away from real failures seen in production. Incidents get resolved operationally, yet the exact failure mode is rarely converted into a durable regression test. This creates repeat incidents and false confidence from stale benchmark sets.

## Solution

Convert every production incident into one or more executable eval cases, then gate future changes on those cases.

Pattern mechanics:
- Capture incident artifacts: inputs, context, tool traces, outputs, and impact.
- Normalize sensitive data and derive a minimal reproducible scenario.
- Encode expected behavior as objective pass/fail criteria.
- Add the case to the evaluation corpus with severity and owner metadata.
- Run incident-derived evals in CI and release gates.

```pseudo
incident = ingest_incident(ticket_id)
case = build_eval_case(
  prompt=redact(incident.prompt),
  tools=incident.tool_trace,
  expected=define_acceptance_criteria(incident)
)

suite.add(case, labels=["incident", incident.severity])
if not suite.run(candidate_policy).pass(case.id):
    block_release(candidate_policy)
```

Distinct from [Persistent Test Memory Feedback Loop](persistent-test-memory-feedback-loop.md): that pattern stores test failures as persistent memory the agent itself consults later, while this pattern turns incidents into release-gating eval cases owned by the team.

## Evidence

- **Evidence Grade:** `low`
- **Most Valuable Findings:**
  - Blameless postmortem culture is established practice for capturing incident knowledge, but it stops at written action items rather than executable cases
  - Vendor evals guidance (Anthropic) describes building executable eval cases with pass/fail grading criteria; deriving those cases from incidents is this pattern's extension of that guidance
- **Unverified / Unclear:** No public source yet documents incident-derived agent evals end to end. Earlier revisions of this pattern carried adoption and success-rate statistics that had no source; they have been removed.

## How to use it

- Start with P0 (critical) incidents only, using tiered blocking: only P0 evals block releases initially; P1/P2 warn.
- Require a linked eval case in incident closure criteria.
- Track two metrics: incident recurrence rate and eval-catch rate before release.
- Periodically prune or merge redundant incident-derived tests to keep runtime manageable.

## Trade-offs

* **Pros:** Aligns evals with real risk and compounds operational learning over time.
* **Cons:** Adds triage overhead and requires discipline in incident data capture.

## References

- Primary source: [Define success criteria and build evaluations (Anthropic docs)](https://platform.claude.com/docs/en/test-and-evaluate/develop-tests) - executable eval cases and grading criteria; the incident-to-case step is the pattern's own extension
- [Postmortem Culture (Google SRE Book)](https://sre.google/sre-book/postmortem-culture/) - adjacent practice for the incident-capture half of the loop
- https://martinfowler.com/articles/practical-test-pyramid.html

</details>

---

## Out-of-Process Provider-Boundary Replay

- URL: https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay
- Markdown: https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay.md
- Category: Reliability & Eval | Status: emerging

> Capture an agent run at the model-provider HTTP boundary from outside the process, then serve those bytes back so the agent re-executes its own logic with no provider call.

### Use when

- The agent is expensive or slow to re-run
- A bug reproduces only in a full session, not in a unit test
- The framework changes faster than any instrumentation you could write for it

### Avoid when

- You need the agent to reach a *live* model, e.g. to test prompt changes
- The run's tool calls are destructive and you have no sandbox
- Your provider traffic never leaves the process (a model compiled in, or an in-process stub)

<details>
<summary>Full pattern specification</summary>

---
title: "Out-of-Process Provider-Boundary Replay"
summary: "Capture an agent run at the model-provider HTTP boundary from outside the process, then serve those bytes back so the agent re-executes its own logic with no provider call."
status: "emerging"
category: "Reliability & Eval"
url: "https://agentic-patterns.com/patterns/out-of-process-provider-boundary-replay"
source: "https://github.com/Continuum-AI-Corp/OrcaReplay"
authors: ["Xingke Yan (@xizhuomengcontin)"]
tags: ["record-replay","determinism","regression-testing","http-boundary","offline","instrumentation-free"]
signals: ["The agent is expensive or slow to re-run","A bug reproduces only in a full session, not in a unit test","The framework changes faster than any instrumentation you could write for it"]
anti_signals: ["You need the agent to reach a *live* model, e.g. to test prompt changes","The run's tool calls are destructive and you have no sandbox","Your provider traffic never leaves the process (a model compiled in, or an in-process stub)"]
updated_at: "2026-10-13"
---

# Out-of-Process Provider-Boundary Replay

> Capture an agent run at the model-provider HTTP boundary from outside the process, then serve those bytes back so the agent re-executes its own logic with no provider call.

## Use when

- The agent is expensive or slow to re-run
- A bug reproduces only in a full session, not in a unit test
- The framework changes faster than any instrumentation you could write for it

## Avoid when

- You need the agent to reach a *live* model, e.g. to test prompt changes
- The run's tool calls are destructive and you have no sandbox
- Your provider traffic never leaves the process (a model compiled in, or an in-process stub)

## Problem

An agent session is expensive to reproduce. Re-running it costs tokens, needs the network, and the
model may not make the same choices twice — so "what did it actually do, and why" usually gets
answered from logs rather than from the run itself.

The usual fix is to instrument the framework: a callback handler, a tracing decorator, a monkey
patch around the client. That works until it doesn't:

- **It is per-framework.** Every agent library needs its own hook, and the hooks move between
  releases faster than the integrations that wrap them.
- **It records an interpretation, not the traffic.** A handler sees the objects the framework built,
  after the framework already normalised, retried, or merged streamed chunks.
- **It cannot capture what you did not anticipate.** A field added by a provider last week is not in
  your span schema, so it is not in your trace.
- **It changes the program under test.** The run you recorded is a run with your instrumentation in
  it.

## Solution

Record one layer lower and one process out: at the **HTTP boundary between the agent and its model
provider**, from a proxy the agent does not know about.

This is the old HTTP-fixture pattern — VCR's cassettes, Polly.JS's recordings — applied at the one
boundary that every agent framework has in common. **Distinct from** [Action Caching & Replay](action-caching-replay.md),
which replays recorded UI actions in a browser: here the agent's own logic re-executes, and only the
provider's responses come from the trace.

1. **Launch the agent as a child process** and set the provider-origin variables *for that process
   only* (`OPENAI_BASE_URL`, `ANTHROPIC_BASE_URL`, or whatever the client reads). Nothing is
   installed into the agent; its own code is unchanged.
2. **Store verbatim bytes.** Request and response exactly as they crossed the socket, including
   streamed frames and tool-call arguments — not a parsed summary of them.
3. **Restore the initial state, then replay.** Restore the working tree, tool fixtures, and configuration captured before recording; replay in a disposable sandbox. **Serve the recording back.** Run the same command again with the proxy in replay
   mode. The agent executes its own logic, its own control flow, its own tool dispatch; only the
   provider's answers come from the trace.
4. **Report divergence instead of hiding it.** When the replayed request does not match the
   recorded one byte for byte, say so and say by how much. A prompt carrying an absolute path or a
   session id will differ between runs; that is worth naming, not silently matching.
   In strict regression mode, a mismatch or missing exchange aborts replay without provider fallback.
   A diagnostic mode may continue only with explicit divergence labels; it is not a passing regression test.

```
record:  agent ──HTTP──▶ [proxy: forward + store] ──▶ provider
replay:  agent ──HTTP──▶ [proxy: match + serve from trace]     ✗ provider
```

The verdict from a replay is a number, not a vibe: how many exchanges were reused, how many matched
exactly, how many diverged, how many requests had no recorded counterpart at all.

## Evidence

- **Evidence Grade:** `medium`
- **Most Valuable Findings:**
  - Independent implementations exist beyond the author's tool: [Deterministic Replay for AI Agent
    Systems](https://arxiv.org/abs/2607.16200) (2026) presents the same idea academically, and
    [culpa](https://github.com/AnshKanyadi/culpa) and
    [mock-server's AI traffic inspection](https://www.mock-server.com/mock_server/ai_traffic_inspection.html)
    record and replay agent traffic in the wild.
  - The boundary generalises where instrumentation does not: the same proxy captures agent
    frameworks written in different languages, because the thing it hooks is HTTP, not an API.
  - Byte-level matching is what makes a replay falsifiable. If the harness normalises the request
    before comparing, an exact match and a lucky match become indistinguishable.
  - Denying provider egress during replay checks that no live response can silently substitute
    for a missing recording. Stopping a local mock origin is one additional check, not proof
    that requests cannot reach a hosted provider.
- **Unverified / Unclear:** How far this stretches for agents whose provider traffic is multiplexed
  with unrelated traffic on one connection, and for clients that pin certificates.

## How to use it

**Use it when** you want a run you can hand to someone else, a regression test that costs nothing to
run in CI, or a bug report that reproduces on a machine with no API key.

**Getting there:**

- Check that the client actually reads its origin from the environment. Some SDKs only honour a
  constructor argument, and some compile the origin in — those need a TLS-intercepting proxy with a
  trusted local CA, or they cannot be captured this way at all.
- Record the *shapes you really use*: streaming SSE, tool calls, and any non-chat endpoint. A
  harness proved against a single plain completion has proved very little.
- Capture the initial working tree and relevant tool inputs before recording, and the resulting diff
  afterward. Restore the initial snapshot for each replay; a final-state snapshot alone cannot reproduce
  the run. Live tool responses, clocks, and other uncontrolled inputs still limit determinism.
- Redact on the way in, not on the way out: an API key that reaches the trace file has already
  leaked.

## Trade-offs

**Pros**

- No instrumentation to write or keep up to date; the agent's code is untouched.
- Captures what actually went over the wire, including fields nobody modelled.
- Replays cost nothing and need no key, so they belong in CI and in bug reports.
- Framework-agnostic by construction.

**Cons**

- **Blocking provider egress is not sandboxing.** Replay stops the model call, but the agent still
  *executes its recorded tool calls for real* — a tool that shells out to `curl` will hit the
  network again. To stop all egress you still need a sandbox.
- Non-determinism inside the prompt (timestamps, absolute paths, session ids) shows up as
  divergence, so the harness needs a considered answer for it rather than a normalisation that
  hides it.
- Origins that are compiled in, or clients that pin certificates, are out of reach without a TLS
  intercept the user has to trust.
- A trace is a full transcript. It is exactly as sensitive as the conversation it recorded.

## References

- [VCR](https://github.com/vcr/vcr) — the original record/replay HTTP fixture library.
- [Polly.JS](https://github.com/Netflix/pollyjs) — the same idea for JavaScript, with request matching rules.
- [Docker Cagent](https://github.com/docker/cagent) — a proxy-and-cassette model for deterministic agent testing.
- [OrcaReplay](https://github.com/Continuum-AI-Corp/OrcaReplay) — an implementation at the agent's provider boundary, including the divergence verdict described above; maintained by this pattern’s author. Beyond the plain HTTP proxy, it now captures through a PATH shim for shell tool calls, a shadow git index for per-turn workspace state, and an opt-in `--tls-intercept` mode for agents whose origin cannot be redirected.
- [Deterministic Replay for AI Agent Systems](https://arxiv.org/abs/2607.16200) (arXiv, 2026) — independent academic treatment of replaying agent executions via their external interactions.
- [culpa](https://github.com/AnshKanyadi/culpa) — an independent record/replay implementation for agent traffic.

</details>

---

## Canary Rollout and Automatic Rollback for Agent Policy Changes

- URL: https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes
- Markdown: https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes.md
- Category: Reliability & Eval | Status: emerging

> Ships agent policy changes to a small traffic slice first, monitors guardrail metrics, and rolls back to the last stable version automatically

### Use when

- Prompts, tool policies, or routing rules change often
- Small policy edits can cause regressions in cost, latency, safety, or quality

### Avoid when

- No real-time telemetry to detect regressions
- Policies are not versioned, so rollback cannot restore a known-good state

<details>
<summary>Full pattern specification</summary>

---
title: "Canary Rollout and Automatic Rollback for Agent Policy Changes"
summary: "Ships agent policy changes to a small traffic slice first, monitors guardrail metrics, and rolls back to the last stable version automatically"
status: "emerging"
category: "Reliability & Eval"
url: "https://agentic-patterns.com/patterns/canary-rollout-and-automatic-rollback-for-agent-policy-changes"
source: "https://martinfowler.com/bliki/CanaryRelease.html"
authors: ["Codex (@openai)"]
tags: ["canary","rollback","reliability","policy","evaluation"]
signals: ["Prompts, tool policies, or routing rules change often","Small policy edits can cause regressions in cost, latency, safety, or quality"]
anti_signals: ["No real-time telemetry to detect regressions","Policies are not versioned, so rollback cannot restore a known-good state"]
updated_at: "2026-10-13"
---

# Canary Rollout and Automatic Rollback for Agent Policy Changes

> Ships agent policy changes to a small traffic slice first, monitors guardrail metrics, and rolls back to the last stable version automatically

## Use when

- Prompts, tool policies, or routing rules change often
- Small policy edits can cause regressions in cost, latency, safety, or quality

## Avoid when

- No real-time telemetry to detect regressions
- Policies are not versioned, so rollback cannot restore a known-good state

## Problem

Agent behavior changes frequently through prompt updates, tool policies, routing rules, and evaluator thresholds. Even small policy edits can produce broad regressions in cost, latency, safety, or task quality. Full rollouts without staged exposure make rollback slow and user impact large.

## Solution

Treat agent policy changes like production releases: ship to a small traffic slice first, monitor leading indicators, and auto-rollback when guardrails are breached.

Core components:
- A traffic splitter that routes a fixed percentage to the new policy.
- A policy version registry with immutable identifiers.
- Real-time monitors for quality, latency, failure rate, safety flags, spend, goal achievement rate, and infinite loop detection.
- Rollback automation that restores the previous stable policy without manual intervention.
- Optional shadow mode: validate technical stability before user exposure.

Illustrative stages — no cited source prescribes these percentages for agent policies, so tune them to your traffic and risk:
1. `1%` traffic canary for fast anomaly detection.
2. `5-10%` validation phase with stricter thresholds.
3. `25-50%` soak period for stability under mixed load.
4. `100%` rollout only if all SLO and safety conditions hold.

```pseudo
policy = registry.current_candidate()
traffic = splitter.assign(request, canary_percent=5)

response = run_agent(policy if traffic.canary else registry.stable())
metrics.ingest(response, policy.version)

if monitors.breach(policy.version):
    registry.rollback_to_stable()
    alert("auto rollback executed", policy.version)
```

## How to use it

- Use this for any change that can alter external behavior: prompts, tools, evaluator logic, memory policies, and routing.
- Define rollback triggers before rollout starts. Set observation windows (e.g., 2+ minutes) to avoid false positives.
- Keep rollback deterministic: always restore the last known-good version.
- Store policy artifacts with versioned metadata so incidents are reproducible.

## Trade-offs

* **Pros:** Limits blast radius and shortens time-to-recovery.
* **Cons:** Requires release orchestration, richer telemetry, and clear version hygiene.

## References

- https://martinfowler.com/bliki/CanaryRelease.html
- https://sre.google/sre-book/monitoring-distributed-systems/
- https://arxiv.org/html/2508.03858v3 - MI9 Runtime Governance Framework (2025)
- https://arxiv.org/html/2512.03180v1 - AGENTSAFE Safety Evaluation (2025)
- https://langfuse.com/docs - Langfuse prompt management: versioned prompts with evaluation gates, an LLM-ops implementation of staged prompt rollouts (open source: https://github.com/langfuse/langfuse)

</details>
