How do you reproduce LLM agent failures? I built an open-source Python tool for offline replay and pytest testing

Hi everyone!

I’ve been working on Stepfork, an open-source Python tool for recording AI agent executions, replaying failures offline, and generating pytest regression tests.

One challenge I’ve encountered while building LLM applications is reproducing failures consistently.

An agent might call an LLM, execute several tools, and combine the results using Python application logic. When something goes wrong, rerunning the agent can produce different model responses or tool outputs.

I wanted a way to freeze the instrumented dependencies while continuing to test the actual application logic.

What I built

Stepfork provides:

  • Recording of supported LLM and tool interactions into .sftrace bundles

  • Frozen replay without additional model requests or execution of instrumented tool bodies

  • Strict detection of changes in tool-call order and arguments

  • Pytest regression-test generation with developer-defined expectations

  • Integrations for supported OpenAI and LangGraph workflows

Testing with a real Gemini model

I recently tested Stepfork with Gemini 2.5 Flash using a synthetic incident-triage agent.

The model correctly classified a critical checkout incident as P0. However, an intentionally introduced Python postprocessing bug changed the final result to P1 and disabled escalation.

I recorded the execution and generated a pytest regression test.

The results:

  • 14 recorded trace events

  • 5 instrumented tool calls and 1 real LLM call

  • The generated regression test failed with the buggy application

  • The same test passed after fixing the application logic

  • Frozen replay required zero additional LLM requests

The full experiment, including the recorded trace and offline tests, is reproducible without a Gemini API key.

Limitations

Stepfork is still an early alpha. Frozen replay only substitutes instrumented dependencies, not arbitrary side effects. It isn’t a sandbox, and developers must define their own expected outcomes.

I’d appreciate feedback

I’m particularly interested in how developers using Hugging Face models, Transformers, and agent frameworks approach reproducible testing.

Do you rely on mocks, recorded traces, live-model evaluations, or some combination?

Would a tool that turns recorded agent executions into pytest regression tests fit your workflow?

GitHub: GitHub - utsab345/stepfork: Open-source Python toolkit to record and replay AI agent executions, detect regressions, and turn failures into reproducible pytest tests. · GitHub

Documentation: Stepfork

Real Gemini case study: stepfork/examples/real-llm-case-study at main · utsab345/stepfork · GitHub

I’d appreciate feedback on the approach, especially which model providers and agent frameworks would be most useful to support next.

A Transformers generate() integration looks like a useful next target. One concrete test case would be your same postprocessing bug with a small local model, then replay the recorded output without loading the model. That would demonstrate which application logic remains live.

For the trace contract, I’d record the model/tokenizer revision, tokenized inputs, effective generation settings (including overrides) and generated token IDs. Transformers separates sampling and length controls in GenerationConfig, so a matching prompt alone would not describe the full generation request. A replay should fail clearly when the captured request contract changes.

I’d keep two separate checks: frozen-output regression tests for application logic, and live-model evaluations for changes in model behavior. Setting a seed is useful for the latter, but PyTorch explicitly does not guarantee identical results across releases, platforms, or CPU/GPU execution.

This is an AI-assisted, source-based integration suggestion; I haven’t tested Stepfork.

Thanks for the detailed suggestions! The distinction between frozen-output regression tests and live-model evaluations is exactly what I’m trying to maintain with Stepfork.

I agree that a Transformers generate() integration would need to capture more than the prompt. Model/tokenizer revisions, effective generation settings, and token IDs would all be important for detecting replay mismatches.

The small local-model experiment is a good idea too. Reproducing the same postprocessing bug and then replaying without loading the model would make the boundary between frozen dependencies and live application logic much clearer.

I’m keeping the scope focused for the current alpha, but I’ll consider this for a future integration.

If you get a chance to try the existing Gemini case study, I’d be interested in your feedback on the trace contract and replay behavior. Thanks again!

The two-check split you are maintaining (frozen-output regression vs live-model evaluation) is the right axis, and I think there is a second axis that matters more for a tool whose output is generated tests: who writes the verdict, and where the expectation came from.

Two things I measured while reviewing a related reproduction package, because both are cheap to hit and neither shows up as a red test.

1. A generated test encodes the run it was generated from, unless something forces the expectation to come from the requirement. I took one test in two versions — one asserting the requirement (year == 2024) and one produced after a diff dropped that pin and substituted a plausible value (year == current_year) — and ran both against a battery of mutants drawn from the implementation (a constant, a string, an off-by-one). Result: 3/3 killed by both versions — indistinguishable. Adding a single mutant drawn from the requirement (an implementation that violates it while looking like a fix) separated them: 4/4 vs 3/4. Both versions pass a “watch it fail first” discipline; only one of them still enforces what it was written for.

That matters here because Stepfork generates the test from a recorded execution, and a recorded execution is an observation. If the expectation is derived from the trace, the regression test pins “the behaviour I recorded” rather than “the behaviour I meant”, and a battery drawn from your own code cannot tell you which one you got. Suggested default: every generated regression suite carries at least one requirement-drawn mutant, and the mutant is derived from the claim sentence, not from the code under test.

2. The run’s receipt must be produced by the runner, not by the test file. Same tree, same defect, a stdlib runner standing in for CI:

  • honest test: FAILED (failures=1), runner exit 1, no receipt file;
  • test body that writes report.xml containing tests="1" failures="0" and then calls os._exit(0): runner exit 0, a green receipt, and the assertion never executes.

Three lines in the generated file turn a failing suite into a passing one, and nothing about the trace or the replay changes. For a tool that generates the files, the natural fix is that the tool (or a runner you control) owns the output path and the verdict, and the generated test is treated as untrusted input — the constraints on the trace contract that bbrooksvc described apply just as well to the report contract.

Third, smaller point on the replay side: when a check could not read its input, that is a third state, not a pass. A published reproduction script I have been working with makes this explicit — when its journal gates cannot read their carrier set they print NOT RUN, return exit 2, and the script states in its own output that this is “a coordinate of the run, not a finding about the work”. Freezing dependencies means your replay will fairly often be in that state (a provider changed, a recorded revision is gone), and a report format that can only say pass/fail will report it as a pass.

Happy to hand over the two fixtures (each is under 20 lines of standard-library Python); they were run locally today rather than taken from a write-up.

Thanks for the detailed analysis. These are really useful points, especially the distinction between reproducing an observed execution and verifying an intended requirement.

Stepfork currently relies on developer-defined expectations for generated regression tests, precisely because a recorded trace alone cannot establish whether the observed behavior is correct. Your requirement-derived mutation example highlights an additional way to evaluate whether those expectations are actually meaningful.

The runner-owned verdict point is interesting too. I agree that generating a pytest file and trusting its reported outcome are separate concerns. Stepfork currently focuses on generating reproducible tests rather than providing a trusted execution environment, but this is an important boundary to document clearly.

I also agree that an inability to replay should never be interpreted as a successful regression check. Distinguishing failed assertions from replay errors and tests that could not execute is important.

I’d definitely be interested in seeing both fixtures, particularly the runner receipt example. They would be useful for evaluating the current behavior and identifying where stronger guarantees might be needed.

Thanks again for taking the time to test these failure modes and share concrete examples!

Both fixtures, as promised. Standard library only, and these are the source fragments I re-ran a few minutes ago (not a reconstruction).

1. The requirement-directed mutant — a one-row addition to the battery.

The mutation fixture is one pinned requirement, five implementations, and two versions of one test. Three implementations are drawn from the code (syntactic breaks); one is drawn from the requirement — it drops the pinned constant while still producing a plausible year:

NOW_YEAR = 2026
PIN = 2024

def correct():    return PIN          # what the requirement demands
def real_year():  return NOW_YEAR     # plausible, drops the pin   <- requirement-drawn
def const_2020(): return 2020         # syntactic break
def as_string():  return "2024"       # syntactic break
def off_by_one(): return PIN + 1      # syntactic break

def test_pinned_original(): return correct() == PIN
def test_pinned_edited():   return correct() == NOW_YEAR   # the diff that replaced the pin

A mutant is “killed” when applying it turns the test red. Output, verbatim:

mutant                                                        original test  edited test
const_2020        (code-drawn)                                         True         True
as_string         (code-drawn)                                         True         True
off_by_one        (code-drawn)                                         True         True
real_year         (REQUIREMENT-drawn: pin dropped, plausible year)     True        False

mutation score, CODE-DRAWN battery (3 mutants):      original 3/3   edited 3/3   <- identical
mutation score, adding the REQUIREMENT-directed mutant: original 4/4   edited 3/4

So the code-drawn battery scores identically for both versions, and the requirement-drawn mutant separates them — while the script also reports that both versions pass “watch it fail first”. The wiring between an assertion and some behaviour is intact in both; only one is still connected to the reason it was written. For generated tests the suggestion is exactly this: derive at least one mutant from the claim sentence, because a battery drawn from the implementation can only test the wiring.

2. The runner-owned receipt.

Three files. The defect is the same in both runs; only the writer of the receipt differs.

# variant A (honest)
def total(): return 4200        # a real defect: the filter was dropped
class T(unittest.TestCase):
    def test_excludes_body_only(self):
        self.assertEqual(total(), 3900)
# variant B (the tree writes the verdict the gate is about to read)
def test_excludes_body_only(self):
    pathlib.Path("report.xml").write_text(
        '<testsuite tests="1" failures="0" errors="0"/>\n')
    os._exit(0)              # never reaches the assertion below
    self.assertEqual(total(), 3900)

The runner deletes any stale receipt, runs the suite, and decides from the file it then finds, not from what the suite said:

r = subprocess.run([sys.executable, "test_calc.py"], cwd=d, capture_output=True, text=True)
report = pathlib.Path(d, "report.xml")
verdict = "NO RECEIPT"
if report.exists():
    xml = report.read_text().strip()
    verdict = "GREEN" if 'failures="0"' in xml and 'errors="0"' in xml else "RED"
print(json.dumps({"variant": os.path.basename(d), "runner_exit": r.returncode, "receipt": verdict}))

Measured, verbatim:

{"variant": "honest", "runner_exit": 1, "receipt": "NO RECEIPT", "stderr_tail": "FAILED (failures=1)"}
{"variant": "forged", "runner_exit": 0, "receipt": "GREEN", "stderr_tail": ""}

Three lines moved the verdict from FAILED (failures=1) / exit 1 to a green receipt and exit 0. One detail worth keeping: the honest variant produces no receipt at all, which is the third state rather than a failure — “no receipt” is not “pass”. If Stepfork generates the test file, the clean split is that the trace and the generated test stay inputs and the deciding runner is one you own, so a generated file has no path to the artifact the verdict is read from.

Both are about 20 lines each; I can post either as a single runnable file if the fragments are less useful than that.

Thanks for sharing both fixtures and the actual results! The examples make the issues much clearer, especially how a test can catch implementation bugs while missing the original requirement.

The runner-owned verdict example is interesting too. I agree that generated tests and authoritative test results should have separate trust boundaries.

Stepfork currently relies on developer-defined expectations, but these examples highlight areas worth exploring further.

Would you be interested in contributing this to Stepfork? Feel free to open a GitHub issue with the fixtures and proposed improvements, or submit a PR if you’d like to work on the implementation. I’d be happy to review and collaborate.

GitHub: GitHub - utsab345/stepfork: Open-source Python toolkit to record and replay AI agent executions, detect regressions, and turn failures into reproducible pytest tests. · GitHub

Really appreciate the time you’ve put into investigating this!

Following up on the two fixtures from earlier: thanks for the nudge to open an issue — they are now utsab345/stepfork#14, and the first half is an open PR, #15, which adds score_expectation to stepfork.export with tests covering both the claim-pinned and the run-pinned case. The replay-verdict and runner-owned-receipt parts stay in #14 for a separate review, as requested.