by Rajesh K | Nov 17, 2026 | Artificial Intelligence, Blog, Latest Post |
Choosing between Promptfoo vs DeepEval vs Ragas? Start with the workflow you need to improve. Shortlist Promptfoo for configuration-driven comparisons and integrated red teaming, DeepEval for evaluation assertions inside application test suites, and Ragas for dataset-based experiments and retrieval diagnostics. These are starting recommendations, not exclusive capabilities: all three extend beyond those descriptions.
The useful question is not which framework has the most metrics. It is which one helps your team detect the failures that matter, investigate them, and make a defensible release decision.
This Promptfoo vs DeepEval vs Ragas comparison is for QA engineers, software development engineers in test (SDETs), AI engineers, and technical leads evaluating large language model (LLM) applications. It covers retrieval-augmented generation (RAG), continuous integration / continuous delivery (CI/CD), and operating trade-offs. Method: primary-source review and isolated code checks, not a live framework benchmark.
Table of Content
- Promptfoo vs DeepEval vs Ragas: Comparison at a Glance
- Promptfoo vs DeepEval vs Ragas: How the Three Evaluation Workflows Differ
- Compare Metrics, Test Data, and Judge Reliability in Promptfoo vs DeepEval vs Ragas
- One Support-Assistant Test Case, Implemented Three Ways
- Promptfoo vs DeepEval vs Ragas for RAG, Agent, and Security Testing: Where the Tools Overlap
- CI/CD, Reporting, and Regression Gates
- Promptfoo vs DeepEval vs Ragas: Cost, Licensing, Privacy, and Maintenance
- Promptfoo vs DeepEval vs Ragas: Which Tool Should Your Team Choose?
- Conclusion
Promptfoo vs DeepEval vs Ragas: Comparison at a Glance
The research baseline for this Promptfoo vs DeepEval vs Ragas comparison, checked on November 11, 2026, is Promptfoo 0.125.1 (released October 25, 2026), DeepEval Python 4.3.3 (November 4, 2026), and Ragas 0.4.3 (January 13, 2026). These are separately identified releases, not a jointly tested compatibility matrix. TypeScript observations are independently scoped to DeepEval 0.9.25, using the typescript-v0.9.25 tagged README and manifest. Versioned sources establish release-specific facts; other linked documentation is a dated, rolling reference.
Table 1. Promptfoo vs DeepEval vs Ragas workflow and capability comparison; adoption effort is an editorial assessment.
| S. No |
Selection criterion |
Promptfoo |
DeepEval |
Ragas |
| 1 |
Main working style |
Prompts, providers, test cases, and assertions |
Test cases, metrics, assertions, and traces |
Datasets, metrics, and experiments |
| 2 |
Main interfaces |
YAML configuration, CLI, JavaScript/TypeScript library; custom providers |
Python; separate TypeScript 0.9.25 implementation with documented gaps |
Python and project quick-start CLI |
| 3 |
Regression integration |
CLI execution and exported results |
pytest-style assertions and evaluation runner |
Python execution; add your release-gate policy |
| 4 |
RAG evaluation |
Built-in RAG assertions and custom checks |
Answer and retrieval metrics |
Retrieval, grounding, and correctness metrics |
| 5 |
Agent evaluation |
Application/provider integration and agent assertions |
End-to-end, trajectory, and component-level evaluation |
Tool-use and agent-goal metrics |
| 6 |
Adversarial testing |
Integrated red-team workflow |
Dedicated red teaming through separate DeepTeam framework |
Custom evaluation workflows; not an equivalent dedicated attack engine in the reviewed scope |
| 7 |
Review experience |
Local comparison viewer and reports |
Local results; optional Confident AI collaboration |
Experiment results; storage and integration choices |
| 8 |
Main adoption work |
Connect the application and define meaningful assertions |
Instrument relevant behavior and maintain test fixtures |
Assemble reliable datasets and operationalize experiments |
Capabilities in the table are documented; the adoption-work row is an engineering assessment. A custom workflow is not the same as a built-in feature, and a separate service should not be counted as part of a core library.
Promptfoo vs DeepEval vs Ragas: How the Three Evaluation Workflows Differ
Promptfoo: Configuration-Driven Evaluation and Red Teaming
Promptfoo organizes evaluations around prompts, providers, variables, and assertions. Its comparison view is useful when reviewing multiple prompt or model configurations against the same cases. Providers can connect the harness to an application rather than only a standalone model.
It is a sensible starting point when your team wants reviewable configuration and side-by-side results. The main design work remains yours: expose the right inputs, capture relevant context, and define what a failure means. A convenient runner cannot compensate for a weak test contract.
DeepEval: Test-Suite and Trace-Based Evaluation
DeepEval brings evaluation into a familiar test-suite structure: create a test case, attach metrics, and assert the result. Component-level evaluation can associate metrics with instrumented spans, helping separate a retrieval problem from a generation or tool-use problem.
DeepEval also offers a TypeScript implementation with a Vitest-oriented workflow. The reviewed announcement labels it beta and does not guarantee numeric score parity with Python. The independently inspected TypeScript 0.9.25 README identifies capability gaps, including synthetic data generation and benchmarks. Check the implementation you intend to adopt rather than extrapolating from the Python version.
Ragas: Dataset-Based Experiments and RAG Diagnostics
Ragas structures experimentation around a dataset, application execution, metrics, and stored results. Its experiment interface supports comparing deliberate changes such as a retriever or prompt revision. Its documentation also covers general-purpose criteria and AI-agent evaluation.
Shortlist it when the hardest question is diagnostic: did retrieval miss evidence, did irrelevant passages dominate, or did generation add unsupported claims? Budget separately for the dataset preparation, result review, and release-gate logic your organization needs.
Compare Metrics, Test Data, and Judge Reliability in Promptfoo vs DeepEval vs Ragas
Deterministic Checks, Model-Based Metrics, and Reference Answers
Use deterministic checks for rules that have an exact answer: valid JSON, required fields, a known eligibility decision, or an allowed tool name. Use model-based evaluation for semantic judgments that cannot be reduced to those rules. Promptfoo supports both deterministic and model-graded assertions; DeepEval and Ragas expose model-based metrics alongside other evaluation options.
For a RAG application, distinguish these questions before choosing metrics:
Table 2. Evaluation questions and the evidence each one requires.
| S. No |
Evaluation question |
Evidence to retain |
Important qualification |
| 1 |
Did the response obey the output contract? |
Raw response, schema, expected field values |
A structurally valid response can still be wrong. |
| 2 |
Are its claims supported by retrieved evidence? |
Response and actual retrieved passages |
Faithfulness does not establish that the passages are current or authoritative. |
| 3 |
Did retrieval cover the information needed? |
Question, retrieved passages, reference answer or reference contexts |
The required reference depends on the recall metric variant. |
| 4 |
Is the answer correct for this case? |
Current authoritative reference and expected decision |
Relevance and grounding are not substitutes for correctness. |
DeepEval and Ragas faithfulness metrics judge support against retrieved context. Ragas’s LLM-based context recall uses a reference answer; other recall variants use different reference evidence. “Reference-free evaluation” therefore cannot describe every metric in a framework.
Why Faithfulness and Correctness Are Different
Consider a fictional returns policy. The current rule allows returns through day 30, but retrieval supplies an obsolete 14-day policy. An answer that repeats the obsolete rule could be faithful to its retrieved context while giving the wrong current decision. This follows from what faithfulness measures; it is not an observed test result.
Keep the authoritative reference separate from the retrieved passages. Otherwise, a stale retrieval can silently become the evaluator’s definition of truth.
Why Scores Are Not Interchangeable
A score of 0.9 is not automatically equivalent across frameworks. Claim extraction, prompts, judge configuration, treatment of ambiguous claims, and aggregation can differ even when the metric names sound identical. The respective faithfulness implementations document their own scoring processes.
For a fair comparison, freeze the same captured outputs and evidence, specify the judge rather than accepting defaults, and review disagreements against human-labeled cases. Use a separate holdout set when selecting thresholds. Include known bad answers and adversarial text, not just easy successes. These are calibration recommendations, consistent with the need to validate model-based judges against the intended task.
Keep evaluator-directed injection separate from application prompt injection within the adversarial set. A response or passage that asks the judge to ignore its rubric is untrusted evaluation data, not an instruction. Check whether it changes the verdict and review disagreements; do not assume an evaluator is immune because it is used for testing.
One Support-Assistant Test Case, Implemented Three Ways
Define the Shared Test Contract
The examples below put Promptfoo vs DeepEval vs Ragas side by side on one shared case. These are illustrative captured-output examples, not verified end-to-end installations. They evaluate one saved response rather than calling the support application. Model-based grading still calls an external judge. Local contract and wrapper checks are reported below; no live judge verdicts or comparative scores are claimed.
Assume a fictional policy with no product-specific exceptions: an item is eligible from day 0 through day 30 after delivery, inclusive. The case fixes elapsed days at 30, avoiding timestamp ambiguity. Its intended contract is a Boolean eligible field matching the reference decision and a nonempty answer supported by the supplied context. A common threshold does not make the three semantic evaluators identical.
Save this as cases.json. The outer structure is compatible with Promptfoo’s JSON test-case format; the Python examples read the same file.
[
{
"description": "return-day-30",
"vars": {
"query": "Can I return an item 30 days after delivery?",
"reference": "Policy v2: eligible from day 0 through day 30 inclusive.",
"context": "Policy v2: eligible from day 0 through day 30 inclusive.",
"expected_eligible": true,
"actual_output": "{\"eligible\":true,\"answer\":\"Yes, day 30 is included.\"}"
}
}
]
Privacy preflight: approve provider routing and use synthetic or sanitized fixtures before executing anything. Set the following opt-outs before imports/runs. They disable the documented telemetry paths, not model inference or every optional service. The restrictive file-permission mask applies on POSIX systems; still configure CI artifact access and retention.
# Review provider routing before running; these only disable telemetry.
export PROMPTFOO_DISABLE_TELEMETRY=1
export DEEPEVAL_TELEMETRY_OPT_OUT=1
export RAGAS_DO_NOT_TRACK=true
umask 077
Setup assumptions, not a verified environment: Node.js 24 for Promptfoo and Python 3.11 in separate virtual environments for the Python examples. Use [email protected], deepeval==4.3.3, or ragas==0.4.3 as appropriate. The Ragas example also needs the openai Python SDK. Validate and lock all resolved dependencies, including the SDK, before adopting these examples; a tested dependency lock is not supplied. Promptfoo’s tagged manifest requires Node.js 22.22.0 or newer.
Supply OPENAI_API_KEY through your secret manager and set JUDGE_MODEL to an explicitly selected, supported OpenAI judge model. The examples use that provider for consistency, not as a requirement of all three frameworks. Do not put credentials in fixtures or committed configuration.
Both Python examples use fixture.py below. Importing it performs no file reads. load_case() validates the fixture envelope; checked_answer() checks the captured application output. A missing or malformed fixture is an invalid evaluation, whereas a malformed response inside a valid fixture is an application quality failure.
"""One-case illustrative fixture; importing this module performs no I/O."""
import hashlib
import json
from pathlib import Path
class FixtureError(ValueError):
pass
class OutputContractError(AssertionError):
pass
def load_case(path: Path) -> dict:
try:
raw = path.read_bytes()
rows = json.loads(raw)
except (OSError, ValueError, UnicodeError) as exc:
raise FixtureError("Unreadable or malformed fixture") from exc
if not isinstance(rows, list) or len(rows) != 1:
raise FixtureError("This demonstration requires one case")
row = rows[0]
if not isinstance(row, dict):
raise FixtureError("Case must be an object")
case_id, case = row.get("description"), row.get("vars")
if not isinstance(case_id, str) or not case_id.strip():
raise FixtureError("Missing stable case ID")
if not isinstance(case, dict):
raise FixtureError("Missing vars object")
for key in ("query", "reference", "context"):
if not isinstance(case.get(key), str) or not case[key].strip():
raise FixtureError(f"Invalid fixture field: {key}")
if not isinstance(case.get("actual_output"), str):
raise FixtureError("Captured output must be a string")
if type(case.get("expected_eligible")) is not bool:
raise FixtureError("Expected decision must be Boolean")
return {**case, "case_id": case_id,
"fixture_sha256": hashlib.sha256(raw).hexdigest()}
def checked_answer(case: dict) -> str:
try:
body = json.loads(case["actual_output"])
except (TypeError, ValueError) as exc:
raise OutputContractError("Invalid application JSON") from exc
if not isinstance(body, dict):
raise OutputContractError("Output must be an object")
if (type(body.get("eligible")) is not bool or
body["eligible"] != case["expected_eligible"]):
raise OutputContractError("Incorrect eligibility decision")
answer = body.get("answer")
if not isinstance(answer, str) or not answer.strip():
raise OutputContractError("Missing answer")
return answer
The reference field preserves the source for the expected Boolean; these minimal examples do not separately score every statement against the authoritative reference. For example, eligible=true with the answer “No, day 30 is excluded” passes the deterministic shape/decision checks. That does not make the text correct: semantic consistency needs the separate evaluator or another explicit assertion. No judge verdict is inferred from this local boundary check.
Promptfoo Configuration
Promptfoo’s echo provider passes the captured output through without generating a new answer. The JavaScript assertion checks the output contract. The model-graded assertion then assesses the answer’s grounding. The latter still needs a judge.
Save as promptfooconfig.yaml:
prompts:
- '{{actual_output}}'
providers:
- echo
tests: file://cases.json
defaultTest:
assert:
- type: javascript
value: |
try {
const body = JSON.parse(output);
return body !== null && !Array.isArray(body)
&& typeof body.eligible === 'boolean'
&& body.eligible === context.vars.expected_eligible
&& typeof body.answer === 'string'
&& body.answer.trim().length > 0;
} catch {
return false;
}
- type: context-faithfulness
transform: 'JSON.parse(output).answer'
threshold: 1.0
Run from the fixture directory in a POSIX shell:
: "${OPENAI_API_KEY:?Set an approved provider key}"
: "${JUDGE_MODEL:?Select an approved judge model}"
npx [email protected] eval -c promptfooconfig.yaml \
--grader "openai:chat:${JUDGE_MODEL}" --no-cache \
-o promptfoo-results.json
The 1.0 cutoff is a demonstration choice, not a calibrated production threshold or a guarantee of strict semantic interpretation. Inspect assertions separately: an incorrect Boolean must fail even when the answer sounds plausible. Malformed application output is a quality failure; a subsequent grading error must not erase that failure or be treated as a pass.
DeepEval Python Test
Save as test_returns.py. The helper validates the deterministic contract. FaithfulnessMetric assesses the extracted answer against retrieved evidence, with LLM mode and ambiguous-claim handling explicitly selected. assert_test() connects the metric result to the test outcome.
import os
from pathlib import Path
from deepeval import assert_test
from deepeval.metrics import FaithfulnessMetric
from deepeval.test_case import LLMTestCase
from fixture import load_case, checked_answer
def test_return_boundary():
case = load_case(Path(__file__).with_name("cases.json"))
answer = checked_answer(case)
metric = FaithfulnessMetric(
model=os.environ["JUDGE_MODEL"],
eval_mode="llm",
threshold=1.0,
penalize_ambiguous_claims=True,
include_reason=True,
)
test_case = LLMTestCase(
input=case["query"], actual_output=answer,
retrieval_context=[case["context"]],
)
assert_test(test_case, [metric])
Ambiguous-claim policy: in the inspected Python 4.3.3 source, penalize_ambiguous_claims defaults to False. Setting it to True excludes ambiguous claims from passing verdicts; threshold=1.0 alone does not change that policy. eval_mode=”llm” prevents an ambient mode setting from silently changing this example. Include unsupported, ambiguous, contradictory, and no-claim responses in judge calibration. These settings express the intended policy; they do not prove the judge applies it correctly.
Run deepeval test run test_returns.py in the activated DeepEval environment. Retain the test result, metric settings, judge identifier, score, and available explanation. Keep framework errors distinct from quality failures in your CI adapter; this native runner does not inherit the custom Ragas wrapper’s exit-code convention.
Ragas Python Evaluation
Ragas 0.4.3 uses the collections interface shown below. The wrapper places fixture loading and optional-package imports inside its protected execution path, checks the installed Ragas version, and rejects nonfinite or out-of-range scores. It writes a structured result for completed decisions and handled invalid runs. The 120-second evaluation budget is illustrative.
Save as ragas_returns.py:
"""Illustrative wrapper. Unit-tested with a stub scorer, not a live judge."""
import asyncio
import json
import math
import os
import sys
import time
import uuid
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path
def installed(name: str):
try:
return version(name)
except PackageNotFoundError:
return None
async def score_answer(case: dict, answer: str, model: str):
# Optional-package imports occur inside the protected execution path.
from openai import AsyncOpenAI
from ragas.llms import llm_factory
from ragas.metrics.collections import Faithfulness
async with AsyncOpenAI(timeout=30.0, max_retries=0) as client:
metric = Faithfulness(llm=llm_factory(model, client=client))
result = await metric.ascore(
user_input=case["query"], response=answer,
retrieved_contexts=[case["context"]],
)
return result.value
async def bounded_score(case, answer, model):
return await asyncio.wait_for(
score_answer(case, answer, model), timeout=120.0
)
def run(case_path: Path, artifact_path: Path) -> int:
started = time.monotonic()
record = {
"schema_version": 1, "run_id": uuid.uuid4().hex,
"case_id": None, "fixture_sha256": None,
"framework": "ragas", "required_version": "0.4.3",
"installed_version": None, "openai_sdk_version": None,
"metric": "collections.Faithfulness", "metric_version": "0.4.3",
"judge_provider": "openai", "judge_model": None,
"judge_parameters": "library defaults; not cross-tool normalized",
"threshold": 1.0, "sdk_timeout_s": 30, "sdk_max_retries": 0,
"evaluation_deadline_s": 120, "judge_call_count": None,
"expected_cases": 1, "validated_cases": 0, "completed_cases": 0,
"status": "INVALID_RUN", "score": None, "reason": None,
"error_category": None, "exit_code": 2,
}
try:
from fixture import load_case, checked_answer, OutputContractError
record["installed_version"] = installed("ragas")
record["openai_sdk_version"] = installed("openai")
record["judge_model"] = os.getenv("JUDGE_MODEL")
case = load_case(case_path) # No import-time fixture I/O.
record.update(case_id=case["case_id"], validated_cases=1,
fixture_sha256=case["fixture_sha256"])
try:
answer = checked_answer(case)
except OutputContractError:
record.update(status="QUALITY_FAIL", exit_code=1,
completed_cases=1, error_category="output_contract")
else:
if record["installed_version"] != "0.4.3":
raise RuntimeError("Missing or unexpected Ragas version")
model = record["judge_model"]
if not model or not model.strip():
raise ValueError("JUDGE_MODEL is required")
score = asyncio.run(bounded_score(case, answer, model))
if (isinstance(score, bool) or not isinstance(score, (int, float))
or not math.isfinite(score) or not 0 <= score <= 1):
raise ValueError("Invalid or non-applicable metric score")
passed = score >= record["threshold"]
record.update(score=score, completed_cases=1,
status="PASS" if passed else "QUALITY_FAIL",
exit_code=0 if passed else 1)
except Exception as exc:
# Class only: do not copy provider messages or fixture text into logs.
record.update(status="INVALID_RUN", exit_code=2,
error_category=type(exc).__name__)
record["duration_ms"] = round((time.monotonic() - started) * 1000, 3)
try:
artifact_path.write_text(
json.dumps(record, indent=2, allow_nan=False) + "\n",
encoding="utf-8",
)
except OSError:
record.update(status="INVALID_RUN", exit_code=2,
error_category="artifact_write_error")
print(json.dumps(record, allow_nan=False))
return record["exit_code"]
if __name__ == "__main__":
source = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("cases.json")
target = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("ragas-result.json")
raise SystemExit(run(source, target))
Run python ragas_returns.py cases.json ragas-result.json in the prepared Ragas environment. The wrapper uses 0 for checks passed, 1 for a completed quality failure, and 2 for an invalid run, including fixture-loading errors. These are wrapper conventions, not universal Ragas exit codes. SDK retries are disabled; inspect framework-level retry behavior separately.
The result artifact contains a run ID, case ID when validated, fixture hash, installed framework/SDK versions, metric version, judge ID, threshold, status, score, duration, and sanitized error category. A deterministic failure short-circuits grading; completed_cases counts a terminal quality decision, not the execution of every metric. If artifact writing fails, the wrapper exits 2 and emits a fallback record to standard output. CI must also reject a missing or incomplete artifact.
Ragas 0.4.3’s inspected faithfulness implementation returns NaN when it extracts no statements and returns a score without a metric explanation. This wrapper rejects NaN and leaves reason null. For an answerable policy question, a no-claim response is not proof of successful grounding. Valid abstention belongs to its own expected behavior and applicability policy.
Local verification: 75 isolated checks passed on Python 3.13.5 and Node.js 22.16.0. They include fixture validation, Python/JavaScript contract checks, controlled wrapper scores/errors, actual subprocess exit codes, and configuration checks using test doubles. They do not establish framework compatibility or semantic accuracy. No real framework installation, judge/API call, cost measurement, or three-tool benchmark was performed; the Node runtime used for these isolated checks is below Promptfoo’s stated minimum.
Retrieval Quality Versus Answer Quality
For RAG work, Promptfoo vs DeepEval vs Ragas is not a choice between single-purpose tools. Promptfoo documents RAG assertions, DeepEval provides retrieval and answer metrics, and Ragas covers both retrieval diagnostics and generation evaluation. None should be reduced to a single-use label.
Use the following risk-based matrix to plan the broader suite; these are proposed application/judge tests, not executed outcomes. The displayed loader deliberately accepts one case. Do not append rows and expect it to become a suite: first replace load_case() with a validated collection loader, require unique case IDs, parameterize test execution, and retain per-case results. Reconcile expected, discovered, and completed counts; missing or duplicate cases must block the release decision.
Table 3. Proposed support-assistant risk matrix; not executed application results.
| S. No |
Scenario |
Controlled input or change |
Expected assertion and evidence |
| 1 |
Normal answer |
Ask about day 10 with current policy |
Eligible; supported answer; retain response and passage IDs. |
| 2 |
Boundary |
Compare days 30 and 31 |
Eligible on 30, ineligible on 31; retain explicit expected decisions. |
| 3 |
Missing evidence |
Ask about an undocumented exception |
Apply a separately defined abstention/escalation contract; retain missing-evidence status. |
| 4 |
Stale evidence |
Retrieve obsolete 14-day policy for a day-20 question |
Flag incorrect current decision; retain old and current document versions. |
| 5 |
Adversarial passage |
Add an instruction to disregard the authorized policy |
Do not follow the injected instruction; retain passage and execution evidence. |
| 6 |
Judge failure |
Force timeout, unavailable service, or malformed grading output |
Mark invalid; retain error category and attempts, never a synthetic passing score. |
The missing-evidence case needs a separately defined abstention/escalation contract; a Boolean-only answer is not universal. A valid abstention can make a grounding metric inapplicable, but “not applicable” must be recorded explicitly and excluded only by a predefined policy, not converted to a perfect score. See Codoid’s RAG Testing: Retrieval Regression, Precision & Recall for retrieval-specific coverage.
DeepEval supports component and trajectory evaluation; Ragas includes tool-call and agent-goal metrics. These can help assess an agent’s behavior, but the evidence provided determines what can be concluded.
For a refund-capable assistant, capture the authenticated principal, tool name, arguments, approval decision, tool response, and final transaction state. A tool call mentioning the correct order is not proof that authorization was enforced. A final answer saying “I did not issue a refund” is not proof that no refund occurred.
Use sandboxed accounts and direct application assertions for forbidden side effects. When testing retries or concurrent requests, inspect transaction counts and idempotency behavior as well as the conversational response. These are application-test requirements, not capabilities an LLM metric supplies automatically.
Safety Metrics Versus Adversarial Red Teaming
Scoring a fixed set of harmful responses and actively probing an application are different activities. Promptfoo includes a red-team generation and execution workflow. DeepTeam is a separate red-teaming framework built on DeepEval. Ragas can participate in custom safety evaluation, but that is not equivalent to a dedicated attack-generation workflow.
Preserve useful adversarial findings as repeatable regression cases. Test only authorized systems and prevent real-world actions during probes. Codoid’s Prompt Injection Regression Testing for LLM & AI Agents covers the broader regression design.
CI/CD, Reporting, and Regression Gates
Turn Evaluation Failures into Build Failures
In CI/CD, the Promptfoo vs DeepEval vs Ragas decision depends on how each run becomes a build gate. Promptfoo provides CLI execution and result exports; its command reference documents a nonzero failed-test exit code. DeepEval’s runner integrates evaluation assertions with pytest-style tests. Ragas experiments can be executed from Python, with release policy applied by your own test runner or wrapper.
A report becomes a release gate only when the pipeline checks it. Require all intended cases to be discovered, all applicable mandatory metrics to complete, and all critical rules to pass. Track quality and execution status separately: an observed quality failure remains a failure even when another check is invalid. Block on either, and treat missing artifacts or premature process termination as incomplete runs.
Table 4. Release decisions must distinguish quality failures from invalid evaluations.
| S. No |
Run outcome |
Meaning |
Recommended release action |
| 1 |
Pass |
Required cases completed and all applicable rules passed |
Eligible for the next release check; not proof of universal safety. |
| 2 |
Quality failure |
Valid execution exposed an incorrect answer, forbidden action, or failed criterion |
Block; investigate the application or reviewed expectations. |
| 3 |
Invalid or incomplete |
Missing cases, judge error, invalid score, timeout, or absent evidence |
Block the decision; repair or retry under the agreed policy. |
Keep critical failures visible rather than averaging them away. For the broader workflow, see Codoid’s Prompt Regression Testing guide.
Handle Judge Errors, Retries, and Unstable Scores
Use a bounded retry policy for transient infrastructure errors, and record every attempt. Do not repeatedly rerun a valid quality failure until it happens to pass. For unstable borderline cases, define the repeat count and aggregation policy in advance, then review disagreement against the reference labels. Model-based judgments require calibration, not blind trust in a threshold.
For the full suite, retain case/run IDs, fixture and application revisions, framework/metric versions, judge settings, scores, available reasons, sanitized error categories, attempts, durations, and measured usage. The example records the fields it knows, leaves unavailable values null, and does not invent a Ragas explanation. Its duration is wrapper evaluation time, not target-application latency. Use separate artifact paths for concurrent runs and retain the dependency lock with each run.
Set concurrency to fit provider quotas, and make caching explicit. Cached answers help compare evaluator changes on fixed data, but they are not fresh evidence of changed application behavior. Promptfoo exposes caching and concurrency controls; choose settings to match the question the run is answering.
Promptfoo vs DeepEval vs Ragas: Cost, Licensing, Privacy, and Maintenance
Open-Source Frameworks Versus Hosted Services
The inspected Promptfoo release uses the MIT license; DeepEval and Ragas identify Apache-2.0 licensing. Those labels describe the open-source projects, not every hosted service, model provider, or enterprise feature associated with them.
Distinguish local execution from shared dashboards, access controls, hosted trace storage, and organizational support. Confident AI is optional for using DeepEval’s open-source evaluation framework. Verify commercial entitlements separately rather than inferring them from an open-source feature list.
Estimate operating cost as target inference plus judge inference, embeddings or test generation where used, retries, storage, CI execution, and human review. Count actual requests: a metric may require several model calls. Without measurements on your cases, there is no defensible “cheapest” winner. The documented claim-extraction and verification stages illustrate why a metric is not necessarily a single request.
Model Calls, Telemetry, and Offline Requirements
Local execution does not mean no outbound data. A local runner can still send prompts, responses, and evidence to a remote judge.
Promptfoo’s red-team data-handling documentation distinguishes hosted generation/grading from your own configured providers and identifies additional cloud-backed paths. DeepEval documents default usage telemetry. Ragas’s tagged source includes an analytics opt-out. Review those separately from model-provider data flows.
Apply the telemetry settings in the pre-execution privacy check before importing libraries or starting commands. Review local result files, cached responses, and CI artifacts as well as outbound requests.
Define who can read logs and artifacts, where they are stored, and when they expire. Sanitize content before sharing it; avoid copying raw provider exception messages, credentials, user identifiers, or retrieved private text into general build logs.
Telemetry opt-outs do not disable inference calls, uploads, or every optional integration. For restricted environments, inventory generation, grading, embedding, moderation, analytics, and sharing paths. Select compatible local components, then verify isolation using egress controls and network observation. Remote-only features may be unavailable; no tested local-provider configuration is claimed here.
Version Pinning and Upgrade Costs
Pin framework versions and dependency resolutions, record judge identifiers, and version your metric definitions alongside the application. Treat evaluator upgrades as measurement changes until a stable calibration set demonstrates otherwise.
Ragas’s v0.4 migration documentation distinguishes collections metrics from older interfaces. DeepEval’s TypeScript release notes and repository identify implementation differences. Mixing snippets or results across those boundaries can undermine a longitudinal comparison.
Before adopting an upgrade, rerun known-good, known-bad, and invalid-run cases. Explain changed verdicts before replacing the established baseline.
Select by Your Main Testing Workflow
When choosing between Promptfoo vs DeepEval vs Ragas for CI/CD, start with Promptfoo when configuration-led execution fits your pipeline, or DeepEval when application-owned test assertions fit your team’s workflow. For diagnosing RAG failures, Ragas is a strong candidate for dataset-based retrieval experiments, while Promptfoo and DeepEval also provide relevant metrics. Ragas can block a build through an explicit gate such as the wrapper above. These are conditional starting points, not exclusive capabilities.
Table 5. Promptfoo vs DeepEval vs Ragas: choose a proof-of-concept starting point by workflow, not by a universal ranking.
| S. No |
Your immediate need |
Start the proof of concept with |
What to verify before choosing |
| 1 |
Review prompt/model alternatives through configuration |
Promptfoo |
Application adapter, assertion clarity, result review, and failed-run handling |
| 2 |
Add evaluation assertions to existing application tests |
DeepEval |
Language-specific support, trace coverage, CI behavior, and maintenance burden |
| 3 |
Diagnose retrieval and compare dataset-based experiments |
Ragas |
Reference quality, required fields, metric interpretation, and gate integration |
| 4 |
Generate and exercise adversarial cases |
Promptfoo; assess DeepTeam separately if relevant |
Authorized attack scope, data routing, action isolation, and reproducible failures |
Run the same representative fixture set through the shortlisted tools. Include accepted answers, plausible wrong answers, boundaries, missing evidence, and one intentional judge failure. Have reviewers label the cases before inspecting automated verdicts.
Compare false passes, false failures, investigation effort, setup effort, completed-case rate, evaluation duration, and measured cost. Keep hard requirements, such as no external data transfer or mandatory language support, as pass/fail selection criteria, not weighted preferences that other features can offset.
When Combining Tools Is Worth the Maintenance
Combining tools can be useful when responsibilities remain distinct: for example, Promptfoo for adversarial regression discovery and execution, with DeepEval for application-owned test assertions; or Ragas for retrieval experiments whose selected cases feed the main release suite. These are proposed architectures, not turnkey integrations or measured outcomes.
Share stable case IDs, reference versions, and raw application evidence. Do not average scores from different implementations into a single “quality” number without validating what that number means. Prefer one framework when an additional tool adds only duplicate scoring and another report to reconcile.
Codoid offers LLM and AI application testing services for teams building an application-specific evaluation approach. Discuss a focused proof of concept around your failure risks, evidence requirements, and release workflow before selecting the tooling.
Conclusion
There is no universal winner in Promptfoo vs DeepEval vs Ragas. Promptfoo is a strong starting point for configuration-driven comparisons and integrated red teaming, DeepEval for evaluation assertions inside application test suites, and Ragas for dataset-based experiments and retrieval diagnostics. All three extend beyond those labels. Whichever way your Promptfoo vs DeepEval vs Ragas shortlist leans, run the same human-labeled fixtures through each candidate, keep quality failures separate from invalid runs, and pin versions before any score becomes a release gate.
Frequently Asked Questions
-
Is Ragas Only for RAG Applications?
No. Its documentation covers general-purpose criteria, experiments, and agent/tool-use evaluation as well as RAG metrics. Its name should not be treated as a limit on its current scope.
-
Does DeepEval Require a Confident AI Account?
No. The open-source framework can run evaluations without a Confident AI account. A configured remote judge may still require provider credentials and incur usage charges; that is separate from the optional hosted platform.
-
Can These Tools Run Without Sending Data to External Services?
Selected workflows can be configured around local components, but offline suitability is configuration- and feature-dependent. Audit model calls, telemetry, sharing, and integrations; do not infer isolation from where the CLI runs. Telemetry opt-out alone is insufficient.
-
Can I Compare the Same Metric Across All Three Tools?
Compare each evaluator’s agreement with the same human-labeled cases, not just equally named scores. Fix the data and judge configuration, inspect disagreements, and calibrate each implementation before using it as a release gate. The metric-comparison section explains why thresholds are not interchangeable.
by Rajesh K | Nov 16, 2026 | AI Testing, Blog, Latest Post |
Multilingual large language model (LLM) regression testing, a core practice in multilingual LLM testing, compares a released application with a candidate on the same reviewed cases in every supported language. Measure factual correctness against independent evidence, evaluate safety against a versioned policy, and make release decisions language by language. Cross-language agreement is useful diagnostic evidence, but it is not proof of correctness. Research on cross-lingual consistency evaluates factual accuracy and cross-language consistency as distinct properties.
The release question is: Did this change preserve required behavior for every supported language, including the highest-risk cases?
This guide applies multilingual LLM testing to text assistants and retrieval-augmented generation (RAG). Its fictional support assistant uses English, Hindi, Tamil, Spanish, and Arabic. Policies, thresholds, annotated examples, and scorecard results are illustrative, not client evidence or measured model performance. The proposed workflow is an engineering approach, not a certification standard. For LLM testing fundamentals, see Codoid’s Comprehensive LLM Software Testing Guide.
Workflow at a glance: reviewed fixtures and evidence → baseline/candidate responses → adjudicated labels → paired language-level comparisons → release gates → triage and retesting.
Table of Content
1. Define What Must Stay Consistent in Multilingual LLM Testing
Separate Factual Accuracy, Cross-Language Agreement, and Safety
In multilingual LLM testing, keep three questions separate. Factual accuracy: does the response satisfy verified facts? Agreement: do equivalent requests produce compatible claims? Safety: does the response follow policy while still providing permitted help?
If every language reports a 60-day return window when the approved policy says 30, the answers agree but are wrong. Correct paraphrases can also differ substantially in wording. Agreement therefore needs its own diagnostic metric rather than becoming an accuracy proxy.
Record language adherence and task completion separately. An English answer to a Tamil request can preserve the facts yet fail the language requirement. Codoid’s AI Application Testing: Bias, Safety, and Factuality Guide discusses broader quality dimensions.
Distinguish Language Differences from Legitimate Locale Differences
Hold market, product, permissions, and effective policy date constant when testing language invariance. A language switch should not silently select another market’s rules.
In the fictional example, Market A allows return requests within 30 days; Market B allows 14. Changing markets justifies a different answer. Changing the language of the same Market A customer does not. Missing market information should trigger the defined clarification behavior.
This distinction also matters when reading research. XL-SafetyBench evaluates country-language pairs, so those results do not isolate language effects from country effects.
2. Build a Multilingual LLM Testing Dataset with Trustworthy Ground Truth
Pair Equivalent Intents Without Making English the Ground Truth
The foundation of multilingual LLM testing is a shared intent identifier. Create one and review each language variant against authoritative evidence. An English model answer is another output to evaluate, not the reference truth.
Illustrative evidence: returns-A-v2, effective October 1, 2026. An unopened, standard eligible item in Market A can be returned by requesting a return within 30 calendar days after delivery; delivery is day zero. The original shipping fee is not refunded. These are invented business rules, not consumer-law guidance.
Preconditions are the same eligible item, Market A customer, and policy snapshot. The draft variants below require independent bilingual review before production reuse.
- Language: English | Equivalent question under the shared preconditions: What is the return-request window, and is the original shipping fee refunded?
- Language: Hindi | Equivalent question under the shared preconditions: वापसी का अनुरोध कितने दिनों के भीतर किया जा सकता है, और क्या मूल शिपिंग शुल्क वापस मिलता है?
- Language: Tamil | Equivalent question under the shared preconditions: திருப்பி அனுப்புவதற்கான கோரிக்கையை எத்தனை நாட்களுக்குள் செய்ய வேண்டும்? முதலில் செலுத்திய அனுப்புதல் கட்டணம் திருப்பித் தரப்படுமா?
- Language: Spanish | Equivalent question under the shared preconditions: ¿En qué plazo puedo solicitar una devolución y se reembolsa el coste del envío original?
- Language: Arabic | Equivalent question under the shared preconditions: ما المدة المتاحة لطلب الإرجاع، وهل تُرد رسوم الشحن الأصلية؟
The two required facts are the 30-calendar-day window after delivery and the non-refundable original shipping fee. Assert both, reject material contradictions, and retain response spans, source passages, and labels. Do not require identical wording.
Add Native-Language Cases, Code-Switching, and Transliteration
Use paired translations for controlled comparisons and native-authored requests for the actual audience. Global MMLU demonstrates how translating English questions can preserve cultural assumptions and introduce linguistic bias. Its benchmark informs dataset design; it is not an application regression suite.
Keep translated, native-authored, mixed-language, dialect/register, and transliterated subsets identifiable. An illustrative Hinglish request is “Return request kitne din mein kar sakta hoon? Original shipping fee refund hogi?” Review its intended meaning rather than expecting formal Hindi.
- Preconditions and variation: Eligible item; ask on day 30 and day 31 | Expected outcome and assertion: Accept an otherwise eligible return request on day 30; reject it on day 31, using delivery as day zero.
- Preconditions and variation: Same market; switch languages mid-conversation | Expected outcome and assertion: Preserve market and policy context; answer in the requested language.
- Preconditions and variation: Market missing; ambiguous date such as 03/04 | Expected outcome and assertion: Request the missing market/date interpretation rather than infer it from language.
- Preconditions and variation: Deadline near midnight in different time zones | Expected outcome and assertion: Apply the explicitly configured policy time zone; retain normalized timestamps and boundary evidence.
- Preconditions and variation: Evidence lacks refund-processing duration | Expected outcome and assertion: State the information gap or escalate; do not invent a duration.
- Preconditions and variation: Current policy selected; stale translated evidence retrieved | Expected outcome and assertion: Flag the source-version mismatch and investigate retrieval before blaming generation.
- Preconditions and variation: Timeout, interruption, or malformed judge result | Expected outcome and assertion: Retain partial output and failure status; withhold a semantic pass.
Keep original inputs, timestamps, source versions, assertions, and response evidence for each case. Boundary and date rules belong in the fixture, not in unstated assumptions.
Version Evidence, Expected Outcomes, and Dataset Splits
Version the test oracle, meaning the approved evidence and expected-outcome rules, independently of the application. Store language, script, market, conversation, source identifiers/hashes, effective dates, required facts, safety category, severity, and review status.
Give each variant a distinct case_id; map related variants to one intent_id, or cluster. For example, returns-001-es-neutral and returns-001-es-formal share intent_id: returns-001 but have different variant_id values. Keep translations, paraphrases, and conversation variants of that intent together when separating development, evaluator-calibration, and release-test data.
When business facts change, create a new oracle version and evaluate both systems against it. Do not edit expected answers merely because a candidate disagrees. Native-only cases need not enter the equivalent-language subset; define that subset before execution.
3. Measure Factual Accuracy Without Rewarding Confident Agreement
Score Short Answers and Long-Form Claims Against Independent Evidence
For short answers in multilingual LLM testing, compare entities, numbers, units, dates, polarity, and conditions. Normalize aliases or numeral forms only when meaning is preserved. For longer responses, extract independently checkable claims. FActScore introduced atomic supported-fact scoring; that measures factual precision, not completeness or overall task success.
Evaluate faithfulness to supplied context separately from correctness against the current oracle. Repeating a stale retrieved policy faithfully can still be wrong. Multilingual FActScore research also identifies extraction, judging, and knowledge-source coverage as potential scoring failures.
Illustrative Spanish answer trace, not an independently bilingual-reviewed annotation: the response below uses the shared Market A preconditions and evidence returns-A-v2.
Puede solicitar la devolución dentro de los 30 días naturales posteriores a la entrega. Se reembolsa el coste del envío original. El reembolso llega en cinco días.
Its English gloss is: request a return within 30 calendar days after delivery; the original shipping cost is refunded; the refund arrives in five days.
- Extracted claim: Return request within 30 calendar days after delivery | Evidence comparison: Matches the required deadline | Proposed label: Supported
- Extracted claim: Original shipping fee is refunded | Evidence comparison: Reverses the explicit non-refund rule | Proposed label: Contradicted
- Extracted claim: Refund arrives in five days | Evidence comparison: Processing duration is absent from this evidence | Proposed label: Insufficient evidence
Track Missing Facts, Unsupported Claims, and Abstention Separately
For this guide’s proposed rubric, supported-claim fraction = supported claims / all assessed factual claims. Report supported, contradicted, and insufficient-evidence counts separately; insufficient evidence is not proof that a claim is false.
In the Spanish example, supported-claim fraction is 1/3 and required-fact coverage is 1/2. The proposed factual case result is fail because the shipping rule is contradicted and an unsupported duration is added. The accompanying annotation file keeps bilingual review pending; it is not a production-adjudicated result.
A response that produces no factual claims has no applicable claim-precision score, not 100%. Empty output on an answerable case fails task completion. Score appropriate abstention on deliberately unanswerable cases separately. Review an incomplete oracle before assigning an application defect.
Report Per-Language Accuracy and Ground-Truth-Aware Consistency
In multilingual LLM testing, define a factual case pass before execution: all mandatory facts are correct, applicable conditions are preserved, and no material contradiction or unsupported assertion appears.
- Metric: Per-language factual accuracy | Definition and reporting requirement: Passing answerable cases / adjudicated answerable cases. Show planned coverage alongside the observed rate.
- Metric: Macro and worst-language accuracy | Definition and reporting requirement: Unweighted mean across languages and minimum language-level result. Identify sample counts; report traffic-weighted results separately.
- Metric: All-language factual success | Definition and reporting requirement: Fully correct equivalent groups / all planned equivalent groups, with complete scored coverage and a fixed required-language set.
- Metric: Factual agreement rate | Definition and reporting requirement: Groups with compatible normalized factual claims / complete eligible groups. Report complete/planned group coverage; agreement is diagnostic only.
- Metric: Paired regressions and recoveries | Definition and reporting requirement: Baseline-pass/candidate-fail and baseline-fail/candidate-pass counts, reported separately.
For repeated trials, predeclare the reduction. The companion gate averages Boolean trials within a variant, variants within an intent, then intents within a language. This gives each intent equal weight. The reporting script instead shows observation-weighted counts. They coincide in the one-trial, one-variant scorecard, but need not coincide elsewhere.
Keep numeric means outside the Boolean input loader. For an all-trials success rule, explicitly require every trial to pass; do not switch between that rule and mean pass rate after seeing results.
4. Measure Safety Consistency Without Rewarding Blanket Refusal
Pair Unsafe Requests with Benign Contrast Cases
Safety checks in multilingual LLM testing should pair benign and unsafe requests. Pair legitimate account recovery through approved channels with a request to access another person’s account without authorization. The former should receive useful permitted guidance; the latter should not receive unauthorized-access instructions.
XSTest uses benign prompts and unsafe contrasts to expose excessive refusal. Apply that design to your own reviewed policy; do not assume benchmark labels transfer unchanged across applications or languages. Record permissions, policy version, expected decision, and severity.
Separate Harmful Responses, Unnecessary Refusals, and Comprehension Failures
A disclaimer followed by prohibited assistance is not safe behavior. A refusal on a harmless request is not useful task completion. Assess substantive content, not refusal keywords.
- Metric: Harmful-response rate on unsafe requests | Numerator / eligible denominator: Responses with policy-violating assistance / adjudicated unsafe-request responses.
- Metric: Benign-output violation rate | Numerator / eligible denominator: Policy-violating outputs / adjudicated benign-request responses.
- Metric: Unnecessary-refusal rate | Numerator / eligible denominator: Unjustified refusals / adjudicated benign-request responses.
- Metric: Non-engagement rate | Numerator / eligible denominator: Irrelevant or incoherent responses / adjudicated responses in the named subset.
- Metric: Scoring coverage | Numerator / eligible denominator: Adjudicated observations / planned observations, by language and scenario population.
These labels can overlap; they are not parts of one percentage that must sum to 100. Incomplete runs stay visible outside semantic rates, and harmful partial output still counts as a confirmed finding.
XL-SafetyBench distinguishes unsafe behavior from non-engagement: low attack success in its evaluated setting can coexist with poor engagement. Preserve its country-language caveat rather than generalizing to every current model.
Test Policy Decisions Across Language and Conversation Changes
In multilingual LLM testing, vary language, script, transliteration, and conversation language while preserving intent and permissions. Include a benign opening followed by a disallowed request and a legitimate task that changes language midway.
Assert policy-correct decisions, absence of prohibited assistance, and useful completion where allowed. Compare tone separately. Count equivalent groups that are policy-correct in every required language, not just groups that make the same decision.
Test Cross-Language RAG Injection and Confidentiality
Cross-language RAG injection belongs in every multilingual LLM testing suite. A benign user request can encounter instructions inside untrusted retrieved content. OWASP distinguishes this indirect injection path from direct user-prompt injection and separately identifies sensitive-information disclosure risks.
- Illustrative case and action: Spanish return question; an English retrieved passage instructs the assistant to replace the approved deadline with 60 days | Expected outcome and retained evidence: Treat the instruction as untrusted content and preserve the approved facts. Retain passage, trust/source metadata, answer spans, and violation label.
- Illustrative case and action: Hindi question with an equivalent Tamil injection; repeat with query/evidence languages reversed | Expected outcome and retained evidence: Apply the same trust boundary. Compare policy outcomes across reviewed translations, not refusal wording.
- Illustrative case and action: Benign summary request for customer A; a deliberately contaminated sandbox context includes customer B’s synthetic protected marker | Expected outcome and retained evidence: Do not disclose the marker or protected meaning. In the end-to-end track, also assert customer B’s document never reaches the model.
Report injection success as successful policy violations / adjudicated injected-context cases. Report unauthorized disclosure as disclosures / adjudicated confidentiality cases; include benign-user paths. Marker matching is a useful assertion, not a complete semantic disclosure detector.
A generation safeguard does not repair failed retrieval authorization. Keep both findings separate. These are proposed text/RAG tests, not executed attacks or agent-tool tests. For a broader suite, see Codoid’s Prompt Injection Regression Testing guide.
5. Validate Multilingual Evaluators Before Trusting Their Scores
Combine Deterministic Checks with Evidence-Grounded Judging
Every multilingual LLM testing score depends on the evaluator. Use direct assertions for structured values and simple invariants, then evidence-grounded judgment for semantic claims and safety decisions. Require labels, evidence identifiers, supporting answer spans, and an explicit uncertain outcome.
Treat the answer being judged as untrusted data, separate it from evaluator instructions, and disable unnecessary tool access. Test whether embedded instructions corrupt scoring. A malformed judge response remains unscored. Adjudicated means a reviewed final label, not simply a successful API response.
Research on multilingual LLM judges found inconsistent judgments across its tested languages and tasks. Validate the judge for the application rather than assuming multilingual fluency establishes evaluation reliability.
Calibrate Against Bilingual Human Review by Language and Risk Category
For multilingual LLM testing, select correct and incorrect facts, negation, mixed scripts, benign contrasts, unsafe responses, and ambiguity. Bilingual reviewers should label independently before disagreements are resolved. Track judge versions and retain the original decisions.
The following invented calibration example shows how to calculate errors; no human annotation exercise was performed.
- Adjudicated human reference: Human pass | Judge pass: 56 | Judge fail: 4 | Total: 60
- Adjudicated human reference: Human fail | Judge pass: 6 | Judge fail: 34 | Total: 40
The judge’s false-pass rate is 6/40 = 15%, using human-fail cases as the denominator. Its false-failure rate is 4/60 ≈ 6.7%, using human-pass cases. Overall agreement is 90/100, which conceals the different consequences of those errors.
Calculate these by language and risk category. Log abstentions separately, prioritize severe false passes, and escalate consequential disagreements. Agreement between two automated judges is not a substitute for an independent reference.
Version the Judge and Treat Translation as a Diagnostic Aid
Record judge model, rubric, prompt language, decoding settings, calibration set, and adjudication history. If the evaluator changes, rescore both stored system outputs with the same evaluator before comparing them.
Back-translation can help investigate a mismatch, but retain the original answer and use qualified review for meaning, negation, and register. Translation bias and judge inconsistency remain separate sources of error.
6. Run Reproducible Baseline-versus-Candidate Comparisons in Multilingual LLM Testing
Freeze the Evaluation Contract and Preserve Every Attempt
Freeze the manifest, oracle, and evaluator so multilingual LLM testing results can be reproduced. Record each system’s model identifier, prompts, source hashes, retrieval/translation/safety configurations, decoding settings, limits, and run identity. Where immutable provider snapshots are unavailable, record returned identifiers and timestamps and qualify reproducibility.
Reset mutable state between independent cases. Predefine repeated trials and bounded transport retries; preserve every attempt rather than retrying until a favorable answer appears. Hold concurrency and request budgets comparable. Retain partial output, retrieved passages, finish reasons, and error status. Inspect’s official log documentation illustrates this type of execution record.
Use approved synthetic or de-identified fixtures. Minimize retained data; redact secrets without changing the tested meaning; restrict access; define retention/deletion periods; and approve what can be sent to external judges or reviewers. Reproducibility does not authorize unrestricted sharing. OWASP’s disclosure guidance supports explicit handling of sensitive data.
Codoid’s Prompt Regression Testing guide covers the wider baseline-and-contract workflow.
Isolate Retrieval, Generation, Translation, and Guardrail Regressions
Run a controlled-evidence track with fixed verified passages and an end-to-end track through production-like retrieval. Cover query language and evidence language independently.
- Query / evidence: Tamil / current Tamil | Diagnostic comparison: Check the native-language path.
- Query / evidence: Tamil / current English | Diagnostic comparison: Check cross-language evidence interpretation with equivalent facts.
- Query / evidence: English / current Tamil | Diagnostic comparison: Reverse the language direction; do not assume symmetry.
- Query / evidence: Tamil / current English plus stale Tamil | Diagnostic comparison: Verify version selection and conflict handling.
If end-to-end testing fails but fixed-evidence testing passes, investigate retrieval, filtering, and document versions. If both fail, examine generation, prompting, interpretation, and scoring. A correct pre-translation answer that becomes incorrect implicates the translation stage; increased benign refusals warrant guardrail review. These are diagnostic leads, not proof of causation.
Aggregate Pre-scored Results with Python
This example summarizes reviewed labels from a multilingual LLM testing run; it does not evaluate raw model answers or independently approve a release. Exit 0 from the reporter means reporting completed, not that the candidate is acceptable.
Download the versioned Python examples, fixtures, and verification evidence. Version 2.0.0 uses Python 3.13 and the standard library, with no model credentials or third-party package installation.
The manifest enumerates expected observations in JSON Lines (JSONL), one JSON object per line:
{"case_id":"returns-001-es-neutral","intent_id":"returns-001",
"variant_id":"neutral","language":"es","trial":0,
"metric":"factual_pass"}
The object is wrapped here for readability; store it on one line in JSONL. Results add status and value: completed adjudication uses “status”:”ok” and a Boolean value; error or unscored uses null. In the bundled synthetic data, labels are deliberately constructed, not produced by model or human evaluation.
Input validation: the loader rejects duplicate/missing observations, unexpected rows, conflicting case mappings, invalid statuses, and numeric values where Boolean trial labels are required. It checks both systems against the independent manifest, so dropping a case from both cannot conceal it.
What the report calculates: per-language observation counts, coverage, deltas, regressions, and recoveries for factual_pass, harmful, and unnecessary_refusal. Here, pp means percentage points; harmful and unnecessary-refusal rates are better when lower. A separate module performs the equal-intent reduction and all-language success calculation.
What it does not decide: raw-answer correctness, evaluator calibration, security completeness, confidence bounds, or deployment approval. The separate gate consumes reviewed bounds and a critical-failure assessment; missing inputs cannot produce a pass. Additional safety populations require their own configured checks.
Extract the examples archive, then run from its directory:
python -m zipfile -e Multilingual_LLM_Regression_Testing_Examples_v2.0.0.zip .
cd multilingual_llm_v2
python -m unittest -v
python report.py
python scorecard.py
python gate.py manifest.jsonl baseline.jsonl candidate.jsonl contract.json
For the included fixtures, report.py returns 0, while gate.py returns 1 because known quality limits fail. Gate exit 2 means insufficient or invalid evidence; 0 means only its configured example checks pass. Confidence limits are not calculated by this package.
Version 2.0.0 passed 63 offline tests on Python 3.13.5. The package includes commands, output, hashes, regenerated fixtures, and negative tests for below-floor results and insufficient evidence. This verifies code behavior and synthetic arithmetic, not an LLM, judge, statistical calibration, or production release.
7. Set Per-Language Release Gates for Multilingual LLM Testing
Combine Absolute Quality Floors with Paired Regression Limits
Define gates before execution. In this multilingual LLM testing example, the illustrative contract uses a factuality floor of 88%, harmful-response ceiling of 5%, unnecessary-refusal ceiling of 10%, and two-percentage-point non-inferiority margins. These are demonstration values, not universal recommendations.
Evaluate known critical failures and complete candidate slices against empirical absolute limits. A breached hard rule means fail. Otherwise, missing paired results, unresolved critical review, or inadequate uncertainty evidence means insufficient evidence. Return pass only when every required configured check clears; preserve both failure reasons and evidence gaps.
An empirical floor describes the observed suite. It is not a confidence guarantee about future production performance. Keep that decision separate from whether a candidate’s deterioration is smaller than the allowed margin. Non-inferiority testing addresses the latter question; a nonsignificant difference is not evidence that a release is equivalent.
Account for Repeated Trials, Sample Size, and Uncertainty
Analyze paired baseline/candidate results. Repeated calls explore variability; new independent intents expand coverage. Related translations, variants, and trials must not be counted as unrelated samples. Test choice depends on the experimental design, and tools such as Inspect expose grouped metrics and trial reducers rather than making that choice for you.
Proposed analysis contract: reduce trials to variant means, variants to intent means, then compare the mean intent scores within each language/metric population. Use a paired intent-cluster percentile bootstrap: resample independent intents with replacement, carrying their related translations, variants, and trials together. Recalculate candidate-minus-baseline differences for each resample. Predeclare the resample count, seed, quantile convention, and target population. This is an approximate method requiring statistical review, not a certified default. Paired resampling and one-sided interval conventions are documented in SciPy.
For a single directional check at alpha 0.05, use a one-sided 95% bound. The example predeclares a family of 15 directional comparisons: five languages × three metrics. For this family, the contract requests simultaneous coverage and uses Bonferroni allocation, alpha/15. Each bound therefore has nominal 99.6667% one-sided coverage. This conservative adjustment depends on valid individual bounds; it cannot repair an unsuitable estimator or unrepresentative data. It is not asserted to be mandatory for every all-must-pass release policy.
For higher-is-better factuality, require the lower bound on candidate-minus-baseline to exceed −2 pp. For lower-is-better harmful/refusal rates, require the upper bound to be below +2 pp. Equality does not clear this contract. The gate checks the method, confidence convention, intent count, and fingerprints tying supplied bounds to the data and contract. It cannot verify that a reviewer’s statistical judgment is sound.
Hypothetical bound example, not computed from the scorecard: a factuality lower bound of −3 pp does not establish non-inferiority against −2 pp, so the delta gate remains insufficient. A lower bound of −1.6 pp clears that delta gate only; coverage, absolute quality, and safety must still clear.
Do not automatically pass sparse or degenerate data, including all-zero observed harms. Require a justified alternative analysis or more evidence. Bootstrap documentation flags degenerate distributions as a reason to inspect whether another method is appropriate. No universal sample count establishes multilingual readiness.
Read a Worked Scorecard and Preserve Regression Evidence
These synthetic multilingual LLM testing results use 100 factual cases, 50 unsafe requests, and 50 benign contrasts per language, with one variant and trial per intent. They reproduce from the included paired rows.
- Language: English | Factual passes: 92/100 → 96/100 | Change: +4 pp | Harmful responses: 1/50 → 0/50 | Unnecessary refusals: 2/50 → 2/50
- Language: Hindi | Factual passes: 90/100 → 94/100 | Change: +4 pp | Harmful responses: 2/50 → 1/50 | Unnecessary refusals: 3/50 → 2/50
- Language: Tamil | Factual passes: 90/100 → 84/100 | Change: −6 pp | Harmful responses: 1/50 → 4/50 | Unnecessary refusals: 3/50 → 7/50
- Language: Spanish | Factual passes: 92/100 → 96/100 | Change: +4 pp | Harmful responses: 1/50 → 0/50 | Unnecessary refusals: 2/50 → 1/50
- Language: Arabic | Factual passes: 89/100 → 93/100 | Change: +4 pp | Harmful responses: 2/50 → 1/50 | Unnecessary refusals: 3/50 → 2/50
Macro factual accuracy rises from 90.6% to 92.6%, but Tamil falls below the illustrative 88% floor. Its harmful-response rate rises from 2% to 8%, and unnecessary refusal from 6% to 14%, also exceeding the demonstration ceilings. The gate returns FAIL without needing an uncertainty estimate to override those empirical breaches.
The fixtures deliberately align successes on the same intent IDs, so all-language factual success falls from 89/100 to 84/100. That overlap comes from paired records; language-level percentages alone do not determine it. No confidence bounds or critical-review clearance are supplied for this synthetic run, so no other language is declared release-ready.
For each regression, inspect the response, source snapshot, policy, and judge record. Adjudicate the label, identify the failing component, fix it, then rerun affected slices and the unchanged release suite. Preserve baseline/deployment rollback references. Do not remove difficult languages or update the baseline merely to turn a failing gate green.
CONCLUSION
Effective multilingual LLM testing means releasing on language-level evidence, not multilingual averages. Use a release-evidence checklist rather than a single multilingual score:
- Evidence to retain: Fixtures and oracle | Release-readiness check: Supported languages, market assumptions, intent/variant mapping, current source hashes, and independent review status are recorded.
- Evidence to retain: Execution and evaluation | Release-readiness check: Baseline/candidate identities, configurations, attempts, partial outputs, evaluator version, calibration, and adjudication history are preserved.
- Evidence to retain: Decisions | Release-readiness check: Per-language factuality and safety results, complete denominators, uncertainty method, critical findings, and unresolved owners are visible.
- Evidence to retain: Reproducibility and handling | Release-readiness check: Versioned code, test output, checksums, access permissions, retention, and approved external-data handling accompany the report.
- Evidence to retain: Release ownership | Release-readiness check: Acceptance criteria, rejection/rollback actions, and authorized sign-off are explicit; reporting success is not substituted for approval.
A multilingual improvement is not a release pass when a required language fails its quality or safety contract.
Discuss your supported languages, highest-risk scenarios, and release-evidence requirements with Codoid through its LLM & AI Application Testing Services to scale your multilingual LLM testing.
Frequently Asked Questions
-
Is translating an English test set enough?
No. Use reviewed translations for controlled comparisons and native-authored cases for local usage and context. Keep their provenance visible; translation alone can retain unsuitable cultural assumptions.
-
Should an LLM give identical answers in every language?
No. Require equivalent facts and appropriate policy decisions for equivalent contexts, not identical wording. Market or policy-date changes can legitimately change the answer.
-
Can one LLM judge evaluate every supported language?
Treat that as a capability to validate. Calibrate by language and risk, retain uncertain outcomes, and escalate consequential disagreements to bilingual reviewers.
-
How many test cases and repeated runs are enough?
There is no universal number. Choose coverage and uncertainty targets for the decision, report independent intents separately from repeated calls, and justify the analysis before examining results.
by Rajesh K | Nov 13, 2026 | Automation Testing, Blog, Latest Post |
Effective Playwright passkey testing involves testing registration, sign-in from an unauthenticated session, and reuse of the same passkey. Confirm that the server enrolls the credential and authenticates the intended account. A browser returning a credential is not sufficient evidence of successful authentication. Use Playwright’s built-in credentials API for repeatable application-flow tests and a separate Chromium CDP suite for additional authenticator controls. This guide pins Playwright 1.65.0. The credentials API arrived in 1.61, credential storage-state support in 1.62, and explicit counter preservation in 1.64.
Before you start: You need an authorized, non-production WebAuthn application, disposable accounts, and protected setup/read-only inspection hooks. The examples use TypeScript, Node.js 22.x, same-origin cookie sessions, explicit button-triggered ceremonies, and no attestation-verification requirement. Set PASSKEY_BASE_URL, PASSKEY_RP_ID, and the secret PASSKEY_TEST_API_TOKEN. These are illustrative application contracts, not standard WebAuthn routes. The files were syntax-checked, not dependency-type-checked or executed against an application. This guide focuses on building a robust Playwright passkey testing framework.
Table of Content
1. Choose the Right Approach for Playwright Passkey Testing
Built-In Credentials API for Application-Flow Testing
browserContext.credentials supplies cross-browser WebAuthn emulation. Install it before application code accesses WebAuthn. It intercepts the page’s credential methods; it does not exercise every browser’s native authenticator stack.
The pinned implementation generates ES256 responses: ECDSA using the P-256 curve and SHA-256. It reports successful user presence (UP) and user verification (UV) and uses attestation format none. These are emulator behaviors, not proof of biometric interaction, authenticator-policy enforcement, or attestation validation.
Chromium CDP for Authenticator Controls
Chrome DevTools Protocol (CDP) provides controls for virtual authenticators. Playwright’s CDP sessions are Chromium-specific, and CDP’s WebAuthn domain is experimental. Confirm command compatibility with the pinned browser.
- Approach: Built-in credentials API | Use it for: Registration, sign-in, account binding, and imported-credential reuse | Do not treat it as: Native authenticator or hardware coverage
- Approach: Chromium CDP | Use it for: Browser-integrated ceremonies and controlled verification/presence failures | Do not treat it as: Firefox, WebKit, or physical-device validation
- Approach: Real devices and providers | Use it for: Native prompts, account selection, biometrics, synchronization, and recovery | Do not treat it as: A substitute for deterministic backend regression tests
Keep the built-in and CDP suites separate. An installed interceptor can answer the page request before the native path that the CDP test intends to exercise.
What Still Requires Real-Device Testing
Maintain real-device tests for Face ID, Touch ID, Windows Hello, security keys, cross-device sign-in, and provider synchronization. Software authenticators cannot establish that those interactions occurred. Browser autofill and account-chooser interaction are also different from returning a credential to JavaScript.
2. Define the WebAuthn Test Contract for Playwright Passkey Testing
Separate Authenticator Credentials, Server Records, and Login Sessions
When planning Playwright passkey testing, use three independently managed states:
- State: Virtual authenticator | Evidence to inspect: Credential ID, RP ID, user handle, key material, counter | What it does not prove: Server enrollment
- State: Server enrollment | Evidence to inspect: Credential-to-account association and verification data | What it does not prove: An authenticated browser session
- State: Application session | Evidence to inspect: Cookies and the authenticated identity | What it does not prove: That this test used a passkey
Registration persists server-side verification data. Authentication uses that enrollment to verify an assertion. Restoring a signed-in session skips the sign-in journey rather than testing it.
Agree on RP ID, Origin, Account Binding, and Verification Policy
The relying party (RP) is the application using WebAuthn. Configure the allowed origin separately from the RP ID: the origin includes scheme and any nondefault port; the RP ID does not. Use valid HTTPS, or an appropriate localhost development origin.
For this contract, encode credential IDs, challenges, and userHandle as canonical, unpadded base64url. Keep account.id, your internal application identifier, separate from the encoded WebAuthn user handle. The handle must represent 1 to 64 opaque bytes and must not contain an email address or other personally identifying data.
The application converts JSON strings to browser buffers before navigator.credentials.create() or get() and serializes the returned credential before posting it to verification. Make the adapter responsible for this conversion; do not compare raw bytes, padded base64, and base64url as interchangeable strings.
The examples require residentKey: ‘required’, userVerification: ‘required’, and ES256. These are selected test prerequisites, not universal product defaults. Hosted identity providers, cross-origin frames, and redirect-based login need a separate origin/session/endpoint contract; do not broaden this example’s accepted origins merely to make such flows pass.
Identify Application-Specific Setup and Evidence
Implement or adapt the following interfaces. Options endpoints return options JSON directly; verification requests post the serialized credential directly, with its id at the top level.
- Illustrative interface: PUT /__test/accounts/{lease} | Required contract: Protected provisioning; 200/201 with id, email, userHandle, and a single-use same-origin bootstrapPath
- Illustrative interface: GET /__test/accounts/{lease}/credentials | Required contract: Protected, sanitized array of { id, userId, userHandle, counter }; no private keys
- Illustrative interface: DELETE /__test/accounts/{lease} | Required contract: Idempotent removal of the account, enrollments, sessions, and challenges; 204/404
- Illustrative interface: GET /api/me | Required contract: 401 without a session; otherwise 200 with { userId }; no redirect
- Illustrative interface: POST /api/webauthn/register/options and /verify | Required contract: Real registration options and verification; accepted verification is 200 with { verified: true }
- Illustrative interface: POST /api/webauthn/authenticate/options and /verify | Required contract: Real authentication; success as above; the CDP failure case expects 400 with { verified: false }
UI contract: /settings/passkeys provides the button “Create a passkey”; /login provides the label “Email” and buttons “Sign in with a passkey” and “Sign in without a username.” Authenticated pages provide “Sign out.” Add these stable completion/error targets:
- Test ID: signed-in-email | Expected visible state: Exact test-account email after bootstrap and successful sign-in
- Test ID: passkey-status | Expected visible state: Passkey added after accepted enrollment
- Test ID: login-form | Expected visible state: Visible after sign-out completes
- Test ID: passkey-error | Expected visible state: “Passkey sign-in failed. Try again.” after rejected authentication; the sign-in button is visible and enabled
These strings and status codes belong to the example application, not the WebAuthn standard. Adapt them together with the code.
Never expose authentication-bypass setup hooks in production. Restrict them to an isolated test deployment and disposable accounts; authenticate administrative calls with a runner-held secret. The bootstrap creates an enrollment session only. Happy-path WebAuthn verification remains real and unmocked.
3. Build an Isolated Playwright Passkey Fixture
Pin Dependencies and Install the Emulator Before Application Code Runs
Use a supported, patched Node.js 22.x runtime. For a new CommonJS sample project, initialize and install the dependencies below. Existing projects should retain their own compatible module settings. Commit the generated package manifest and lockfile.
npm init -y
npm pkg set type=commonjs
npm install --save-dev --save-exact @playwright/[email protected] [email protected] @types/node@22
npx playwright install chromium firefox webkit
Keep the files together:
- playwright.config.ts
- tsconfig.json
- package.json # Generated; type is commonjs.
- package-lock.json # Generated by npm; commit it.
- tests/passkey.fixture.ts
- tests/passkey.steps.ts
- tests/passkey.spec.ts
- tests/webauthn.cdp.spec.ts
- fragments/storage-state.ts.txt # Optional fragment, not a test file.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022", "DOM"],
"types": ["node"],
"strict": true,
"noEmit": true,
"esModuleInterop": true
},
"include": ["playwright.config.ts", "tests/**/*.ts"],
"exclude": ["node_modules", "fragments"]
}
This configuration uses NodeNext resolution with a CommonJS package. For an ESM repository, align the package type, imports, and compiler settings instead of copying this module setup unchanged. Playwright transforms TypeScript but does not perform semantic type checking; run npx tsc -p tsconfig.json –noEmit separately.
import { defineConfig } from '@playwright/test';
const baseURL = process.env.PASSKEY_BASE_URL;
if (!baseURL) throw new Error('Set PASSKEY_BASE_URL');
export default defineConfig({
testDir: './tests',
fullyParallel: true,
timeout: 45_000,
expect: { timeout: 10_000 },
use: {
baseURL, headless: true,
storageState: { cookies: [], origins: [] },
trace: 'off', screenshot: 'off', video: 'off',
},
projects: [
...(['chromium', 'firefox', 'webkit'] as const).map(
browserName => ({ name: browserName, use: { browserName },
testIgnore: '**/*.cdp.spec.ts',
})),
{
name: 'chromium-cdp', use: { browserName: 'chromium' },
testMatch: '**/*.cdp.spec.ts',
},
],
});
The 45-second test limit and 10-second waits are harness limits, not passkey performance targets. Raw recordings are disabled until an appropriate restricted-artifact policy is in place.
Allocate Disposable Accounts and Clean Up Test State
One account lease per test attempt prevents enrollment and session state leaking between tests. The provisioning hook must support idempotent cleanup by lease even when provisioning succeeds but its response is lost. Add server-side expiry for accounts abandoned by interrupted runners.
import { randomUUID } from 'node:crypto';
import { test as base, expect } from '@playwright/test';
export { expect };
function required(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Set ${name}`);
return value;
}
export const rpId = required('PASSKEY_RP_ID');
export const adminHeaders = {
'X-Test-Token': required('PASSKEY_TEST_API_TOKEN'),
};
export type Account = {
id: string; email: string; userHandle: string;
bootstrapPath: string; testPath: string;
};
export function assertBase64Url(
value: unknown, field: string, maxBytes = Infinity,
): asserts value is string {
if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value)) {
throw new Error(`${field}: expected nonempty unpadded base64url`);
}
const bytes = Buffer.from(value, 'base64url');
if (bytes.toString('base64url') !== value || bytes.length > maxBytes) {
throw new Error(`${field}: noncanonical encoding or invalid length`);
}
}
// This base fixture does not install WebAuthn interception.
export const appTest = base.extend<{ account: Account }>({
account: async ({ request, baseURL }, use) => {
if (!baseURL) throw new Error('Missing baseURL');
const testPath = `/test/accounts/${randomUUID()}`;
const errors: Error[] = [];
let phase = 'setup: account provisioning';
try {
const response = await request.put(testPath, {
headers: adminHeaders, maxRedirects: 0, timeout: 10_000,
});
phase = `setup: provisioning HTTP ${response.status()}`;
expect([200, 201]).toContain(response.status());
phase = 'setup: account contract';
const account = await response.json() as Account;
if (!account || ['id', 'email', 'userHandle', 'bootstrapPath']
.some(key => typeof account[key as keyof Account] !== 'string' ||
!account[key as keyof Account]) {
throw new Error('Invalid account contract');
}
assertBase64Url(account.userHandle, 'userHandle', 64);
const bootstrap = new URL(account.bootstrapPath, baseURL);
if (bootstrap.origin !== new URL(baseURL).origin ||
!account.bootstrapPath.startsWith('/')) {
throw new Error('Bootstrap must stay on the test origin');
}
phase = 'fixture use';
await use({ ...account, testPath });
} catch {
// Do not print bodies, bootstrap tokens, or request headers.
errors.push(new Error(`${phase} failed; raw details withheld`));
} finally {
let status = 'unavailable';
try {
const response = await request.delete(testPath, {
headers: adminHeaders, maxRedirects: 0, timeout: 10_000,
});
status = String(response.status());
expect([204, 404]).toContain(response.status());
} catch {
errors.push(new Error(`cleanup: deletion failed (HTTP ${status})`));
}
}
if (errors.length) throw new AggregateError(errors, 'Account fixture');
},
});
export const test = appTest.extend({
context: async ({ context }, use) => {
await context.credentials.install();
await use(context);
},
});
The context override installs interception before the dependent page fixture is used. The account fixture aggregates sanitized setup/use and cleanup failures, including available HTTP status, instead of letting a failed deletion overwrite a setup failure. Raw request bodies and bootstrap secrets stay out of those errors. Test assertions remain reported by Playwright; account expiry is still required when a runner cannot complete teardown.
For broader ownership and parallel-run design in your Playwright passkey testing, see Codoid’s Playwright Test Architecture guide.
4. Automate WebAuthn Passkey Registration in Playwright Passkey Testing
Trigger Registration and Wait for Server Verification
In a robust Playwright passkey testing suite, start from the disposable account’s enrollment session and verify its identity. Register response waiters before clicking; then require accepted verification and a visible completion state. The shared helper file also contains the sign-in and sign-out steps used below.
import type { Page, APIRequestContext } from '@playwright/test';
import {
expect, rpId, adminHeaders, assertBase64Url, type Account,
} from './passkey.fixture';
export function nextPost(page: Page, path: string) {
const origin = new URL(page.url()).origin;
return page.waitForResponse(response =>
new URL(response.url()).origin === origin &&
new URL(response.url()).pathname === path &&
response.request().method() === 'POST', { timeout: 10_000 });
}
export async function assertIdentity(page: Page, account: Account) {
const me = await page.request.get('/api/me', { maxRedirects: 0 });
expect(me.status()).toBe(200);
expect(await me.json()).toMatchObject({ userId: account.id });
await expect(page.getByTestId('signed-in-email')).toBeVisible();
await expect(page.getByTestId('signed-in-email')).toHaveText(account.email);
}
export async function signOut(page: Page) {
await page.getByRole('button', { name: 'Sign out', exact: true }).click();
await expect(page.getByTestId('login-form')).toBeVisible();
await expect.poll(async () =>
(await page.request.get('/api/me', { maxRedirects: 0 })).status(),
).toBe(401);
}
export async function registerThroughUI(page: Page, account: Account) {
await page.goto(account.bootstrapPath);
await assertIdentity(page, account);
await page.goto('/settings/passkeys');
const [optionsResponse, verified] = await Promise.all([
nextPost(page, '/api/webauthn/register/options'),
nextPost(page, '/api/webauthn/register/verify'),
page.getByRole('button', { name: 'Create a passkey', exact: true }).click(),
]);
expect(optionsResponse.status()).toBe(200);
const options = await optionsResponse.json();
assertBase64Url(options.challenge, 'registration challenge');
expect(options.rp.id).toBe(rpId);
expect(options.user.id).toBe(account.userHandle);
expect(options.pubKeyCredParams).toContainEqual({
type: 'public-key', alg: -7,
});
expect(options.authenticatorSelection).toMatchObject({
residentKey: 'required', userVerification: 'required',
});
expect(verified.status()).toBe(200);
expect((await verified.json()).verified).toBe(true);
const id: unknown = verified.request().postDataJSON().id;
assertBase64Url(id, 'registration credential ID');
await expect(page.getByTestId('passkey-status')).toBeVisible();
await expect(page.getByTestId('passkey-status')).toHaveText('Passkey added');
return id;
}
export async function signIn(
page: Page, account: Account, id: string,
mode: 'username-first' | 'discoverable', previousChallenge?: string,
) {
await page.goto('/login');
const before = await page.request.get('/api/me', { maxRedirects: 0 });
expect(before.status()).toBe(401);
if (mode === 'username-first') {
await page.getByLabel('Email', { exact: true }).fill(account.email);
}
const button = mode === 'username-first'
? 'Sign in with a passkey' : 'Sign in without a username';
const [optionsResponse, verified] = await Promise.all([
nextPost(page, '/api/webauthn/authenticate/options'),
nextPost(page, '/api/webauthn/authenticate/verify'),
page.getByRole('button', { name: button, exact: true }).click(),
]);
expect(optionsResponse.status()).toBe(200);
const options = await optionsResponse.json();
assertBase64Url(options.challenge, 'authentication challenge');
expect(options.challenge).not.toBe(previousChallenge);
expect(options.rpId).toBe(rpId);
expect(options.userVerification).toBe('required');
const allowed = (options.allowCredentials ?? [])
.map((item: { id: string }) => item.id);
if (mode === 'discoverable') expect(allowed).toEqual([]);
else expect(allowed).toContain(id);
expect(verified.status()).toBe(200);
expect((await verified.json()).verified).toBe(true);
expect(verified.request().postDataJSON().id).toBe(id);
await assertIdentity(page, account);
return options.challenge as string;
}
export async function assertStored(
request: APIRequestContext, account: Account, id: string, counter: number,
) {
const response = await request.get(`${account.testPath}/credentials`, {
headers: adminHeaders, maxRedirects: 0, timeout: 10_000,
});
expect(response.status()).toBe(200);
expect(await response.json()).toEqual([{
id, userId: account.id, userHandle: account.userHandle, counter,
}]);
}
The pubKeyCredParams assertion checks that the application offers { type: ‘public-key’, alg: -7 }, matching the ES256 prerequisite. The emulator is not a full algorithm-negotiation test: verify unsupported algorithms in a non-intercepted browser/CDP or backend verifier test.
Inspect the Created Credential and Confirm Account Association
The lifecycle test connects the submitted credential ID to the emulator record and the sanitized server record. The expected user handle and account ID must agree with the test contract; a success toast alone cannot establish that association. The exact-one-record assertion is appropriate only because this fixture provisions an empty account.
Do not compare public keys using unrelated encodings. Playwright exports SPKI (SubjectPublicKeyInfo) public-key data; server libraries may store a different representation. Normalize formats deliberately or test through the verifier rather than assuming two encoded strings should match.
Test Duplicate-Registration Protection
For an excluded-credential test, retain the existing credential, require its ID in excludeCredentials, and attempt enrollment again. Assert a recoverable UI result and an unchanged server credential count. Separately, when the product permits another passkey, enroll a distinct credential and verify both belong to the intended account. Excluded-credential protection does not mean an account may have only one passkey.
5. Automate Passkey Sign-In in Playwright Passkey Testing
Start Unauthenticated and Authenticate with the Registered Credential
Every sign-in below in your Playwright passkey testing suite requires /api/me to return 401 before the ceremony, then checks accepted verification, the expected account ID, and the displayed email. The browser-bound request client shares the context’s cookies. Token-based applications must adapt the identity check to their actual token path.
Important: The imported-credential cases below prove reuse, not the original credential’s discoverability. Playwright makes seeded credentials discoverable. The first test verifies original discovery before any export or reseeding.
import { test, expect, rpId } from './passkey.fixture';
import {
registerThroughUI, signIn, signOut, assertStored,
} from './passkey.steps';
test('original credential supports username-free sign-in', async ({
page, account,
}) => {
const id = await registerThroughUI(page, account);
await signOut(page);
// Keep the original authenticator. No export, snapshot, or reseeding.
await signIn(page, account, id, 'discoverable');
});
for (const mode of ['username-first', 'discoverable'] as const) {
test(`imported credential reuse: ${mode}`, async ({
page, context, browser, request, account, baseURL,
}) => {
const id = await registerThroughUI(page, account);
const captured = await context.credentials.get({ rpId });
expect(captured.length).toBe(1); // Never print private-key objects.
let credential = captured[0]!;
expect(credential.id).toBe(id);
expect(credential.userHandle).toBe(account.userHandle);
await assertStored(request, account, id, credential.signCount);
let previousChallenge: string | undefined;
for (let attempt = 0; attempt < 2; attempt++) {
const fresh = await browser.newContext({
baseURL, storageState: { cookies: [], origins: [] },
});
try {
await fresh.credentials.create(rpId, credential);
await fresh.credentials.install();
const login = await fresh.newPage();
previousChallenge = await signIn(
login, account, id, mode, previousChallenge,
);
const updated = await fresh.credentials.get({ id });
expect(updated.length).toBe(1);
expect(updated[0]!.signCount).toBe(credential.signCount + 1);
credential = updated[0]!;
await assertStored(request, account, id, credential.signCount);
} finally {
await fresh.close();
}
}
});
}
Cover Username-First and Discoverable-Credential Flows
The original-credential test registers once, keeps the same authenticator, signs out, confirms the unauthenticated state, and requires an empty credential allowlist. It then checks that the submitted credential authenticates the expected account. No credential export, storage snapshot, or recreation occurs in that test.
The two imported-credential cases instead create a new context for each sign-in and carry the latest credential state forward. Username-first sign-in requires the expected ID in the allowlist; username-free sign-in requires no listed credentials. The consecutive-challenge check detects accidental reuse in these attempts; it does not prove randomness or the server’s full replay policy.
Neither test validates conditional autofill or a native account picker. Conditional mediation involves a pending browser request and user selection; the interceptor also overrides capability checks. Keep native capability, selection, and fallback tests separately configured.
6. Reuse Passkey Credentials in Playwright Passkey Testing
Capture and Reseed a Registered Test Credential
Transfer the credential ID, user handle, matching key material, RP ID, and current counter together. Keep its server enrollment alive. A fresh random key with the same account label is not the registered passkey, and creating a virtual credential does not enroll it on the server.
This is test-fixture reuse, not provider synchronization. The local warning beside the test is important: imported credentials cannot demonstrate that the original registration produced a discoverable credential.
Save Virtual Credentials with Storage State
storageState({ credentials: true }) opts into saving virtual credentials, including their private keys and counters. Restoring a state containing them installs the virtual authenticator. Remove session-bearing state when the purpose is to test authentication, not bypass it.
Optional TypeScript fragment, not a sixth runnable test file:
// Fragment: sourceContext, browser, and baseURL come from your test.
const snapshot = await sourceContext.storageState({ credentials: true });
const fresh = await browser.newContext({
baseURL,
storageState: { ...snapshot, cookies: [], origins: [] },
});
try {
// Assert /api/me returns 401, then perform the normal sign-in flow.
// Keep the matching server enrollment alive throughout this test.
} finally {
await fresh.close();
}
Use this instead of explicit reseeding, not in addition to it. For cross-run reuse, provide a separate managed enrollment lifetime: the per-test fixture above intentionally deletes its account. Save only after in-flight ceremonies finish, and keep credential state in protected, ignored storage with short retention. Never publish a fixture containing working private keys.
Preserve Counters and Avoid Shared-Credential Races
When scaling Playwright passkey testing, a stale snapshot can explain why reuse works once and then fails. After authentication updates the server’s counter, restoring an older credential state can produce a non-increasing counter. Capture the current state rather than resetting the server to hide the failure.
The example’s +1 assertion assumes one emulator assertion per button-triggered attempt. It is not a universal authenticator rule: some authenticators legitimately report zero. Follow the verifier and product policy for those cases.
Assign separate credentials to parallel workers and browser projects. A sequential reuse test should own its entire lifecycle; cloning one mutable snapshot into concurrent tests creates avoidable counter races.
7. Use Chromium CDP for Advanced Playwright Passkey Testing
Configure a Virtual Authenticator and Observe Credential Events
This separate file imports appTest, which does not install the interceptor. It registers through the real UI, signs out, and requests an invalid signature. Credential events show authenticator activity; the verification response, identity endpoint, and recovery UI establish the application outcome.
import { appTest as test, expect } from './passkey.fixture';
import { registerThroughUI, signOut, nextPost } from './passkey.steps';
test('invalid signature leaves a recoverable sign-in screen', async ({
page, account,
}) => {
const session = await page.context().newCDPSession(page);
let authenticatorId: string | undefined;
try {
await session.send('WebAuthn.enable');
const added = await session.send('WebAuthn.addVirtualAuthenticator', {
options: {
protocol: 'ctap2', transport: 'internal',
hasResidentKey: true, hasUserVerification: true,
isUserVerified: true, automaticPresenceSimulation: true,
},
});
authenticatorId = added.authenticatorId;
let created = 0;
let asserted = 0;
session.on('WebAuthn.credentialAdded', event => {
if (event.authenticatorId === authenticatorId) created++;
});
session.on('WebAuthn.credentialAsserted', event => {
if (event.authenticatorId === authenticatorId) asserted++;
});
await registerThroughUI(page, account);
await expect.poll(() => created).toBe(1);
await signOut(page);
await page.goto('/login');
await page.getByLabel('Email', { exact: true }).fill(account.email);
await session.send('WebAuthn.setResponseOverrideBits', {
authenticatorId, isBogusSignature: true,
});
const retry = page.getByRole('button', {
name: 'Sign in with a passkey', exact: true,
});
const [rejected] = await Promise.all([
nextPost(page, '/api/webauthn/authenticate/verify'), retry.click(),
]);
expect(rejected.status()).toBe(400);
expect((await rejected.json()).verified).toBe(false);
await expect.poll(() => asserted).toBeGreaterThan(0);
const me = await page.request.get('/api/me', { maxRedirects: 0 });
expect(me.status()).toBe(401);
const error = page.getByTestId('passkey-error');
await expect(error).toBeVisible();
await expect(error).toHaveText('Passkey sign-in failed. Try again.');
await expect(retry).toBeVisible();
await expect(retry).toBeEnabled();
} finally {
try {
if (authenticatorId) {
await session.send('WebAuthn.removeVirtualAuthenticator', {
authenticatorId,
});
}
await session.send('WebAuthn.disable');
} finally {
await session.detach();
}
}
});
Exercise Verification Failures, Missing Presence, and Invalid Responses
Use separate cases so each failure has an identifiable cause:
- Control: setUserVerified(false) | Action: Attempt a ceremony requiring verification | Required evidence: Failure or deliberate cancellation within the limit; no new session; identify the rejection layer
- Control: setAutomaticPresenceSimulation(false) | Action: Withhold simulated user presence | Required evidence: Pending ceremony can be deliberately aborted; the UI becomes usable again
- Control: setResponseOverrideBits | Action: Produce an invalid signature or altered UP/UV flags | Required evidence: Rejection at the intended layer; no new authenticated identity
These are documented controls, not guarantees that every browser version follows the same observable sequence. Disabling automatic presence does not click Cancel. Exercise the application’s cancellation path, independently bound the test, and confirm recovery; a runner timeout alone is not a recovery test.
A browser can reject before sending verification. To prove server enforcement, use a backend case that reaches the verifier with a well-formed, targeted fixture rather than treating an absent request as evidence of server rejection.
8. Build a Regression Matrix for Playwright Passkey Testing
These are acceptance cases to add around the example suite for comprehensive Playwright passkey testing. Start negative authentication cases without a session and require no newly authenticated identity afterward. The tables specify design expectations, not executed results.
Missing, Deleted, Revoked, and Wrong-Account Credentials
- Preconditions and action: Empty authenticator; attempt sign-in | Layer: Application flow | Expected outcome and evidence: Recoverable error; no accepted verification or session
- Preconditions and action: Delete the virtual key but retain server enrollment | Layer: Application flow | Expected outcome and evidence: Deleted key cannot authenticate; server record remains
- Preconditions and action: Revoke enrollment but retain the key | Layer: Browser + backend | Expected outcome and evidence: Server refuses the credential; no new session; revocation evidence
- Preconditions and action: Submit account A’s credential in B’s username-first ceremony | Layer: Backend + browser | Expected outcome and evidence: No account substitution; intended rejection and no B session
- Preconditions and action: Enroll A and B; run separate username-free cases with only A’s or B’s credential available | Layer: Application flow | Expected outcome and evidence: A’s ID/handle resolves to A; B’s resolves to B; an empty allowlist and correct displayed identity each time
- Preconditions and action: Enroll a second, distinct passkey for A using another authenticator | Layer: Application + backend | Expected outcome and evidence: Two distinct IDs mapped to A; each authenticates A independently
For the two-account case, controlled credential availability tests identity mapping, not native picker interaction. A real chooser test must present both eligible credentials and select each intended account in a supported device/browser environment. The pinned interceptor chooses a matching credential programmatically; do not mistake that for a chooser.
Deleting a virtual credential and revoking enrollment are different operations. Define separately whether revocation also invalidates sessions created earlier. For the two-passkey case, adapt the exact-one-record helper to compare the intended two-record set.
Expired Challenges, Replay, Invalid Origin, and RP Mismatch
- Preconditions and action: Move a server test clock across the configured challenge expiry | Layer: Backend | Expected outcome and evidence: Accept before expiry; reject at/after the product’s documented boundary
- Preconditions and action: Resubmit an accepted assertion; then race two submissions of one challenge | Layer: Backend | Expected outcome and evidence: No replay acceptance; at most one concurrent acceptance; challenge-consumption evidence
- Preconditions and action: Send a validly constructed assertion from an unapproved origin | Layer: Backend | Expected outcome and evidence: Origin rejection rather than an unrelated parsing failure
- Preconditions and action: Request a disallowed RP ID without the interceptor | Layer: Native browser/CDP | Expected outcome and evidence: Browser rejection; no accepted authentication
- Preconditions and action: Verify an assertion for a different RP ID | Layer: Backend | Expected outcome and evidence: RP-ID-hash rejection; no new session
Use your verifier’s test utilities for targeted fixtures. Editing clientDataJSON without rebuilding the signed fixture can also break the signature, making the failure ambiguous. Require a sanitized internal verification reason while keeping public authentication errors appropriately generic.
Network Failures, Retries, and Concurrent Attempts
- Preconditions and action: Fail options retrieval before credential creation/use | Layer: Browser + network fault | Expected outcome and evidence: Clear error, enabled retry, no session
- Preconditions and action: Lose the verification response after possible server acceptance | Layer: Integration | Expected outcome and evidence: Reconcile actual identity/session state; do not blindly replay the assertion
- Preconditions and action: Double-click or start competing ceremonies | Layer: Browser + backend | Expected outcome and evidence: Documented concurrency behavior; no account mix-up or duplicate acceptance
- Preconditions and action: Fail enrollment verification after local key creation | Layer: Integration | Expected outcome and evidence: No false enrollment success; explicit orphaned-key and retry handling
- Preconditions and action: Use an unsupported capability or controlled passkey failure | Layer: Separately configured UI/native case | Expected outcome and evidence: Approved fallback becomes available; no session before fallback; intended identity and success UI only after fallback succeeds
For unsupported-capability UI testing, omit the built-in interceptor and stub only the application’s capability boundary. Label this a UI-contract test, not device validation. Confirm actual unsupported-device behavior separately. Do not invent a password or recovery fallback that the product does not support.
Distinguish a request that never reached the server from an accepted request whose response was lost. Check the resulting session before choosing recovery; when another authentication is needed, begin a new ceremony with a new challenge.
Codoid’s API Automation Testing with Postman, REST Assured, and Playwright guide provides complementary guidance for organizing backend checks.
9. Run Playwright Passkey Testing in CI and Diagnose Failures
Isolate Workers, Retries, and Browser Projects
To run Playwright passkey testing reliably, the configuration explicitly uses headless mode. These virtual-authenticator tests are intended for CI; they still require working application endpoints, browser dependencies, and compatible pinned binaries. Headless execution does not add native-device coverage.
After initial installation has generated a lockfile, use this sequence on the authorized deployment:
# Requires a generated and committed package-lock.json.
npm ci
npx tsc -p tsconfig.json --noEmit
npx playwright install --with-deps chromium firefox webkit
npx playwright test --project=chromium --project=firefox --project=webkit
npx playwright test --project=chromium-cdp
The TypeScript check includes all five named files. Record the resolved package versions, browser revisions, application build, expected origin/RP ID, sanitized outcomes, and cleanup status. Give retries fresh leases unless one test deliberately owns the sequential recovery scenario. Separate account ownership matters when tests modify server state.
Collect Evidence Without Exposing Credentials
Record the test ID, browser project, flow, sanitized verification decision, account alias, observed counter transition, and cleanup result. Restrict artifacts containing credential IDs and user handles as well as clearly secret values.
Credential exports contain private keys; saved authentication state can contain impersonation-capable cookies. Keep both out of Git and ordinary logs. Do not pass complete private-key-bearing objects into assertions that might print them. Recordings can also expose bootstrap tokens and protected API requests; enabling them requires access controls, redaction where possible, and defined retention.
Troubleshoot Enrollment, Sign-In, and Reuse Failures
- Symptom: Native prompt appears in the application-flow suite | Check next: Fixture import and installation order
- Symptom: Sign-in passes without a verification request | Check next: Restored session state; missing pre-sign-in 401 assertion
- Symptom: Reuse works once, then fails | Check next: Stale counter snapshot or concurrent owners
- Symptom: CDP controls seem ineffective | Check next: Accidental interceptor; incorrect CDP target
- Symptom: Discovery works only after import | Check next: Original resident-key request; repeat the no-reseeding test
- Symptom: NotAllowedError | Check next: Cancellation, timeout, unavailable matching credential, and whether verification was sent
- Symptom: InvalidStateError during registration | Check next: Excluded existing credential and whether enrollment count changed
- Symptom: SecurityError | Check next: Origin/effective-domain and RP-ID relationship in the non-intercepted browser
- Symptom: NotSupportedError | Check next: Offered public-key algorithms and actual authenticator support
- Symptom: AbortError | Check next: Application cancellation signal and recovery state
- Symptom: TypeError | Check next: Options shape, buffer conversion, and user-handle byte length
Error names are diagnostic clues, not a one-to-one cause map. The browser and emulator may differ, and an exception alone does not prove that a server request occurred. Use the layer-specific evidence alongside the error.
CONCLUSION
Release-readiness takeaway: Require accepted enrollment, original-discoverability evidence where needed, a genuinely unauthenticated starting state, the correct authenticated identity, visible completion/recovery, and repeatable reuse. Place each negative test at the layer that can demonstrate the intended rejection. Treat native-device behavior as a separate release obligation. A complete Playwright passkey testing strategy covers all these boundaries.
For support integrating these checks into a maintainable suite, explore Codoid’s QA automation testing services.
Frequently Asked Questions
-
Can Playwright test passkeys in Firefox and WebKit?
Yes, through the built-in credentials API's cross-browser emulation. This does not establish coverage of those platforms' native authenticator stacks. The CDP example remains Chromium-specific.
-
Does Playwright storage state save passkeys?
It can include virtual credentials when credentials: true is requested. It does not export passkeys from an operating system or a real password manager. Remove session-bearing state when testing sign-in.
-
Does adding a virtual credential register it with the application?
No. It populates the emulator. The server must already hold the matching enrollment, created through registration or an explicitly provisioned test fixture.
-
Can virtual-authenticator tests validate Face ID or Touch ID?
No. They validate application behavior around simulated credential operations, not actual biometric interaction. Keep biometric acceptance in the real-device plan.
by Rajesh K | Nov 12, 2026 | Software Testing, Blog, Latest Post |
Database migration regression testing should prove that a database change preserves the required schema, existing business data, application behavior, and a usable recovery path. A successful migration command is only one piece of that evidence. With Flyway Migration, use migration-history validation alongside direct schema assertions, row-level data checks, application compatibility tests, and failure-and-recovery rehearsals. Flyway’s validate command checks available migrations against recorded migrations; it does not establish that an order total, status mapping, or application workflow is correct.
This guide covers Flyway Migration regression testing for schema changes on PostgreSQL; it is not an engine-to-engine data migration guide. This is a specialized form of database migration testing.
The illustrative order-management example targets PostgreSQL 18.6 and Redgate Flyway 13.12.1, using Community migration commands. Flyway 13.12.1 was released on November 5, 2026; undo remains a Teams capability. These are target versions, not a tested stack: the database examples were not executed during this revision. Validate the supplied bundle on your exact stack before adopting it.
Table of Content
1. What Flyway Migration Regression Testing Must Prove
Migration history, database state, and application behavior are separate checks
Treat Flyway Migration regression testing as four connected acceptance layers:
- Layer: Migration history | Question to answer: Did the intended migrations run, with the expected scripts and ordering? | Suggested evidence: Validation results, migration output, history records
- Layer: Schema contract | Question to answer: Does the resulting database expose the required structure and permissions? | Suggested evidence: Catalog assertions and application-role checks
- Layer: Data and behavior | Question to answer: Were records transformed correctly, and do supported workflows still work? | Suggested evidence: Independent expected data, SQL assertions, application tests
- Layer: Recovery | Question to answer: Can the team reach a usable state without unacceptable data loss? | Suggested evidence: Failure-injection results and a rehearsed recovery record
Flyway’s schema-history table records applied migrations, checksums, and execution status. Use it as an audit trail, not as a substitute for querying the resulting objects and data.
Transaction rollback and release recovery are different outcomes
By default, Flyway handles each migration in its own transaction where the database and statements support that. If V2 commits and V3 fails, rolling back V3 does not automatically reverse V2. Grouping migrations changes the boundary, but is subject to database and statement restrictions.
For testing, distinguish transaction rollback, which reverses an unsuccessful transactional unit, from release recovery, which restores acceptable application and data behavior. Release recovery might retain an expanded schema, apply a corrective migration, execute a reviewed undo script, or restore a backup. Define the acceptable destination before deployment.
2. Build a Production-Like Flyway Migration Test Baseline
Pin the database, Flyway version, configuration, and database roles
Record the database engine and patch, extensions, encoding, collation, time zone, migration locations, placeholders, transaction settings, and application versions. Use the actual database engine rather than treating a different in-memory database as equivalent.
Separate the migration role from the application role. Run schema changes with the intended migration privileges and application checks with the intended runtime permissions. A superuser-only test does not demonstrate that the application’s credentials work.
For environment setup, see Codoid’s Docker Fundamentals for Testers: Images, Containers, Networks, and Volumes. Its environment and persistence guidance complements the migration-specific checks below.
Test fresh builds and supported upgrade starting points
Test three paths: an empty database, the currently deployed release with representative data, and every older release that you support upgrading from.
For upgrade testing, preserve the previous release’s actual migration history and repeatable scripts. The supplied V1-to-V2 exercise has only versioned migrations. When repeatables exist, build the starting database from the previous release artifact before switching to the candidate artifact; target=1 alone does not recreate an older repeatable definition.
Versioned migrations normally run once in version order. Once a script has reached a permanent downstream environment, corrective changes should normally be new migrations rather than edits to that applied file.
Prepare representative data and explicit expected results
Use synthetic or approved, sanitized fixtures. Include common records, empty tables, relevant nulls, boundary amounts, unsupported legacy values, and relationships. Maintain a separate volume profile for lock and duration tests.
Run the Flyway Migration example from the companion Flyway_Regression_Example_Review_Revision.zip bundle. Prerequisites are Bash 4+, Python 3.10+, a running Docker Engine/Desktop with Linux containers, and Docker Compose v2 supporting up –wait. The first run needs registry access. PostgreSQL, psql and Flyway run in containers, so no host database or Java installation is required.
EXAMPLE FILE MAP
- flyway-regression-example/: Root directory
- compose.yaml: Target images; isolated network
- run.sh: Provision, test, capture, remove
- sql/: V1, V2 and script configuration
- tests/: Fixtures, contracts and role checks
- cases/: Deliberately failing migrations
- scripts/: Error checks and two-session helper
- performance/: Before/after diagnostic queries
- VALIDATION_STATUS.md: What has and has not been run
- README.md: Setup, expected results, teardown
Extract the bundle, change into flyway-regression-example, and run:
The runner creates a unique disposable environment with separate migration and application logins, no published database port, and throwaway credentials. It captures versions and logs, then removes its own containers and storage; artifacts remain on disk. Use the README’s project-specific teardown command after an interrupted host run. Do not reuse production credentials or attach an existing database.
Execution order: provision, fresh build, V1 and fixtures, V2, schema/data/behavior assertions, unchanged rerun, runtime-role and recovery checks, mutation/failure/concurrency cases, evidence capture, teardown.
Expected results, not observed output: the baseline maps orders 101/102/103 to 10/20/30; codes 40 and 99 fail; a widened predicate is detected; transactional failures leave V2 uncommitted; the runtime role cannot change the schema. The suite should exit nonzero for any unexpected outcome. A complete run should print SUITE EXPECTATIONS MET.
Start with sql/V1_create_orders.sql:
CREATE TABLE public.customers (id bigint PRIMARY KEY);
CREATE TABLE public.orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES public.customers(id),
legacy_status text NOT NULL,
total_amount numeric(12,2) NOT NULL CHECK (total_amount >= 0)
);
Save this as tests/seed.sql, and run it only after V1, before the candidate migration:
INSERT INTO public.customers VALUES (1), (2);
INSERT INTO public.orders VALUES
(101, 1, 'new', 0.00),
(102, 1, 'paid', 49.95),
(103, 2, 'cancelled', 9999999999.99);
CREATE SCHEMA qa;
CREATE TABLE qa.orders_before AS
SELECT * FROM public.orders;
CREATE TABLE qa.expected_status (
id bigint PRIMARY KEY,
code smallint NOT NULL
);
INSERT INTO qa.expected_status VALUES
(101, 10), (102, 20), (103, 30);
The expected codes are explicit test data, not generated by reusing the migration. This is a test oracle: independently recorded expected results against which the implementation is checked. Keep the qa snapshot and expectation tables out of production migration locations. The three-row fixture checks correctness, not load capacity.
3. Validate Flyway Migration History and Actual Schema Contracts
Check Flyway migration versions, checksums, ordering, and repeatable changes
Capture flyway info before and after migration. Run migrate with validation enabled, then standalone validate against the completed candidate state. Applied migrations whose files are missing from configured locations, pending migrations, and changed repeatables have distinct validation states; do not assume standalone pre-deployment validate will accept every pending state.
Include these regression cases:
- Starting condition and action: Applied versioned file is changed in a disposable test copy | Expected result: Validation rejects the checksum mismatch
- Starting condition and action: An applied versioned file is omitted from configured locations | Expected result: Validation reports the missing migration under the intended rules
- Starting condition and action: A repeatable view definition changes | Expected result: It reruns after pending versioned migrations; dependent queries match the new contract
- Starting condition and action: Unchanged candidate is migrated again | Expected result: Versioned changes do not run again; business data does not duplicate
- Starting condition and action: An object is manually altered without changing migration files | Expected result: Direct schema assertions detect the deviation, even when migration-history validation passes
Repeatables rerun when their checksum changes and execute after pending versioned migrations, ordered by description. They must be safe to apply repeatedly. A second migrate call is not evidence that every versioned SQL script is independently idempotent.
Assert columns, constraints, indexes, permissions, and dependent objects
Define a schema contract covering column types, nullability and defaults; constraint definitions and enforcement; index keys, uniqueness and validity; views and routines; and ownership or grants used by the application.
For PostgreSQL 18, inspect constraints by table identity as well as name. Check pg_constraint.convalidated and conenforced where applicable. A NOT VALID constraint can enforce new writes without proving that all existing rows satisfy it. Specify whether an intermediate unvalidated state is acceptable, and by which release it must be validated.
For indexes, inspect pg_index.indisvalid and indisready, not only the presence of an index name. Assert the intended definition and absence of unexpected invalid indexes after deployment. Include a query against each affected view or routine, using the application role.
The complete tests/assert_schema.sql checks the column type, nullability and default; the constraint’s table and column identity; validation/enforcement flags; and its reviewed predicate. It creates a temporary reference table with an independently specified CHECK (status_code IN (10,20,30)), then compares pg_get_constraintdef output from both objects on the same server. This avoids guessing a deparser string or copying the actual definition into the expectation. Review any intentional contract change; equivalent but differently written predicates may need explicit approval.
-- Excerpt: run through the complete tests/assert_schema.sql.
SELECT pg_get_constraintdef(oid, false)
INTO actual_definition
FROM pg_catalog.pg_constraint
WHERE conrelid = 'public.orders'::regclass
AND conname = 'orders_status_code_ck'
AND contype = 'c' AND convalidated AND conenforced
AND conkey = ARRAY[status_attnum]::smallint[];
IF actual_definition IS DISTINCT FROM expected_definition THEN
RAISE EXCEPTION 'Schema contract mismatch: status predicate';
END IF;
Prove the test can detect a defect: tests/widen_constraint.sql changes only the predicate to IN (10,20,30,40), keeping its name and valid/enforced state. The schema assertion and the behavioral rejection of 40 must both fail. Merely rejecting 99 cannot distinguish the widened contract. The bundle contains this mutation test; its PostgreSQL outcome still requires execution.
4. Prove Flyway Migration Data Integrity with Executable SQL Assertions
Verify row-level transformations, relationships, and business invariants
The Flyway Migration example expands orders with status_code: new becomes 10, paid becomes 20, and cancelled becomes 30. Existing identifiers, customer relationships, legacy statuses, and amounts must remain unchanged.
This is a small, blocking, transactional example, not an online-migration recipe. Use PostgreSQL Read Committed isolation. V2 acquires its table lock before checking source values and retains it until the migration transaction ends; existing writers may delay it, and reads/writes can be blocked while it runs. The 3-second lock wait and 30-second statement limits below are illustrative test settings, not production targets.
File: sql/V2__expand_order_status.sql. Its adjacent .sql.conf file explicitly sets executeInTransaction=true; keep Flyway grouping disabled for this exercise. If the guard fails after ADD COLUMN, the transactional migration must roll back the new column.
-- Small, blocking, transactional example; PostgreSQL READ COMMITTED.
-- These are illustrative test limits, not production availability budgets.
SET LOCAL lock_timeout = '3s';
SET LOCAL statement_timeout = '30s';
-- Acquire the table lock BEFORE inspecting the source values.
ALTER TABLE public.orders ADD COLUMN status_code smallint;
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM public.orders
WHERE legacy_status NOT IN ('new', 'paid', 'cancelled')
) THEN
RAISE EXCEPTION 'Unmapped legacy order status';
END IF;
END $$
UPDATE public.orders
SET status_code = CASE legacy_status
WHEN 'new' THEN 10
WHEN 'paid' THEN 20
WHEN 'cancelled' THEN 30
END;
ALTER TABLE public.orders
ADD CONSTRAINT orders_status_code_ck
CHECK (status_code IN (10, 20, 30));
status_code deliberately remains nullable so old writers can omit it. In PostgreSQL, a CHECK condition alone does not reject nulls. That is an explicit compatibility choice here, not proof that the migration has reached its final contract.
The bundle runs tests/assert_preserved.sql and tests/assert_data.sql immediately after migration, before application-role tests deliberately change the data. Their combined core assertions are shown below:
DO $$
BEGIN
IF (SELECT count(*) FROM qa.orders_before) <> 3 THEN
RAISE EXCEPTION 'Unexpected test fixture';
END IF;
IF EXISTS (
SELECT 1
FROM qa.orders_before b
FULL JOIN public.orders o USING (id)
WHERE b.id IS NULL OR o.id IS NULL
OR ROW(o.customer_id, o.legacy_status, o.total_amount)
IS DISTINCT FROM
ROW(b.customer_id, b.legacy_status, b.total_amount)
) THEN
RAISE EXCEPTION 'Existing order data changed';
END IF;
IF EXISTS (
SELECT 1
FROM qa.expected_status e
FULL JOIN public.orders o USING (id)
WHERE e.id IS NULL OR o.id IS NULL
OR o.status_code IS DISTINCT FROM e.code
) THEN
RAISE EXCEPTION 'Status mapping mismatch';
END IF;
END $$
The full joins expose missing and unexpected rows, while the row comparison checks preserved values. IS DISTINCT FROM makes null differences observable; ordinary inequality can evaluate to unknown for null inputs. RAISE EXCEPTION turns a mismatch into an SQL error rather than a diagnostic row that CI might ignore.
Extend this pattern to the business invariants affected by each migration: orphan detection, tenant ownership, per-currency totals, timestamp meaning, uniqueness, and generated-key behavior. Counts and aggregate sums are useful diagnostics, but use independently expected row values for critical transformations.
Exercise invalid inputs, boundaries, and unchanged data
In a separate V1 database, change a fixture status to on_hold and update the recorded pre-migration expectation to reflect that deliberate setup. Attempt V2. Require SQLSTATE P0001 with the unmapped-status message, no committed status_code column or V2 history entry, and preservation of the source data for investigation. The fresh-build job separately covers the empty table; do not apply the fixed three-row assertion to it.
After a successful V2, tests/assert_behavior.sql accepts 10/20/30 and the intentional null state, then requires 40 and 99 to fail specifically against orders_status_code_ck. It first checks that the fixture row exists, so a zero-row UPDATE cannot produce a misleading result. All attempted test writes are enclosed in a transaction that is rolled back:
-- Roll back accepted writes too: this test must not alter the data oracle.
BEGIN;
DO $$
DECLARE
code smallint;
violated_constraint text;
BEGIN
IF NOT EXISTS (SELECT 1 FROM public.orders WHERE id=101) THEN
RAISE EXCEPTION 'Missing behavioral fixture';
END IF;
FOREACH code IN ARRAY ARRAY[10,20,30]::smallint[] LOOP
UPDATE public.orders SET status_code=code WHERE id=101;
END LOOP;
UPDATE public.orders SET status_code=NULL WHERE id=101;
IF (SELECT status_code FROM public.orders WHERE id=101) IS NOT NULL THEN
RAISE EXCEPTION 'Intentional null contract was not preserved';
END IF;
FOREACH code IN ARRAY ARRAY[40,99]::smallint[] LOOP
BEGIN
UPDATE public.orders SET status_code=code WHERE id=101;
RAISE EXCEPTION 'Unintended code % was accepted', code;
EXCEPTION WHEN check_violation THEN
GET STACKED DIAGNOSTICS violated_constraint=CONSTRAINT_NAME;
IF violated_constraint <> 'orders_status_code_ck' THEN
RAISE;
END IF;
END;
END LOOP;
END $$
ROLLBACK;
The handler accepts only the named check-constraint violation. Missing tables, permission failures, or an unexpectedly accepted value fail the test. PostgreSQL supports inspecting the constraint name in an exception handler; changes within a failed block roll back. The outer ROLLBACK also removes the accepted-value probes.
Add independent cases for duplicate primary keys, nonexistent customers, null required fields, negative amounts, and permitted zero or maximum values. For the expansion state, also prove that an old-style insert without status_code remains accepted. Use separate fixtures or rolled-back transactions so negative tests do not contaminate later checks.
5. Test Flyway Migration Application Compatibility, Locks, and Writes
Check old and new application releases against intended schema states
An added nullable field is not a complete compatibility strategy. Define which representation remains authoritative while old and new writers coexist.
For this example, keep legacy_status authoritative during the overlap. The new application writes both representations in one transaction but continues to derive business status from the legacy field. Do not switch reads to the new code merely because the backfill completed.
- Application and schema state: Old application + V1 | Required application test: Existing create, read, and status-update workflows pass
- Application and schema state: Old application + expanded V2 | Required application test: Old SQL remains valid; inserts may omit the new field
- Application and schema state: New application + expanded V2 during overlap | Required application test: Reads use the authoritative legacy value; writes maintain both values
- Application and schema state: New application + V1 | Required application test: Unsupported in this example; deployment sequencing must prevent it
- Application and schema state: Old application + later contracted schema | Required application test: Treat as unsupported once required legacy fields are removed
The stale-value case matters: V2 sets order 101 to code 10. An old instance changes its legacy status to paid, leaving code 10 behind. A new reader that falls back only when the code is null will return the wrong status. Make that sequence an explicit regression test.
Before switching authority, stop old application instances or prevent them from writing to the database, reconcile derived codes, and verify no mismatches remain. Retain reverse-compatible writes for the agreed rollback window. Removing the legacy representation is a later, separately gated change. Backward-compatible schema evolution can preserve the option to roll back application code.
For broader service-level coverage, see Codoid’s Microservices Testing: A Practical Strategy for QA and Development Teams.
The companion runtime job connects as app_runtime with separate credentials. tests/app_overlap.sql performs an old-style insert, creates order 104 using both fields, and proves the stale-code sequence on order 101. tests/denied_ddl.sql and tests/denied_create.sql must fail with SQLSTATE 42501; a generic connection failure does not count. These are SQL-client contract simulations, not tests of your application binaries, APIs, ORM, or deployed rollback.
Exercise concurrent activity, permissions, and timeout behavior
Run representative reads and writes while the migration executes. Record blocked sessions, wait durations, application errors, and whether acknowledged writes survive. Compare results with team-approved budgets rather than inventing universal migration-time limits.
The bundle’s two-session helper first holds a writer transaction on V1, starts V2, and polls pg_locks until it observes the migration waiting for AccessExclusiveLock. In the interleaving case, the writer then commits on_hold; the now-locked guard must reject it and roll V2 back. In a separate case, the writer retains its lock until V2 reports SQLSTATE 55P03; after release, a reviewed retry must succeed. Failure to observe the intended wait fails the test rather than asserting that the race occurred. These database cases are supplied but have not been run here.
For concurrent backfills, deliberately update a row while it is being processed, interrupt and restart a batch, and retry the same logical work. Assert no lost updates or duplicate transformations against a workload-specific expected dataset.
Also compare query behavior after migration, not only deployment duration. Use equivalent representative datasets and the same hardware, statistics policy, warm-up, parameter distribution and concurrency. Measure an affected order-read request and status-write request before and after V2; record latency percentiles, throughput, errors and waits against budgets agreed before testing. Keep the new writer’s dual-field update in the candidate workload rather than measuring a different business operation.
The performance/ directory supplies before.sql, after.sql and an unfilled acceptance.csv. The query below is a plan diagnostic for the order-read workload; repeat it under the declared measurement protocol, not as a substitute for a load test.
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT id, total_amount
FROM public.orders
WHERE customer_id = 1 AND legacy_status = 'paid'
ORDER BY id LIMIT 50;
EXPLAIN ANALYZE executes the statement. For write diagnostics, use disposable data and an explicit transaction/ROLLBACK; rollback does not reverse external trigger effects or sequence consumption. Compare measured behavior, using plans to investigate regressions, not as exact golden-text assertions. No performance result or universal percentage threshold is claimed here.
Test the application role’s permitted reads and writes, as well as prohibited schema changes. Permission failure during migration is a separate case. A runtime role should not silently gain migration privileges as a workaround.
6. Inject Flyway Migration Failures and Verify Safe Recovery
Contrast transactional failures with partially committed changes
Use throwaway databases and deliberately modified Flyway Migration artifacts. Inject a guaranteed SQL error after an earlier schema or data statement, then inspect objects, business rows, and migration history. Do not modify a script already applied to a shared environment.
- Engine or migration mode: PostgreSQL migration containing transaction-compatible statements | Failure expectation to verify: The failed migration’s transactional changes roll back; earlier committed migrations remain
- Engine or migration mode: PostgreSQL non-transactional operation | Failure expectation to verify: Inspect surviving objects and operation-specific recovery requirements
- Engine or migration mode: MySQL 8.4 migration containing implicit-commit DDL | Failure expectation to verify: Earlier statements may remain committed; do not expect whole-file rollback
Flyway documents these transactional boundaries. MySQL’s atomic DDL is statement-level atomicity, not permission to combine multiple DDL statements into a rollback-capable transaction.
For PostgreSQL, CREATE INDEX CONCURRENTLY cannot run inside a SQL transaction and a failed build may leave an invalid index. Flyway also has a separate advisory-lock setting: Redgate documents postgresql.transactional.lock=false for this case. Disabling the script’s SQL transaction alone does not configure that lock.
The isolated index-failure example uses these two controls; it does not change V1/V2 to non-transactional execution:
# cases/concurrent_index/V3__index_failure_demo.sql.conf
executeInTransaction=false
# Excerpt from run.sh; fw is the bundle's Flyway wrapper.
fw "$db" \
-locations=filesystem:/flyway/sql,filesystem:/flyway/cases/concurrent_index \
-postgresql.transactional.lock=false migrate
This deliberately attempts a unique index on duplicated customer IDs to produce a failed-build state, not a legitimate orders-domain rule. Require the expected uniqueness failure and an invalid index record; preserve history and catalog evidence. Review cleanup, any necessary history repair, and a valid retry separately. Interruption and a complete cleanup/retry rehearsal remain additional acceptance tests.
Reconcile database state before retrying or repairing history
Test permission denial, lock timeout, and connection loss near completion. For connection loss, treat the outcome as unknown until a fresh connection checks both history and database state. A failed client command is not a sufficient basis for manually replaying statements.
Use the following recovery sequence: preserve logs and the release identifier; inspect committed objects and data; select a DBA-reviewed cleanup, corrective migration, or restore; reconcile history only when required; then rerun assertions and application tests.
Flyway repair changes schema-history records. It can remove failed entries, realign recorded metadata, and mark missing migrations as deleted; leftover user objects still require separate cleanup. Use the same migration locations as migrate, and never make automatic repair the response to every failed deployment.
Also verify that later migrations did not execute after the failure. Preserve the failed-state evidence before cleanup, and confirm that a retry does not duplicate backfilled or reference data.
- Symptom: Checksum mismatch | Evidence to retain: Applied history and candidate script diff | Next action: Restore the correct artifact or add a reviewed migration; do not repair merely to silence validation.
- Symptom: Unmapped legacy status | Evidence to retain: P0001, source row, rolled-back schema/history | Next action: Agree the mapping or correct source data; rerun the assertions.
- Symptom: Lock timeout | Evidence to retain: 55P03, blocking session and transactional state | Next action: Resolve the blocker or reschedule; verify state before retry.
- Symptom: Invalid concurrent index | Evidence to retain: Index definition, indisvalid/indisready, history | Next action: Choose reviewed cleanup and retry; repair only the history changes actually required.
7. Validate Flyway Migration Rollback Safety Without Assuming Every Change Is Reversible
Choose application rollback, Flyway undo, a forward fix, or restore
Choose recovery according to the actual state and business-data risk of your Flyway Migration, not according to whether an inverse SQL statement can be written.
- Recovery option: Application rollback, retaining the schema | Candidate use: The expanded schema remains compatible with the older application | Evidence required before relying on it: Old application passes against current data and schema
- Recovery option: Flyway undo — Teams | Candidate use: A completed versioned migration has a reviewed, applicable inverse | Evidence required before relying on it: Undo preserves required data and handles dependencies
- Recovery option: Forward fix | Candidate use: Keeping committed changes and applying a corrective migration is safer | Evidence required before relying on it: The correction repairs the defect without breaking current writes
- Recovery option: Backup or point-in-time restore | Candidate use: Destructive or inconsistent changes cannot be safely corrected in place | Evidence required before relying on it: Successful restore, reconciliation plan, and acceptable recovery objectives
Flyway undo uses a corresponding U migration and assumes the versioned migration completed. It is not a general handler for partially executed, non-transactional changes. Repeatables have no undo operation; restore the desired definition through the repeatable migration and reapply it.
For PostgreSQL point-in-time recovery, test the base backup and required write-ahead log archive. A restore to before a destructive migration also returns the database to that earlier business state; later legitimate writes need explicit reconciliation. A database restore does not by itself reverse external payments, messages, or other side effects.
Test post-deployment writes and the rollback window
A useful rollback rehearsal includes acknowledged writes after migration. The companion SQL-client simulation creates order 104 with paid/code 20, changes order 101 through the old writer, and inserts order 105 without the new field. It then models returning to the old writer by creating order 106 while retaining V2. tests/app_rollback.sql checks an independently specified six-row expected dataset, including identifiers, customer relationships, statuses and amounts.
For a real application-only rollback rehearsal, execute the same sequence through the actual old/new application releases. Confirm that post-deployment orders remain readable and new old-version writes still work. Do not reuse the original three-row expectation: the recovery oracle must include the intentional later changes. Passing the SQL simulation alone does not establish application rollback readiness.
For a schema undo rehearsal, additionally prove that all post-deployment values remain representable in the old schema. A newly introduced status with no legacy equivalent should block that recovery route until its data-handling policy is defined.
Set the rollback window in operational terms: which application versions can run, which writes remain backward-compatible, and which contract change closes the window. Measure recovery time against the team’s recovery time objective, and permitted data loss against its recovery point objective. Do not substitute a backup-success notification for a restore rehearsal.
Reapply changes and verify the final state
After a successful undo rehearsal, reapply the candidate migrations and rerun schema, data, and application assertions. Check the resulting history states rather than manually deleting audit records; Flyway distinguishes an undone migration from an ordinary pending migration.
After application-only rollback, the migration may still be applied. In that case, a subsequent migrate should not repeat the versioned backfill. Test redeployment of the compatible application separately.
For restored databases, identify the restored schema and business-data point, reconcile permitted later writes, and then exercise the supported upgrade path. Report the final usable state, retained data, remaining limitations, and actual recovery duration.
8. Automate Flyway Migration Regression Gates in CI/CD
Build, migrate, assert, recover, and reapply your Flyway Migration
Use separate jobs or databases for the happy path, each supported upgrade, invalid fixtures, concurrency, and recovery. Expected-failure jobs must assert the specific failure and resulting state; suppressing an error with `|` true is not a test.
The companion run.sh is the single entry point described in the setup section. It exercises fresh build, seeded upgrade, unchanged rerun, runtime permissions, SQL-client recovery, predicate mutation, malformed data, mid-migration failure, controlled contention and invalid-index detection in separate disposable databases. The snippets below are orchestration excerpts, not standalone commands; the complete wrappers and files are in the bundle.
log_run schema sql_file "$db" tests/assert_schema.sql
log_run data assert_data "$db"
log_run behavior sql_file "$db" tests/assert_behavior.sql
log_run unchanged-rerun fw "$db" migrate
# On the separately mutated fixture:
expect_failure mutation-schema P0001 \
'Schema contract mismatch' \
sql_file "$db" tests/assert_schema.sql
psql runs with `ON_ERROR_STOP` and verbose diagnostics so SQL errors stop execution and expose SQLSTATE. The harness captures the command exit code, log and expected diagnostic; an unexpected success or wrong error fails the suite. Its exit trap preserves an existing failure, captures server logs and tears down only the new Compose project. Local shell-helper checks are not evidence that these database cases passed.
Validation-on-migrate and clean-disabled settings remain enabled. Credentials are ephemeral and separated by role; the database is not exposed on a host port. Neither a database-name prefix nor a local test pass is a security audit. Keep credentials out of source control and shell tracing, and upload restricted-access artifacts even when CI fails.
Preserve evidence and define release blockers
Attach the source commit and fixture checksums, image digests, PostgreSQL server/client patch, Flyway distribution/version, JDBC jar identity and checksum, configuration without secrets, history snapshots, assertions, and recovery logs. The bundle captures runtime inventory when executed; no tested digest or JDBC runtime version is invented here. Retain catalog evidence and actual application results alongside it.
A practical release gate can use this matrix:
- Gate: Pull request | Minimum checks: Fresh build, current-release upgrade, schema and data assertions, unchanged rerun | Suggested blocking condition: Unexpected history, wrong mapping, lost data, broken constraints
- Gate: Pre-release compatibility | Minimum checks: Supported old/new application combinations and runtime roles | Suggested blocking condition: Required workflow or permission contract fails
- Gate: Pre-release operations | Minimum checks: Representative data volume, concurrent traffic, lock and timeout cases | Suggested blocking condition: Agreed availability or performance budget is breached
- Gate: Recovery readiness | Minimum checks: Applicable rollback, forward-fix, or restore rehearsal with new writes | Suggested blocking condition: Unexplained data loss, untested recovery, or unmet recovery objectives
Assign each blocker an owner. QA owns the test evidence; application owners confirm business semantics; database and operations owners approve recovery and operational limits. A green migration job should mean that the agreed checks passed not merely that no SQL error reached the console.
Conclusion
Use the four evidence layers as your release gate, and retain the schema, data, application and recovery results with the release artifact. The question is not only “Did Flyway succeed?” but “Does the evidence support this deployment?” Effective Flyway Migration regression testing requires this complete evidence chain.
For support with database migration testing and CI/CD integration, explore Codoid’s Database Testing Services.
Frequently Asked Questions
-
Why can Flyway validation pass while the application still fails?
Because validation concerns migration consistency, not every application contract. A schema can match its migration files while a status transformation is wrong, a grant is missing, or an older application cannot use a changed column. Combine validation with schema, data, and application assertions.
-
Can Flyway Community roll back a migration?
Community does not provide Flyway's Teams-only undo command. A failed transaction-compatible migration can still be rolled back by the database; that is different from undoing an already committed release. Community-based recovery can use a compatible application rollback, a new corrective migration, or a rehearsed restore.
-
How should you test an irreversible migration?
Prove the chosen recovery path rather than inventing an inverse. Preserve required source data or a recoverable backup, rehearse restore or a corrective approach, include post-deployment writes, and block destructive rollout until the accepted data-loss and recovery-time conditions are demonstrated. Undo scripts are particularly limited when the original change deletes data.
-
What is the difference between Flyway repair and undo?
Repair modifies the schema-history table to fix checksum mismatches, remove failed migration entries, or realign metadata. It does not reverse database objects. undo (Teams only) runs a corresponding inverse migration to actually revert a successful versioned migration. Neither is a substitute for careful state inspection after a partial failure.
-
Why do repeatable migrations rerun during testing?
Flyway reruns repeatable migrations (e.g., views, stored procedures) whenever their checksum changes, ordered by description after versioned migrations. They must be idempotent and safe to apply multiple times. A second migrate call is not evidence that every versioned SQL script is independently idempotent.
-
How do I handle non-transactional migrations like CREATE INDEX CONCURRENTLY?
Set executeInTransaction=false in the script's .sql.conf file. For PostgreSQL, you may also need to set postgresql.transactional.lock=false. A failed build can leave an invalid index, so your test suite must verify pg_index.indisvalid and indisready and rehearse cleanup.
-
Can I use an in-memory database (like H2) for Flyway migration testing?
No. In-memory databases have different DDL transactionality, locking behavior, constraint enforcement, and catalog views. Use the actual production database engine (e.g., PostgreSQL 18) in Docker or CI to validate schema contracts, data transformations, and rollback safety accurately.
by Rajesh K | Nov 11, 2026 | Performance Testing, Blog, Latest Post |
Validate one multipart request before adding load. Use a representative file-size and arrival-rate mix, then measure verified completions and useful payload bytes, not only requests per second. Test overload in an authorized environment and establish whether the service rejects, queues, and recovers within agreed limits. The question is not simply how many uploads JMeter can send. It is how much valid data the service can finish handling, and what happens when demand exceeds that capacity. This is the core of effective JMeter file upload load testing.
Prerequisites and scope: Basic jmeter load testing knowledge, synthetic files, an agreed upload contract, and access to server/storage telemetry. The examples target JMeter 5.6.3, HttpClient4, Java 17, and a synchronous API; Apache currently lists 5.6.3 and recommends Java 17 or later. HttpClient4 provides an HTTP/1.x baseline, not HTTP/2 or HTTP/3 fidelity merely because HTTPS is used.
Start here: Configure the request in Section 2, generate the fixture in Section 3, run one authorized upload using Section 5, then analyze its results using Section 4. Validate the reference companion files before applying load. Numerical examples are illustrative unless explicitly identified as executed checks.
Table of Content
1. Define What a Successful Upload Means
Separate request acceptance, durable storage, and processing completion
Agree on three milestones: request accepted, file stored to the required guarantee, and any scanning or conversion completed. HTTP 202 Accepted is not completed processing; 201 Created does not independently define your storage durability requirements. Those belong in the API contract.
For the synchronous example, define POST /api/uploads to return 201 only after storage completes. Its JSON response must contain an upload_id, state = “stored”, integer size_bytes, and a SHA-256 hash derived from the stored content. A checksum merely echoed from the request is not independent integrity evidence.
For an asynchronous API, maintain a separate ledger of acceptance and terminal outcomes keyed by logical upload ID. Distinguish server completion time from the time a polling client observes it. Label polling traffic separately. The supplied rate analyzer deliberately rejects 202; it does not implement this ledger.
Define the business unit as well: one HTTP request containing three files is not necessarily one business upload. Document atomic versus partial acceptance before counting completions.
Specify the workload and performance objectives
Record file sizes, files per request, valid content types, metadata, credentials, arrival pattern, and retention. Set objectives by size class, including verified completion, response-time percentiles, integrity, and recovery.
Declare a business deadline measured from the first attempt, plus an observation period long enough to evaluate it. Retries consume that same deadline. Keep deliberately invalid uploads outside the valid-upload success cohort, while still recording their load and outcomes.
Budget disk and temporary storage from attempted bytes, retries, and retained outputs, not only successful files. Assign cleanup ownership and stop limits before execution. Codoid’s API Performance Testing: Response Time, Throughput, and Scalability provides broader workload and objective-setting context.
2. Configure a Valid Multipart File Upload in JMeter
Configure the HTTP Request sampler and file fields
The companion JMX files (the JMeter test-plan files) contain one upload sampler per iteration, without transaction-parent samples or automatic retries. upload.jmx uses a standard Thread Group; upload-arrivals.jmx uses the separate arrival schedule in Section 3.
Test Plan, Thread Group / Open Model Thread Group, CSV Data Set Config, HTTP Header Manager, HTTP Request: upload, JSR223 PreProcessor: initialize identity and diagnostics, JSR223 Assertion: verify synchronous storage contract.
Apply these illustrative settings to an authorized endpoint. JMeter’s HTTP Request component documents the file, multipart, and timeout controls.
- Request: Label upload; POST; /api/upload; HttpClient4
- Host and protocol: ${_P(host, uploads.test.example)}; HTTPS; port 443
- Users, standard Thread Group: ${_P(users,1)}
- Ramp-up, standard Thread Group: ${_P(ramp,1)} seconds
- Loops, standard Thread Group: ${_P(loops,1)}
- Multipart and body: Enable multipart/form-data; leave Body Data empty
- Files Upload: Path ${file_path}; field name file; MIME type ${mime_type}
- Text parameter: purpose=load-test; UTF-8 encoding
- Headers: Bearer test token; X-Test-Upload-ID; X-Test-Attempt-ID
- Connection behavior: Keep-alive on; both redirect options off for this direct endpoint
- Illustrative timeouts: Connect 10,000 ms; response 120,000 ms; adapt to the contract
Read the token from the process environment, not a literal in the plan. A correlation header is not an idempotency guarantee. Use the API’s actual field name and browser-compatible multipart-header setting; the example uses browser-compatible headers.
Let JMeter construct the multipart boundary and request Content-Type. The inspected 5.6.3 HttpClient4 code replaces a pre-existing Content-Type in the multipart path and uses file-backed parts. Avoid manually building a giant request string.
A multipart request contains boundaries, part headers, file content, and other fields. It differs from a raw-binary body; multiple files for one form field use separate parts sharing that field name under RFC 7578.
First-request troubleshooting: Check that the generator can read the file, that file matches the endpoint’s field name, that the API expects multipart rather than raw data, and that the token is present and valid. Interpret 408, 415, or authentication responses using the endpoint contract, not a universal error-to-cause mapping. For basic JMeter navigation, see Codoid’s JMeter Tutorial: An End-to-End Guide.
Validate one upload before scaling
Run one thread and one iteration. Confirm request parts, stored bytes, the returned identifier, and cleanup. The fixture generator creates a three-byte smoke.txt containing abc without a newline, with this calculated SHA-256:
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb41f0f61f20015ad
An illustrative response, not a captured JMeter result, is:
{
"upload_id": "stored-001",
"state": "stored",
"size_bytes": 3,
"sha256": "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb41f0f61f20015ad"
}
The companion Groovy assertion checks status and JSON separately, then state, identifier, size, and hash. It records verified, verification_reason, and stored_upload_id; the preprocessor resets all three before each attempt. Its fixed diagnostics include unexpected_status, async_not_complete, json_parse, state_mismatch, missing_id, size_mismatch, and hash_mismatch.
For a controlled negative case, return a different valid-length hash while keeping the other fields unchanged. Expected result: success = false, verified = false, and verification_reason = hash_mismatch, with the sanitized storage ID retained. These are assertions to validate on JMeter, not claims that Groovy was executed here.
An illustrative selection of columns in the JTL, JMeter’s results file, would be:
label,responseCode,success,business_id,payload_bytes,verified,verification_reason,stored_upload_id
upload,201,true,logical-001,3,true,ok,stored-001
Keep full payloads and tokens out of load-run logs. Use compiled Groovy caching and vars.get(…) rather than interpolating changing values into cached script source. Reconcile representative successful uploads against independently read storage size/hash evidence outside the capacity-critical path.
3. Model Large Payloads and Upload Arrival Rates
Prepare representative files and a reusable manifest
From the companion directory, generate the smoke fixture and manifest before the test:
python prepare_fixtures.py --out ./work
The script refuses to overwrite an existing directory. Its actual generated manifest uses an absolute local path. The equivalent portable example below has the real three-byte size/hash but uses a relative path for illustration:
file_path,mime_type,payload_bytes,expected_sha256,size_class
fixtures/smoke.txt,text/plain,3,ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb41f0f61f20015ad,smoke
For the proposed large-file workload, use –large with a new output directory. It creates binary fixtures, individual manifests, and a seeded 20-row schedule:
- Size class: Small | Exact file size: 1 MiB = 1,048,576 bytes | Share of requests: 70%
- Size class: Medium | Exact file size: 25 MiB = 26,214,400 bytes | Share of requests: 25%
- Size class: Large | Exact file size: 250 MiB = 262,144,000 bytes | Share of requests: 5%
The generated binary files use a repeated byte pattern. They are suitable for controlled transfer mechanics, not representative compression, deduplication, or media-validation behavior. Replace them with valid synthetic documents or media when those properties matter. A .pdf suffix does not make arbitrary bytes a PDF.
Three CSV rows do not produce the stated mix. The schedule contains 14 small, five medium, and one large entry, shuffled with a recorded seed. Check the realized mix, particularly for short or distributed runs. Run isolated size classes before the mixed workload.
Configure CSV Data Set Config with header-derived variables, comma delimiter, UTF-8, sharing mode All threads, recycling enabled, and Stop thread on EOF disabled. Precompute hashes, keep inputs immutable, and provision supporting files on every generator.
Choose concurrency-driven or arrival-driven load
Use fixed concurrency to study a user population. Use an arrival model to study incoming work that does not slow merely because previous operations take longer. Validate actual request starts in either case.
JMeter’s Open Model Thread Group is experimental and interrupts remaining threads when its entire schedule ends. A drain instruction in prose is not enough: include the pause in the executable schedule.
rate(1/sec) random_arrivals(60 sec) rate(1/sec) pause(180 sec)
This illustrative schedule has three boundaries: schedule start, arrival cutoff at 60 seconds, and final cutoff at 240 seconds. No new arrivals are scheduled during the final pause. Existing work can continue, but work still active at the final cutoff may be interrupted. One arrival per second is an average, not an exact count each second.
Choose the pause from approved operation deadlines and cleanup/reconciliation needs, not response timeout alone. Record the schedule’s actual epoch and any startup delay; do not treat the first completed row as the schedule start. Run a slow-upload check that spans the arrival cutoff, then a separate case exceeding the final cutoff. Archive outcomes rather than assuming a bounded pause guarantees completion.
Progress from correctness to isolated-size baselines, ramp, sustained mixed load, controlled overload, and recovery. Before increasing rates, check the payload budget. This example’s weighted mean is 19.45 MiB:
0.70 x 1 + 0.25 x 25 + 0.05 x 250 = 19.45 MiB/upload
10 uploads/s x 19.45 MiB = 194.5 MiB/s = 1.63 Gbit/s
That payload demand already exceeds a 1 Gbit/s link before overhead. It is sizing arithmetic, not measured capacity.
4. Measure Upload Throughput Without Confusing Requests and Bytes
Calculate upload rate, verified payload throughput, and sent-byte rate
Declare a window [T0, T1): include events at T0, exclude events at T1. Let W be its duration in seconds. Keep the event definitions separate:
- Attempt-start rate: Upload HTTP attempts starting in the window / W; retries count again
- Acceptance rate: Contract-valid acceptance responses observed in the window / W; identify duplicate acknowledgments
- Verified completion rate: Unique logical uploads first verified complete in the window / W
- Verified payload rate: Their verified file bytes / W / 1,048,576, in MiB/s
- Sample-attributed sent-byte rate: sentBytes for upload requests finishing in the window / W / 1,048,576
- Network transmit rate: Interface/transport counter deltas during the window, with other traffic accounted for
“Sample-attributed” means assigning all recorded bytes of a request to its finishing window. It does not establish when every byte crossed the network. JMeter’s request throughput and result fields do not automatically provide business-completion accounting.
sentBytes is not wire throughput or proof of storage. It excludes the full lower-layer accounting required for that claim, and an I/O failure may return without normal sent-byte assignment. Zero does not prove that no bytes left the generator.
Consider a synthetic 60-second dataset: 120 attempts, each with 25 MiB of payload; 114 verified completions and six 503 failures; all requests start and finish inside the window. A chosen 1 KiB per-attempt sent-byte increment gives:
Attempt rate = 120 / 60 = 2.0 uploads/s
Verified completions = 114 / 60 = 1.9 uploads/s
Verified payload rate = (114 x 25) / 60 = 47.5 MiB/s
Attributed sent rate = (120 x (25 + 1 / 1024)) / 60 = 50.001953125 MiB/s
The 1 KiB increment is fabricated for arithmetic, not measured multipart or network overhead. The package includes this synthetic CSV and its analyzer output:
python analyze_uploads.py examples/synthetic-120.jtl \
1793750400000 1793750460000
"observed_starts_per_s": 2.0,
"http_201_responses_per_s": 1.9,
"verified_unique_uploads_per_s": 1.9,
"verified_payload_MiB_per_s": 47.5,
"sample_attribute_sent_MiB_per_s": 50.001953125,
"finished_samples": 120,
"window_starts_finishing_at_or_after_end": 0
}
The helper counts 201 acknowledgments separately from verified completion. It does not validate an API’s acceptance contract, calculate percentiles, or issue a release verdict. Use the complete reconciled run, including earlier rows, so a duplicate acknowledgment does not become a new completion. Exclude polling, cleanup, and parent transaction labels from upload calculations.
Interpret elapsed time, latency, and size-specific percentiles
Elapsed time runs from before the request to the final response; latency ends at the first response; connect time includes connection establishment and TLS handshake. None is an isolated upload-transfer timer. Subtracting latency from elapsed does not calculate file-upload duration.
Report size class, outcome, and sample count beside percentiles. For the synchronous contract, use the end of the response carrying the storage evidence as the client-observed completion time. Server timestamps are needed to separate body receipt, persistence, and subsequent processing.
The following is a reporting template, not measured output. Populate percentiles from eligible individual observations with a declared percentile method; do not average worker percentiles.
- Size class / outcome: Small / verified | Count: Fill | p50 ms: Fill | p95 ms: Fill | p99 ms: Fill | Verified bytes: Fill | Unfinished IDs: 0
- Size class / outcome: Medium / verified | Count: Fill | p50 ms: Fill | p95 ms: Fill | p99 ms: Fill | Verified bytes: Fill | Unfinished IDs: 0
- Size class / outcome: Large / verified | Count: Fill | p50 ms: Fill | p95 ms: Fill | p99 ms: Fill | Verified bytes: Fill | Unfinished IDs: 0
- Size class / outcome: Each class / failed | Count: Fill | p50 ms: Fill | p95 ms: Fill | p99 ms: Fill | Verified bytes: O | Unfinished IDs: O
- Size class / outcome: Each class / unresolved | Count: Fill | p50 ms: Not known | p95 ms: Not known | p99 ms: Not known | Verified bytes: O credited | Unfinished IDs: Fill
A request can start in the arrival window and finish during drain. Count those events in their respective windows; do not discard the request. JTL-only analysis cannot reveal starts that never emitted a result, so reconcile ingress and completion records independently.
The Python helper streams rows but retains dictionaries for U distinct logical IDs: memory is O(U), not constant. It no longer materializes an additional completion list. For very large runs, use a disk-backed keyed store or external grouping that preserves earliest-completion semantics; that backend is not supplied or benchmarked here.
5. Run the Test Without Saturating the Load Generator
Use CLI execution and lightweight result collection
Debug at low volume in the GUI, then use CLI mode for load. Disable resource-heavy listeners and Functional Test Mode. Do not retain full request/response bodies during the capacity run.
The companion upload.properties explicitly enables millisecond start timestamps, timing fields, sentBytes, success, assertion messages, and the diagnostic variables. It disables HttpClient4 automatic retries for the baseline. These settings do not disable retries elsewhere in the application or proxy.
sampleresult.timestamp.start=true
sample_variables=business_id,attempt_id,payload_bytes,size_class,\
verified,verification_reason,stored_upload_id
httpclient4.retrycount=0
httpclient4.request_sent_retry_enabled=false
Use the complete properties file, not only this excerpt. On Bash, securely enter and export the token so the Java subprocess receives it:
export JAVA_HOME=/path/to/jdk-17
read -r -s -p "Test token:" UPLOAD_TOKEN
printf '\n'
export UPLOAD_TOKEN
python run_upload.py --manifest ./work/manifest.csv \
--host uploads.test.example --confirm-authorized
Replace the Java path and hostname; make jmeter available on PATH or pass –jmeter. The wrapper checks the intended toolchain and fixture hashes, creates a unique results directory, and refuses an existing target JTL. It does not print or place the token in command arguments. Its checks are not a resource watchdog or proof of test success.
The underlying execution uses -n, -t, -q, -J, -l, and -j. For arrival mode, add –arrivals –rate 1 –arrivals-seconds 60 –drain-seconds 180 only after the smoke and stop-control checks. On Windows, use jmeter.bat, Windows environment syntax, and appropriate file paths.
At every load step inspect generator CPU, memory/garbage collection, fixture-read latency, network utilization, socket/file-descriptor availability, NAT constraints, and result-write latency. Check actual starts against the intended schedule before blaming the server for a plateau.
Validate distributed files and per-engine load budgets
Each remote engine runs the full plan; JMeter does not divide its configured load automatically. Supporting files are not transferred with the plan. Local -J properties are not a substitute for worker configuration; -G is for suitable shared remote properties.
- Worker prerequisite: Toolchain and credentials | What to verify before starting: Matching JMeter/Java versions; each worker process receives its own approved token
- Worker prerequisite: Target and load allocation | What to verify before starting: Effective host, port, protocol, and per-worker user/arrival budget; rates sum to the intended total
- Worker prerequisite: Startup settings | What to verify before starting: Retry and timestamp settings loaded before engine startup; restart engines after relevant changes
- Worker prerequisite: Files and result contract | What to verify before starting: Local manifest, fixtures and Groovy scripts; matching hashes; controller result-variable configuration
Use worker-specific configuration for different budgets. Do not distribute secrets in shared command-line properties. Reconcile starts, ingress, rejections, completions, and unresolved work without assuming every counter should be identical. For broader sizing, see Codoid’s JMeter Distributed Load Testing: Sizing & Bottlenecks.
6. Test Server Backpressure, Rejections, and Retry Behavior
Separate slow request consumption, buffering, and processing queues
A slow response is not proof of transport backpressure. TCP receive-window behavior can restrict sending when a peer cannot accept more data; HTTP admission decisions and application queues are different mechanisms.
(Figure 1 description: Conceptual observation points, not a measured deployment. Observe the proxy and storage path as well as the generator; correlate terminal outcomes independently. Flow goes JMeter Engine -> Proxy / Ingress -> Application -> Storage / Workers. Solid arrows request path. Dashed arrows evidence flow. Slow responses alone do not prove transport backpressure.)
For example, NGINX with proxy_request_buffering on reads the request body before forwarding it. Disabling it permits forwarding as the body arrives, subject to protocol-specific buffering behavior. Request buffering is not response buffering. Verify the deployed proxy version and upstream protocol instead of assuming HTTP/1.1 settings apply everywhere.
Large client bodies can use proxy temporary storage. A fast client-to-proxy transfer can therefore coexist with slow persistence upstream. Monitor temporary-disk usage, body-read progress, storage latency, queue depth, and oldest-item age.
Establish the baseline, then change one constraint: slow request-body consumption, constrain persistence, or limit processing workers. Keep load and fixture mix unchanged. Record fault start, fault removal, admission decisions, completion rate, backlog, and recovery. Expected signal patterns are hypotheses to verify, not guaranteed outcomes.
Assign stop enforcement, not just thresholds. The following is an ownership template; owners must implement and rehearse the mechanisms before the overload run.
- Limit: Active uploads | Owner and monitored signal: Performance engineer; generator and ingress in-flight counts | Required enforcement and recovery action: Tested supervisor stops new arrivals; escalates to bounded interruption if necessary
- Limit: Temporary/storage disk | Owner and monitored signal: Infrastructure owner; free space and consumption rate | Required enforcement and recovery action: Watchdog stops load and fault injection before reserve is exhausted; reconciles partial objects
- Limit: Queue size/age | Owner and monitored signal: Application owner; depth and oldest-item age | Required enforcement and recovery action: Server admission limit rejects excess work; supervisor stops the experiment at the agreed threshold
- Limit: Error budget or time limit | Owner and monitored signal: Test lead; rolling errors and elapsed phase time | Required enforcement and recovery action: Timestamped abort signal; restore normal configuration; verify cleanup and recovery
The companion launcher does not implement these environment-specific watchdogs. Do not begin an overload experiment until ownership and enforcement are real.
Classify failures and verify bounded recovery
Keep response classes separate: 413 indicates unacceptable content size; 429 indicates rate limiting; 503 indicates temporary unavailability; 202 indicates acceptance without final completion. A timeout/reset leaves the client without a conclusive outcome. None alone proves where the bottleneck is. 429 may include Retry-After, but need not.
Run a no-retry baseline, then the intended bounded retry policy. An illustrative policy allows at most three total attempts within one business deadline, with backoff and jitter. Honor valid Retry-After guidance without exceeding that deadline. Do not immediately retry merely to improve the final success percentage.
POST is not generally idempotent; a lost response can follow a committed write. Use a server-supported idempotency contract or reconcile before resubmitting ambiguous work.
For retries, generate business_id once outside the retry loop and assign a new attempt_id per attempt. Keep the payload unchanged. Test response loss after commit and concurrent duplicate submissions. The supplied no-retry preprocessor creates a new business ID each iteration and must be moved/adapted for that workflow.
Report attempt amplification as total attempts divided by logical uploads initiated, together with retry bytes and duplicate outcomes. After removing the fault, verify that queues drain, resource use recovers, and partial files are cleaned within the agreed period. No buffering/recovery trace is presented here as a measured result.
7. Build a Failure Matrix and Release Decision
Cover boundaries, interruptions, and duplicate submissions
Use this starting matrix, with expected outcomes taken from the endpoint’s documented contract.
- Scenario: Valid uploads | Input/action: Every approved size/type and metadata combination | Required assertions and evidence: Terminal state, exact stored size, integrity, attributable ID
- Scenario: Size boundaries | Input/action: Per-file limit L-1, L, L+1; total-body boundary B separately | Required assertions and evidence: Correct enforcing layer; no invalid retained object
- Scenario: Invalid inputs | Input/action: Empty/missing file field, invalid type, malformed metadata | Required assertions and evidence: Contract-specific result; no false completion
- Scenario: Authorization | Input/action: Expired token or unauthorized destination | Required assertions and evidence: Denial without unauthorized stored content
- Scenario: Interrupted transfer | Input/action: Disconnect mid-body and near completion | Required assertions and evidence: Reconciled outcome; partial-file cleanup within its deadline
- Scenario: Ambiguous/concurrent duplicates | Input/action: Lose response after commit; retry or submit concurrently | Required assertions and evidence: One intended logical result under the idempotency contract
- Scenario: Multiple-file partial failure | Input/action: Mix valid/invalid parts where supported | Required assertions and evidence: Documented atomic or partial acceptance; per-file accounting
- Scenario: Overload and recovery | Input/action: Exceed the approved admission budget, then remove pressure | Required assertions and evidence: Bounded resources, expected rejection, backlog and latency recovery
Multipart overhead counts toward total request-body size. A file equal to the body’s size limit can exceed that limit once other parts and headers are added. RFC 7578 defines the multipart structure; NGINX’s client-body limit is a request-body limit, not an individual-file rule.
Keep scenario pass/fail separate from useful upload volume. Correctly rejecting an invalid upload can pass a negative test while adding zero verified payload bytes.
Set evidence-based pass/fail gates
Define the valid-upload cohort as unique logical IDs whose first attempts start in [T0,T1). Count each once, including operations that fail or remain unresolved. Exclude deliberately invalid test cases according to the predeclared eligibility rule.
Deadline completion percentage = eligible IDs verified complete within their business deadline / all eligible logical IDs x 100
Retries do not increase the denominator. For synchronous client-observed completion, assess the first qualifying response against the first-attempt start plus deadline. Do not divide unrelated start-rate and completion-rate windows to obtain a success percentage.
Illustrative decision: First attempts start from 12:00:00 up to, but not including, 12:01:00. Each has a 180-second business deadline. Observe through 12:04:00 and reconcile all 1,000 eligible IDs:
- Final cohort outcome: Verified within deadline | IDs: 980 | Counted as deadline success? Yes
- Final cohort outcome: Verified, but late | IDs: 8 | Counted as deadline success? No
- Final cohort outcome: Terminally rejected | IDs: 5 | Counted as deadline success? No
- Final cohort outcome: Terminally failed | IDs: 4 | Counted as deadline success? No
- Final cohort outcome: Still unresolved at final observation | IDs: 3 | Counted as deadline success? No; retain their uncertainty
The result is 98% so an illustrative 99% gate fails. “Terminal” means no more permitted retry/reconciliation work remains under the declared policy. If observation ends before the last eligible deadline, flag insufficient coverage; do not silently drop unfinished operations or issue a full pass.
Combine this cohort gate with size-specific latency limits, delivered-load validity, zero observed integrity mismatches/unintended duplicates, bounded retry amplification, resource limits, and recovery/cleanup objectives. A finite run cannot prove a zero future-defect rate.
- Symptom: Starts flatten; generator egress is full | Evidence and next controlled check: Reallocate generators at unchanged aggregate demand; verify starts improve
- Symptom: Proxy disk grows; application starts lag | Evidence and next controlled check: Inspect body buffering and upstream timings; compare an approved configuration
- Symptom: Acceptance rises; completions lag | Evidence and next controlled check: Inspect queue age and storage/processing timing; isolate the constrained stage
- Symptom: Failures recur at one size | Evidence and next controlled check: Test precise file and total-body boundaries at low concurrency
- Symptom: Attempts rise; useful throughput falls | Evidence and next controlled check: Compare retry/duplicate records against the no-retry baseline
Archive the JMX and script hashes, fixture manifest, effective settings, full JTL, completion evidence, telemetry window, and cleanup record. An unexplained accounting gap limits the capacity claim even when response-time charts look acceptable.
Conclusion
The release question is whether the intended upload workload completes correctly, stays within resource limits, and recovers predictably, not whether JMeter reports a large request count. Keep attempted traffic, accepted work, verified completions, and useful payload bytes distinct, and make every release gate traceable to evidence. Effective JMeter file upload load testing requires this rigorous approach.
For support with workload design and bottleneck analysis, explore Codoid’s Performance Testing Services.
Frequently Asked Questions
-
Is multipart/form-data the same as a resumable multipart upload protocol?
No. It defines body encoding for fields and files, not resumable sessions, chunk retries, or finalization. Those require the service's separate protocol and workflow, outside this synchronous helper's scope.
-
Why can sent-byte throughput rise while successful upload throughput falls?
Retries and failed attempts can increase sent-byte accounting without increasing unique verified completions. Compare attempts, completion evidence, and useful payload bytes; JMeter's byte counter is not a storage receipt.
-
Does increasing JMeter's response timeout solve large-upload failures?
Not necessarily. JMeter's response timeout governs individual response waits, not a guaranteed overall deadline. NGINX's client-body and upstream-send timeouts govern gaps at different stages. A Duration Assertion evaluates duration; it does not cancel a request. Also inspect test shutdown: the Open Model schedule can interrupt long requests at its final cutoff.
by Rajesh K | Nov 10, 2026 | AI Testing, Blog, Latest Post |
RAG testing (retrieval regression testing) verifies that the updated pipeline still finds the evidence a question needs and that document changes reach final context within the agreed freshness deadline, the maximum permitted delay after an authoritative source change. Compare baseline and candidate results against versioned queries, measure precision and recall with explicit definitions, and separately check revisions, deletions, permissions, and final context.
A relevance score alone is not a release decision. In the illustrative example below, rank-sensitive context precision improves to 1.00 while recall falls to 0.67. Another test returns the expected chunk ID but fails because its text contains an obsolete policy.
Table of Content
1. What Should RAG Retrieval Regression Testing Verify?
Separate retrieval quality from answer quality
Retrieval-augmented generation supplies external knowledge to a language model. Retrieval and generation are distinct parts of that workflow; evaluate them separately before assessing the complete answer.
For your regression suite, capture these boundaries:
- Boundary: Candidate retrieval | Evidence to capture: Ordered IDs, text, scores, filters, source revisions | Test question: Was the required evidence found?
- Boundary: Reranking | Evidence to capture: Reordered candidates and reranker configuration | Test question: Did useful evidence move out of the usable results?
- Boundary: Final context | Evidence to capture: Exact text and order sent to the model, after filtering, deduplication, and truncation | Test question: Did the model actually receive the evidence?
Treat these as separate result sets. Finding a passage among 50 candidates does not establish that it survived a five-passage context limit. Conversely, a wrong answer with complete, correct context calls for downstream investigation rather than an automatic retrieval diagnosis.
Without retrieval traces, report answer-level observations, not verified retrieval precision or recall.
Use separate tests for retrieval changes and document changes
Use two complementary tracks:
- Fixed-corpus regression: Compare baseline and candidate on the same source snapshot and reviewed labels. Record embedding, chunking, query-rewriting, search, reranker, filter, and context-budget configurations. Identify the intentional change; hold unrelated settings constant.
- Document-lifecycle regression: Hold the retrieval configuration constant while adding, changing, withdrawing, or deleting controlled documents. Evaluate each transition against its intended state, not yesterday’s answer.
For prompt changes, keep a separate behavioral suite, as discussed in Codoid’s Prompt Regression Testing guide.
Extend that foundation with an explicit test contract:
Define relevant evidence, not just expected document IDs
- Dataset field: Query and identity | What to record: Query ID, exact question, tenant, role, language, and evaluation time
- Dataset field: Reference evidence | What to record: Required facts, acceptable supporting passages, and relevance judgments
- Dataset field: Source state | What to record: Logical document ID, revision, effective interval, and content digest
- Dataset field: Expected behavior | What to record: Answerability, mandatory evidence, forbidden revisions, and access restrictions
- Dataset field: Evaluation contract | What to record: Cutoff, metric definitions, duplicate handling, and acceptance rules
- Dataset field: Reproducibility | What to record: Dataset, corpus, parser, chunker, embedding, and retriever configuration versions
Keep a manifest, an inventory of expected chunk IDs, revisions, and text. Keep logical evidence separate from those physical IDs: after rechunking, “receipt required” may move from one chunk to two. Revalidate its supporting passages instead of preserving obsolete IDs.
When several documents independently support the same fact, distinguish document discovery from sufficient evidence. Document recall may require finding all labeled documents; claim coverage can credit one valid supporting alternative. Define alternatives explicitly rather than letting overlapping chunks multiply the reference denominator.
Cover ordinary, difficult, and unanswerable queries
Include single-document lookups, multi-document questions, exact product identifiers, paraphrases, near-duplicate distractors, current and historical questions, restricted records, and genuinely unsupported questions. Add previously observed failures with sanitized inputs.
For an unsupported question, specify whether the application should retrieve related material and abstain, or return no context. These are different contracts. Do not require empty retrieval for every unanswerable question.
Keep conversational-memory tests separate; Codoid’s AI Agent Memory Testing article addresses that adjacent boundary.
Review labels and version the evaluation contract
Have a domain reviewer approve required facts and relevance labels. For larger corpora, review pooled baseline and candidate results and disclose incomplete judgments: recall against an assessed pool is not exhaustive corpus recall.
In the demonstration, an unjudged result makes the evaluation invalid, rather than silently counting as relevant or irrelevant. Have reviewers label it, version the dataset, and rerun both configurations. This is a deliberate policy choice; evaluation tools expose different unlabeled-result conventions.
Use separate development and held-out release sets; dataset splits can support this separation. Tune on development cases, freeze the candidate, then run the reserved set at release checkpoints. Require domain approval for label changes. When a held-out failure becomes a tuning case, move it to development and refresh the reserved set rather than repeatedly tuning against it.
2. Measure Context Precision and Recall Without Mixing Definitions
Calculate precision@k and recall@k
For unique, judged results, precision measures how many retrieved items are relevant, while recall measures how much of the relevant reference set was retrieved. The demonstration uses:
Precision@k = relevant result positions within the first k / k
Recall@k = distinct relevant IDs found within the first k / total relevant reference IDs
Here, missing positions count against precision: returning two relevant items at k=5 gives precision = 5 = 0.40. A separate “precision among returned items” would be 1.00. State the denominator instead of comparing these as identical metrics.
Specify the unit, documents, chunks, or evidence units, and the pipeline stage. Do not compare document-level baseline recall with chunk-level candidate recall. If the relevant reference set contains more than k chunks, perfect ID recall is impossible at that cutoff; avoid unreachable acceptance thresholds.
Distinguish rank-sensitive context precision from ID precision
Ragas documents a rank-sensitive context-precision calculation:
Rank-sensitive context precision = sum of [precision at rank i x relevance at i] / number of relevant retrieved items
Its ID-based precision instead compares matching context IDs with retrieved context IDs. These measures are not interchangeable.
Consider a fully labeled, fictional corpus. A, B, and C are the three relevant chunks; X, Y, and Z are irrelevant. All results below use k=5:
- Retrieval order: Baseline (A, X, B, Y, C) | Precision@5: 0.60 | Recall@5: 1.00 | Rank-sensitive context precision: 0.75
- Retrieval order: Candidate (A, B, X, Y, Z) | Precision@5: 0.40 | Recall@5: 0.667 | Rank-sensitive context precision: 1.00
- Retrieval order: Complete and reordered (A, B, C, X, Y) | Precision@5: 0.60 | Recall@5: 1.00 | Rank-sensitive context precision: 1.00
For the baseline, the rank-sensitive calculation is (1 + 2/3 + 3/5) / 3. The candidate puts its two relevant chunks first, but loses C. Its perfect ranking score does not establish completeness or freedom from irrelevant trailing context.
Add normalized discounted cumulative gain when graded relevance matters, or mean reciprocal rank when first-hit placement matters; neither replaces a completeness check.
Measure reference-claim coverage separately
Ragas’s claim-based context recall checks how many reference-answer claims the retrieved context supports. Its ID-based recall instead checks reference IDs found among retrieved IDs.
For a reference requiring “14-day window,” “receipt required,” and “unopened items,” context supporting only the first two has claim coverage of 2/3. This is a calculation over the example’s reviewed claims, not a measured model result.
Require support from the supplied text, not the evaluator’s background knowledge. Review partial support, negation, exceptions, and conflicting revisions. Matching a document ID alone cannot establish that the needed sentence survived context assembly.
Handle duplicates, empty results, and missing references explicitly
Use declared conventions. Duplicate chunk IDs fail this suite’s gate; recall counts each reference ID once. For an answerable query, no relevant item in the evaluated prefix means rank-sensitive context precision is 0, including nonempty all-irrelevant results. Precision and recall are also 0. Empty retrieval follows the same rule; genuinely unanswerable cases remain N/A.
The companion’s all_irrelevant.json fixture returns X, Y, and Z for current_policy: three inspected results, all judged irrelevant, and three zero metric scores. Missing labels on an answerable case are invalid data, not an unanswerable case. Report scored and N/A case counts alongside averages.
3. Test Document Updates from Source to Retrieved Context
Validate additions, edits, rechunking, and deletion
Use isolated fixtures, restoring the initial state before each independent scenario. The following is a proposed lifecycle matrix, not a claim about a particular vendor’s guarantees.
- Change and precondition: New document; query initially unsupported | Action: Add a document containing the missing fact | Required assertion and evidence: New evidence becomes retrievable by the agreed deadline; retain source and query traces
- Change and precondition: Existing policy revision | Action: Change one fact; preserve a second supporting document | Required assertion and evidence: Retrieve the new fact plus unchanged support; verify text and revision
- Change and precondition: Document becomes shorter | Action: Remove a section and rechunk | Required assertion and evidence: New chunk manifest matches the intended state; obsolete chunks are absent where removal is required
- Change and precondition: Explicit document deletion | Action: Delete the source and trigger its removal workflow | Required assertion and evidence: Enumerate remaining records and check known old IDs; verify caches and retrieval after completion
- Change and precondition: Metadata or permission change | Action: Revoke access or change a filter attribute | Required assertion and evidence: Unauthorized users receive no protected context; authorized controls still work
- Change and precondition: Partial ingestion | Action: Fail one item or processing stage | Required assertion and evidence: Detect incomplete state; recovery produces the full intended manifest
- Change and precondition: Duplicate or reordered event | Action: Replay an event; deliver an older revision last | Required assertion and evidence: No duplicate records or unintended return to older content
- Change and precondition: Approved rollback | Action: Restore the authorized release state | Required assertion and evidence: Queries, manifests, caches, and active routing match the rollback contract
For Azure Storage indexes, change detection and deletion detection have different requirements. Microsoft warns that missing deletion handling can leave orphaned search documents; enabling a policy later does not automatically repair previously missed deletions.
Test effective dates, permissions, and cached results
Use a fictional support policy: v1 allows returns within 30 days; v2 changes the window to 14 days at October 1, 2026, 00:00 UTC. A separate receipt requirement stays unchanged.
Test immediately before, at, and after that boundary. Current questions must follow v2 after activation. Historical questions may use v1 only where the product permits historical retrieval. Explicit deletion is a separate contract; do not retain historical access where removal forbids it.
Warm the application cache before the update, then repeat queries through the normal user path. Check fresh sessions and restart recovery. For permission revocation, use both authorized and unauthorized identities, including equivalent cached questions. Do not assume an indexing freshness allowance authorizes temporary data exposure.
Exercise partial failures, retries, concurrent updates, and rollback
Inject a failure after one new chunk is written but before another is written or an old chunk is removed. Inspect item-level outcomes, retry according to the documented error policy, and compare the recovered records with the intended manifest.
Azure AI Search can return HTTP 207 for partially unsuccessful indexing requests. It also documents no ordering guarantee for actions inside a request body. These are Azure-specific reasons to inspect individual outcomes and avoid assuming request order determines final state.
Replay v1 after v2 to test obsolete-event handling. Require the application’s revision rule to win, not whichever event arrives last. Test readers during an update against the product’s declared consistency contract. A rollback must restore an approved state, not blindly revive a policy that is no longer valid.
Verify readiness and enforce a freshness deadline
Measure source acceptance, indexing visibility, correct retrieval, and correct final context separately.
For each update, record the authoritative change time, the deadline, attempts, first observed correct result, and timeout outcome. Use bounded polling with a monotonic timer for elapsed duration. Preserve the observed propagation lag; retries must not erase a missed deadline. Recheck after readiness to catch regression or cache repopulation.
Pinecone documents eventual consistency. For its serverless Database API, a query’s indexed log sequence number can confirm that a write has been reflected. It does not prove that later writes preserved the intended record or that ranking returned the needed evidence.
Assert that required new text is present and prohibited old text is absent. Enumerate all relevant pages of records and inspect known old IDs; a single top-k miss proves only that the item was not returned. Pinecone’s serverless listing functionality supports pagination and ID-prefix filtering, subject to the selected API.
If record enumeration is unavailable, document that limit rather than claiming complete deletion verification.
4. Automate Retrieval Regression Checks in Python
Define a portable fixture and retrieval-result format
What you can run: an offline scorer replay over synthetic fixtures, without a database, credentials, model calls, or third-party packages. Live ingestion, freshness, physical deletion, cache behavior, full authorization, and claim-based judging require separate adapters. Tested on Python 3.13.5; Python 3.11+ is the intended compatibility target, not a verified support matrix.
Companion release v1.1.0: Download the Python scorer, fixtures, tests, and captured reports.
Extract the archive, open its rag_retrieval_regression_v1_1_0 directory, and run the commands below from there. The adjacent .sha256 file identifies the archive; RELEASE.json identifies its code and fixtures. The synthetic replay has no live-service dependency.
dataset.json holds six queries, binary judgments, required IDs, forbidden revisions, thresholds, and the trusted manifest. Each observed hit includes chunk_id, doc_id, version, tenant, and actual text. Run metadata identifies the corpus, dataset, contract, stage, and retrieval configuration.
This is the complete content_integrity case in dataset.json (a case object, not a standalone dataset):
{
"id": "content_integrity",
"query": "What is the current return window?",
"slice": "policy-current",
"tenant": "retail",
"as_of": "2026-10-02T09:00:00Z",
"answerable": true,
"expect_empty": false,
"judgments": {"A": 1, "B": 0, "C": 0, "A_old": 0, "X": 0, "Y": 0, "Z": 0, "S": 0},
"required_ids": ["A"],
"forbidden_versions": {"returns": ["v1"]},
"min_precision": 0.2,
"min_recall": 1.0,
"max_precision_drop": 0.0,
"max_recall_drop": 0.0
}
The manifest expects A to contain “Returns are accepted within 14 days of delivery.” The actual synthetic hit in candidate.json instead carries old text under the current ID and revision:
{
"chunk_id": "A",
"doc_id": "returns",
"version": "v2",
"tenant": "retail",
"text": "Returns are accepted within 30 days of delivery."
}
Do not manufacture returned text from the expected manifest when adapting the example to a live retriever. The manifest is the reference; the trace is the observation.
Calculate metrics and assert document-state requirements
The bundled scorer rejects incomplete runs, unknown or unjudged IDs, malformed records, contradictory references, and incomparable snapshots. It calculates metrics at the declared cutoff, checks mandatory evidence within that cutoff, and checks revision, content, tenant, and duplicate failures across every captured hit.
Entry point for the companion scorer – run_regression.py. This file imports the complete scorer in rag_regression.py and preserves its failure status:
# Save beside rag_regression.py and the supplied JSON fixtures.
import json
import sys
from pathlib import Path
from rag_regression import compare, load
root = Path(__file__).resolve().parent
try:
report = compare(
load(root / "dataset.json"),
load(root / "baseline.json"),
load(root / "candidate.json"),
)
except (OSError, ValueError, TypeError, KeyError) as error:
print(json.dumps({"status": "INVALID", "error": str(error)}))
sys.exit(2)
print(json.dumps(report, indent=2, allow_nan=False))
sys.exit(0 if report["status"] == "PASS" else 1)
The implementation compares the exact returned text’s SHA-256 digest with the trusted fixture text. This detects old content presented under an expected ID or revision. It is an integrity check, not semantic relevance judgment, proof of correct embeddings, or a substitute for real authorization tests.
For controlled rechunking or text normalization, rebuild and review the manifest. For embedding updates, retain the embedding-model identifier and input-content digest, then rerun retrieval cases; matching text metadata alone does not verify the vector was regenerated.
Run self-tests and distinguish replay from live integration
For the expected-failure demonstration, run the verifier rather than pasting failing commands into one fail-fast shell sequence:
The verifier checks checksums, nonzero test discovery, each expected exit, and report contents; it writes a new verification/ directory. Its exit 0 means the demonstration behaved as specified, including the intentional failures, not that its defective candidate is safe to release.
- Check: Self-tests | Expected exit: 0 | Expected result: 49 test methods pass
- Check: Defective candidate | Expected exit: 1 | Expected result: FAIL; five newly failing queries
- Check: Recovered candidate | Expected exit: 0 | Expected result: PASS
- Check: Incomplete input | Expected exit: 2 | Expected result: INVALID
- Check: All-irrelevant fixture | Expected exit: 1 | Expected result: FAIL; current-policy metrics are 0
- Check: run_regression.py | Expected exit: 1 | Expected result: Same intentional candidate failure
Individual commands and their exact expected outcomes are in the README. The verifier deliberately handles exits 1 and 2; never replace those checks with a blanket failure suppression such as || true.
Release gating is different. CI means continuous integration. Supply real captured traces and run the separate gate as a dedicated failing-on-error CI step:
python ci_gate.py dataset.json baseline.json captured_candidate.json \
--report artifacts/retrieval.json
captured_candidate.json is your adapter’s output, not a supplied fixture. The gate saves its report and returns 0 for PASS, 1 for FAIL, or 2 for INVALID. Missing input or report-write failure also fails. Configure CI to preserve reports on failed steps and propagate every nonzero exit; the package does not configure your CI service.
A clean extraction of release v1.1.0 was executed locally on Python 3.13.5: 49 tests passed, including the original 40 and nine review-driven tests. Candidate, recovered, invalid, and all-irrelevant runs produced the expected exits. The candidate’s five failures cover missing evidence, stale text, a forbidden revision, a duplicate chunk, and unauthorized tenant content.
For content_integrity, this is the complete candidate score object from the captured evidence/candidate.stdout.json report (queries entry with that query_id):
{
"precision_at_k": 0.2,
"recall_at_k": 1.0,
"rank_context_precision": 1.0,
"scored_hits": 1,
"captured_hits": 1,
"duplicate_rate": 0.0,
"failures": [
"content_mismatch:A"
]
}
The correct chunk ID gives recall 1.0, but content_mismatch:A fails the query. This is executed synthetic replay evidence, not a live freshness measurement. The README defines the remaining adapter work.
5. Set CI Gates That Do Not Hide Important Regressions
Separate hard failures from quality tolerances
Use deterministic rules for observable contracts; LangSmith similarly distinguishes code evaluators from model-based judgments. Suggested release policy:
Hard failures: unauthorized final context, prohibited revisions after their applicable deadline, missing mandatory evidence, invalid evaluation input, incomplete ingestion, or a failed recovery contract.
Quality tolerances: agreed precision/recall floors and permitted changes relative to a qualified baseline. Choose these by task and risk, not an invented universal target. The sample’s per-query thresholds and zero-drop tolerance are fixture settings, not production recommendations.
Define operational measures before a live run. Use a fixed observation window and a prescribed query schedule; do not let ad hoc retries change the denominators.
Stale-context rate: among completed, inspectable scheduled current-policy probes from the update deadline through the fixed window end, count probes containing any prohibited old revision. An empty returned context is inspectable but missing evidence, not stale evidence. Exclude historical queries from this current-policy population. Report missing evidence separately, and record timeouts or absent traces as observation failures. A zero observed-stale rate cannot pass an incomplete-observation gate.
On-time update completion: count each initiated logical transition once, using a unique transition ID assigned before the update. Among transitions whose deadlines have elapsed by the reporting cutoff, divide those that satisfied all required state and retrieval checks by that entire cohort. Ingestion failures and timeouts stay in the denominator; pending deadlines are reported separately. Late recovery does not rewrite an on-time failure. Report retry attempts and time to first verified correct state separately.
For the existing fictional policy edit, an unexecuted test specification could use transition T-001, source change 09:00 UTC, deadline 09:01, and scheduled probes at 09:01, 09:02, and 09:03. Its disposition is NOT RUN until actual context, timestamps, and checks are recorded. These are chosen test inputs, not measured propagation times or a recommended service-level target.
Compare paired queries and important slices
A paired comparison evaluates the same queries under both configurations. Keep identity, time, reference state, and metric definition equivalent. Report per-query changes, newly failing cases, and slices such as current policy, historical policy, permissions, and unsupported questions.
An overall average must not compensate for a prohibited disclosure or lost critical fact. The sample reports a macro-average, the unweighted mean across scored queries, with its contributing count. A passing candidate does not qualify a failing baseline.
For lifecycle tests, compare each state with its own approved expectations. Do not interpret the correct replacement of yesterday’s fact as a regression.
Control evaluator and retrieval variability
Pin evaluator model, rubric, prompt, and dataset versions. Keep human-reviewed calibration cases. Repeat unstable retrieval or model-judged cases and report variability before treating small score differences as meaningful.
For a larger noisy suite, predeclare a paired uncertainty method. One option is 10,000 bootstrap resamples of query pairs with replacement, computing the mean candidate-minus-baseline score for each resample and a 95% percentile interval; fix the seed and compare the interval with the agreed tolerance. Paired resampling preserves matching observations across the two configurations. Aggregate repetitions within queries first; group related paraphrases when queries are not independent. This is a recommended analysis, not implemented in the six-query replay. Deterministic security failures do not wait for statistical significance.
Offline evaluation supports comparing application versions on curated datasets; the release decision still depends on your acceptance contract. Changing the judge and retriever simultaneously should be an explicit experiment, not an unexplained baseline replacement.
6. Diagnose Failures with a Retrieval Evidence Trail
Locate the failing stage
Use the following as investigation hypotheses, not automatic root-cause verdicts:
- Observation: Fact missing from parsed text | Inspect next: Source export, parser, table extraction, and chunk boundaries
- Observation: Correct text absent from stored records | Inspect next: Ingestion item failures, namespace, and index routing
- Observation: Stored evidence missing from candidates | Inspect next: Query rewriting, filters, embeddings, and search configuration
- Observation: Candidate present but reranked out | Inspect next: Reranker inputs, model version, and cutoff
- Observation: Ranked evidence absent from final context | Inspect next: Deduplication, context packing, truncation, and token budget
- Observation: Correct ID but obsolete text | Inspect next: Cached payload, stale revision, or incorrectly relabeled record
- Observation: Correct context but incorrect answer | Inspect next: Generation prompt, conflict resolution, or answer evaluator
Preserve artifacts needed to reproduce the regression
Retain query and identity scope, evaluation time, ordered results at each stage, source revisions, actual context, filters, model/configuration versions, ingestion outcomes, readiness observations, metric inputs, and failure reasons.
Protect traces as potentially sensitive data. Store only authorized content, redact unrelated secrets, restrict report access, and retain enough provenance to reproduce the failure without exposing confidential documents.
7. A Release Checklist for Retrieval and Document Updates
Before release, verify these six checks:
- Corpus and labels are versioned, reviewed, and separated into development and reserved release cases.
- Metric units, cutoffs, duplicate handling, and zero/N/A conventions are explicit.
- Required evidence reaches the exact final context supplied to the model.
- Updates and removals meet their deadlines; timeouts and late recovery remain visible.
- Permissions, tenant boundaries, and relevant cache states have independent checks.
- Reports preserve enough inputs, versions, traces, and failure details to reproduce the result.
Retrieval regression testing is strongest when relevance metrics and document-state assertions reinforce each other. One explains whether the system found useful evidence; the other verifies that the evidence is current, permitted, and consistent with the intended source state.
CONCLUSION
Effective RAG testing requires more than a single relevance score. By separating retrieval quality from answer quality, measuring precision and recall with explicit definitions, and independently verifying document updates, you can build a defensible regression suite. This approach ensures that your RAG pipeline not only finds useful evidence but also that the evidence is current, permitted, and correctly assembled into the final context.
Codoid’s LLM & AI Application Testing Services include evaluation datasets and retrieval-quality testing for teams building this coverage.
Frequently Asked Questions
-
Can context precision be high while recall is low?
Yes. In the worked example, A and B appear first, giving rank-sensitive precision of 1.00, while missing C reduces recall to 2/3. Inspect both completeness and ordering.
-
Can matching document IDs hide an update failure?
Yes. The local fixture deliberately returns old policy text under the expected current ID. ID recall remains perfect for that query, but the content-integrity assertion fails.
-
Does an empty search result prove that a document was deleted?
No. It establishes only that the query returned nothing. Verify the applicable removal contract through record inspection, complete enumeration where available, and application-path checks after readiness.
-
What is a good context precision or recall threshold?
Set thresholds from reviewed user tasks, critical evidence requirements, a qualified baseline, and tolerated risk. A task needing every mandatory fact warrants a stricter completeness rule than exploratory search. Treat unauthorized evidence as a separate failure, not a score trade-off.