Designing an LLM-Driven Test Automation Platform for Pull Requests
System DesignModel answerLast updated
Design a multi-agent system that turns specs and diffs into reviewed tests, runs them in isolation, repairs broken scripts, and separates script faults from real product regressions.
Scenario
A large engineering organization merges thousands of changes every day, and writing and maintaining tests by hand has become the bottleneck. You are asked to design an LLM-agent-driven test automation platform. It consumes product requirement documents, code diffs, OpenAPI specs and design links, and coordinates several specialized agents to produce:
- reviewed, structured test cases,
- synthetic test data,
- runnable test scripts (browser end-to-end and API integration),
- execution results and a report, with draft bug tickets for real failures.
Functional requirements
- Traceability. Every artifact links in both directions: requirement, test case, script, execution run.
- Data and script generation. Fixtures must be realistic but contain no real personal data. Scripts target a browser-automation framework for UI flows and a Python test framework for APIs.
- Isolated execution with repair. Run generated scripts in a sandbox. When a script fails for script-level reasons (syntax, broken selector), retry with automatic fixes up to a fixed limit, without hiding genuine product defects.
- Human review gates. Risky or destructive tests and data require human approval before they run.
- Reporting. Produce a structured report with evidence (logs, network traces, screenshots) and draft de-duplicated defect tickets.
Non-functional requirements
- Determinism. Agent-to-agent handoffs must be schema-validated to limit hallucinated content.
- Security. Untrusted, model-written code must not reach production systems, leak data, or break out of its runtime.
- Latency. Typical changes complete the pipeline in under 15 minutes.
Load assumptions
- 2,500 changes or specs per day.
- About 20 generated test cases per spec.
- Up to 50,000 test executions per day across a distributed runner fleet.
What to cover
- The agent roles and the state machine or graph that orchestrates them.
- Typed contracts for the artifacts passed between agents.
- The sandbox used to run untrusted code.
- How the system decides whether a failure is a bad script or a real regression.
Include capacity estimates and a latency budget, and discuss trade-offs.
Hints
Hint 1
Start with arithmetic: executions per day, retry multiplier, peak rate and test duration give you the number of concurrent sandboxes. Then split the 15-minute budget across stages.
Hint 2
Treat the model as an untrusted component: validate every handoff against a schema, use deterministic non-LLM checks wherever possible, and run the workflow on a durable engine with idempotent steps.
Hint 3
For repair versus regression, ask what the repair agent is allowed to change. If it can alter expected results, it can silently erase real bugs, so lock the assertions and compare against a baseline build.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and capacity
Assumptions: inputs are the diff, requirements doc and OpenAPI spec; targets are web end-to-end and API tests; each change gets an ephemeral preview environment to test against.
| Quantity | Estimate |
|---|---|
| Specs | 2,500/day, concentrated in a working window: roughly 175/hour peak |
| Test cases | 2,500 x 20 = 50,000/day, matching the execution budget |
| Runs with retries | About 1.5x for repairs and flake reruns: ~75k/day, ~2/s average, ~6/s peak |
| Concurrency | 6/s x ~60 s per test = ~360 sandboxes; keep a warm pool of 400-500 |
| Tokens | Roughly 300k per spec, so ~750M/day. Route small models to simple steps and cache context. |
Latency budget (15 min): ingest and retrieval 1, planning 2, data and code generation in parallel 4, static verification 0.5, execution 5, repair and triage 2, report 0.5. Human review time is excluded from the SLA; low-risk approved tests proceed without waiting.
2. Orchestration
Use a durable workflow engine (Temporal, or a graph framework with persisted checkpoints). Each agent call is an idempotent activity keyed by (run_id, stage, input_hash), so crashes and retries resume without duplicate work.
INGEST -> PLAN -> [human gate if risky/destructive]
-> per test case: DATAGEN || CODEGEN -> STATIC_VERIFY
-> EXECUTE (PR build and baseline build) -> EVALUATE
-> pass: done | script-side: HEAL (<=3) -> EXECUTE | product-side: TRIAGE
-> REPORT + TICKET DRAFTS
Agents:
- Ingestor (plain code): parses diff, doc and spec into requirements and the set of impacted endpoints.
- Planner (strong model): writes test cases with expected results taken from acceptance criteria, and tags risk and destructiveness.
- Data generator (small model plus a fake-data library): produces fixtures valid against the schema by construction; a scanner rejects real-looking identifiers.
- Coder (code model): fills templates and page-object helpers rather than free-form code.
- Static verifier (no LLM): AST parse, lint, banned imports (process spawning, raw sockets, environment reads), and a check that each expected result maps to an assertion in code.
- Evaluator/triage, healer, reporter.
3. Contracts
Every hop uses a versioned typed model (Pydantic or JSON Schema): Requirement, TestCase, FixtureSpec, ScriptArtifact, ExecutionResult, Verdict. Key fields:
TestCase.req_ids(non-empty, for traceability),expected(the oracle, immutable after approval),destructive.ScriptArtifact.assertion_fingerprint: a hash of the assertions in the code.ExecutionResult.failure_signature: normalized error class plus stack, with evidence URIs.Verdict.label:SCRIPT_DEFECT,ENV_FLAKE,PRODUCT_REGRESSION,UNKNOWN, with confidence and rationale.
On validation failure, re-ask the model with the validator errors; after two failures the stage fails closed. Store the traceability graph as edge tables in a relational DB, evidence in object storage, and failure-signature embeddings in a vector index for ticket de-duplication.
4. Sandbox
- Isolation: microVMs (Firecracker) for UI tests, user-space-kernel containers (gVisor) for cheaper API tests. One sandbox per run, destroyed afterward, drawn from a warm pool to avoid cold starts. Read-only root filesystem, tmpfs workspace, non-root, seccomp, no host mounts, caps such as 2 vCPU, 4 GB, 5 min.
- Network: default-deny egress. Allow only the PR's preview environment, a mock server generated from the OpenAPI spec for third-party dependencies, and the artifact upload endpoint. No route to production, metadata services or internal DNS.
- Secrets and data: short-lived test-tenant credentials injected per run; synthetic data only; cap outbound payload size and log egress to spot exfiltration.
- Scheduling: a queue feeds autoscaled runners based on depth; shard tests within a spec to fit the 5-minute execution budget.
5. Repair versus regression
The central rule: the healer may change how a test reaches a state, never what it asserts. After each patch, recompute the assertion fingerprint; any change to expected values or assertion count rejects the patch.
Classify in layers, cheapest first:
- Error taxonomy. Syntax errors, import errors, and locator-not-found before any assertion point to the script. Assertion mismatches on a reached state, 5xx responses, and contract violations point to the product.
- Baseline differential. Run the same script on the baseline build. Fails on both: likely script or environment. Passes on baseline, fails on the PR: likely regression.
- Flake check. Rerun a few times; inconsistent results are labeled
ENV_FLAKEand tracked against a flake score. - LLM judgment only for the ambiguous remainder, given the logs, DOM snapshot, and the diff, with a confidence score. Low confidence yields
UNKNOWNand goes to a human.
Cap repair at 3 attempts. Never auto-repair a failure classified as product-side.
6. Review gates and reporting
Gate high-risk areas (payments, authentication) and any destructive test or data. Show reviewers a diff-style view and allow batch approval. The report lists requirement coverage, pass/fail per test, evidence links, and draft tickets de-duplicated by signature similarity.
7. Trade-offs and common mistakes
- Letting the same model write the test and judge its failure biases results; use the baseline run and deterministic checks as independent evidence.
- Unbounded repair loops burn tokens and mask bugs.
- Free-form generated code is hard to verify; templates and page objects shrink the attack and error surface.
- Running tests against shared staging causes flakiness; per-PR environments cost more but give clean signal.
- Forgetting idempotency leads to duplicate tickets after retries.
- Track metrics: escaped-defect rate, false-positive ticket rate, repair success rate, flake rate, cost per spec.