
Don't Break Agents During Bedrock Model Upgrades
Build an automated regression testing pipeline for multi-agent systems on Amazon Bedrock AgentCore. A two-tier pattern scores end-to-end quality and each agent individually, catching regressions before a model upgrade reaches production.
Introduction
Multi-agent systems hide regressions that single-model tests catch easily. When agents interact through routing decisions and data handoffs, one agent's regression can be masked by another compensating. Consider a multi-tenant financial analysis platform where a model upgrade causes the research agent to retrieve less relevant documents; the analysis agent compensates from incomplete data, end-to-end quality looks acceptable, and the regression stays invisible without per-agent visibility.
This post describes a two-tier evaluation pipeline built on Amazon Bedrock AgentCore . Tier 1 scores end-to-end task quality. Tier 2 scores each agent individually. Together they catch both system-level and agent-level regressions before a model upgrade reaches production.
A companion repository provides the complete deployable pipeline — Terraform infrastructure, Lambda handlers, Step Functions state machine, and sample datasets. Deploy with
terraform apply (or tofu apply for OpenTofu ) and trigger your first regression run in under an hour.What you will learn
- How two-tier evaluation catches regressions that end-to-end testing alone misses
- How to clone agents with different foundation models for A/B comparison
- How deterministic-first evaluation reduces cost by skipping the LLM judge when simple checks suffice
- How to gate production promotion on human approval with Step Functions
Solution overview

- Trigger. An Amazon EventBridge rule watches the S3
config/prefix for uploads and starts the state machine.
- Agent Factory. Creates two Amazon Bedrock AgentCore Runtimes from the same container image — one with the baseline model, one with the candidate. Both reach
READYbefore testing begins.
- Test Case Runner. Invokes both Runtimes with a shared
runtimeSessionIdper test case. Strands emits OpenTelemetry spans toaws/spansin Amazon CloudWatch ; the Runner queries by session ID and groups spans byagent.name.
- Per-Agent Evaluator. Scores each specialist's trace segment. Deterministic checks run first — failures escalate to AgentCore's
EvaluateAPI for LLM judge scoring.
- End-to-End Evaluator. Calls
CreateEvaluationJobin Amazon Bedrock model evaluation, scoring final outputs with built-in correctness, completeness, faithfulness, and helpfulness metrics.
- Report Generator. Aggregates scores into a comparison table with deltas and pass/fail verdicts.
- Approval Gate. Step Functions pauses on
.waitForTaskToken. Amazon SNS delivers the report and approve/reject URLs to reviewers.
- Promoter. Calls
UpdateAgentRuntimeEndpointto atomically repoint the production endpoint at the candidate version.
The pipeline uses Amazon Bedrock AgentCore Identity for workload identity, Amazon Bedrock AgentCore Memory for conversation context, and Amazon Bedrock AgentCore Gateway for Model Context Protocol (MCP) tool routing. Baseline and candidate run at temperature 0.0 to reduce output drift.
Prerequisites
Skill level: Intermediate — Python and AWS experience required. Time: Under 1 hour to deploy, about 30 minutes per run.
- An AWS account with Amazon Bedrock access in a US region supporting Anthropic Claude models
- Model access enabled for baseline (
anthropic.claude-sonnet-4-5), candidate (anthropic.claude-sonnet-4-6), and judge (anthropic.claude-opus-4-6)
- Docker for building the agent container image
- AWS CLI v2 and Python 3.13
- CloudWatch Transaction Search enabled (CloudWatch console → Application Signals → Settings)
- A multi-agent system deployed as an AgentCore Runtime — or use the sample financial analysis swarm included in the repository
Deploy the pipeline
git clone https://github.com/alexkro-code/sample-agentcore-model-upgrade-test.git
cd sample-agentcore-model-upgrade-test
cp infra/terraform.tfvars.example infra/terraform.tfvars
# Edit terraform.tfvars with your account values
cd infra && terraform init && terraform applyThis creates the S3 bucket, six Lambda functions, the Step Functions state machine, EventBridge rule, SNS topic, ECR repository, IAM roles, and CloudWatch log groups. For OpenTofu, substitute
tofu for terraform .Next, build and push the agent container, upload datasets, and trigger your first run:
cd ../app && bash build_and_push.sh
cd ..
BUCKET=$(cd infra && terraform output -raw bucket_name)
aws s3 cp datasets/e2e-cases.jsonl "s3://$BUCKET/datasets/"
aws s3 cp datasets/per-agent-cases.jsonl "s3://$BUCKET/datasets/"
aws s3 cp configs/sample-config.json "s3://$BUCKET/config/regression-config.json"The config upload triggers the pipeline through EventBridge.
The multi-agent system under test
AnyCompany's financial analysis platform runs four specialist subagents plus a supervisor in one AgentCore Runtime container, wired with the Strands Agents SDK via Agents-as-Tools.
# supervisor.py -- container entry point
import os
from strands import Agent
from strands.models import BedrockModel
from bedrock_agentcore.runtime import BedrockAgentCoreApp
def _model(role):
model_id = os.environ.get(f"MODEL_ID_{role.upper()}", os.environ["MODEL_ID"])
return BedrockModel(model_id=model_id, temperature=0.0)
DATA_RETRIEVAL = Agent(name="data_retrieval", model=_model("data_retrieval"),
system_prompt="Query financial databases for the requested data.")
RESEARCH = Agent(name="research", model=_model("research"),
system_prompt="Search the knowledge base for analyst reports.")
ANALYSIS = Agent(name="analysis", model=_model("analysis"),
system_prompt="Synthesize data from other agents into an analysis.")
COMPLIANCE = Agent(name="compliance", model=_model("compliance"),
system_prompt="Enforce tenant policies and block restricted content.")
SUPERVISOR = Agent(
name="supervisor", model=_model("supervisor"),
system_prompt=("You coordinate financial analysis requests. Call the "
"data_retrieval, research, analysis, and compliance tools."),
tools=[
DATA_RETRIEVAL.as_tool(name="data_retrieval", description="Query financial data."),
RESEARCH.as_tool(name="research", description="Search analyst reports."),
ANALYSIS.as_tool(name="analysis", description="Synthesize findings."),
COMPLIANCE.as_tool(name="compliance", description="Check tenant policy."),
],
)
app = BedrockAgentCoreApp()
@app.entrypoint
def handler(payload):
return {"output": str(SUPERVISOR(payload["input"]))}
if __name__ == "__main__":
app.run()The Agent Factory creates two Runtimes from this image — same code, different
MODEL_ID environment variable. The opentelemetry-instrument wrapper in the Dockerfile causes Strands to emit spans tagged with agent.name and session.id , which the Test Case Runner uses for per-agent segmentation.Pipeline configuration
A JSON file in S3 defines the regression run — models to compare, thresholds, and dataset locations.
{
"run_id": "regression-2026-04-27-001",
"datasets": {
"e2e": "s3://amzn-s3-demo-bucket-agent-regression/datasets/e2e-cases.jsonl",
"per_agent": "s3://amzn-s3-demo-bucket-agent-regression/datasets/per-agent-cases.jsonl"
},
"image_uri": "123456789012.dkr.ecr.us-east-1.amazonaws.com/agent-swarm:v1",
"production_runtime_arn": "arn:aws:bedrock-agentcore:us-east-1:123456789012:agent-runtime/agent-swarm-prod",
"production_endpoint_name": "production",
"runtime_role_arn": "arn:aws:iam::123456789012:role/agent-swarm-runtime-role",
"baseline_model": "anthropic.claude-sonnet-4-5",
"candidate_model": "anthropic.claude-sonnet-4-6",
"judge_model": "anthropic.claude-opus-4-6",
"thresholds": {
"e2e_correctness": 0.85,
"per_agent_floor": 0.80,
"max_regression_delta": 0.10
},
"runs_per_config": 3,
"output_prefix": "s3://amzn-s3-demo-bucket-agent-regression/results/"
}Uploading this file to the
config/ prefix triggers a new run. thresholds sets the minimum scores and maximum tolerated regression between baseline and candidate. runs_per_config controls repetitions — agent inference is nondeterministic even at temperature 0.0, so multiple runs produce more reliable signals.Two-tier evaluation
This is the core architectural pattern. Two evaluation tiers compose into one signal — end-to-end catches system regressions, per-agent isolates which agent regressed and why.
How it works
Tier 1 (End-to-End) uses Amazon Bedrock model evaluation. A batch job scores final outputs against reference answers with built-in correctness, completeness, faithfulness, and helpfulness metrics. This catches "the system got worse" but cannot tell you which agent caused it.
Tier 2 (Per-Agent) uses deterministic checks first, escalating to AgentCore's
Evaluate API only when checks fail. This isolates the root cause — which agent regressed on which dimension.The deterministic-first pattern is the key cost optimization. Simple checks (did the supervisor route to the right agents? did data retrieval call the correct tool? did the guardrail fire when expected?) are free and fast. The LLM judge only fires when these fail, skipping 30–50 percent of expensive judge calls in practice.
Deterministic checks per role
import boto3, statistics
from botocore.config import Config
_AGENTCORE = boto3.client("bedrock-agentcore",
config=Config(retries={"max_attempts": 5, "mode": "adaptive"}))
E2E_THRESHOLD = 0.85
PER_AGENT_FLOOR = 0.80
MAX_REGRESSION_DELTA = 0.10
DETERMINISTIC_CHECKS = {
"supervisor": {"routing_correctness": lambda ev, exp:
set(exp.get("expected_agents", [])).issubset(
{e.get("tool_name") for e in ev if e.get("type") == "tool_call"})},
"data_retrieval": {"tool_call_accuracy": lambda ev, exp:
any(e.get("tool_name") == exp.get("expected_tool_name")
for e in ev if e.get("type") == "tool_call")},
"research": {"rag_faithfulness": lambda ev, exp:
any(e.get("type") == "kb_lookup" for e in ev) and
any(e.get("knowledge_base_id") == exp.get("expected_kb_id")
for e in ev if e.get("type") == "kb_lookup")},
"analysis": {"synthesis_quality": lambda ev, exp:
sum(e.get("output_tokens", 0) for e in ev
if e.get("type") == "model_call") >= exp.get("min_output_tokens", 200)},
"compliance": {"policy_adherence": lambda ev, exp:
exp.get("should_block", False) ==
any(e.get("type") == "guardrail" for e in ev)},
}
def evaluate_agent(agent_role, agent_events, expected, session_spans=None):
results = {}
for metric, check in DETERMINISTIC_CHECKS.get(agent_role, {}).items():
try:
passed = check(agent_events, expected)
results[metric] = {"score": 1.0 if passed else 0.0,
"method": "deterministic", "passed": passed}
except Exception as exc:
results[metric] = {"score": 0.0, "method": "deterministic",
"passed": False, "error": str(exc)}
failed = [m for m, r in results.items() if not r["passed"]]
if failed and session_spans:
try:
resp = _AGENTCORE.evaluate(
evaluatorId="Builtin.Correctness",
evaluationInput={"sessionSpans": session_spans},
evaluationTarget={"traceIds": [s.get("traceId", "")
for s in session_spans
if s.get("attributes", {}).get("agent.name") == agent_role]},
evaluationReferenceInputs=[{"expectedResponse":
{"text": expected.get("expected_output", "")}}],
)
for m in failed:
results[m]["llm_score"] = resp.get("value", 0.0)
results[m]["llm_label"] = resp.get("label", "")
results[m]["llm_explanation"] = resp.get("explanation", "")
except Exception as exc:
for m in failed:
results[m]["llm_error"] = str(exc)
scores = [r["score"] for r in results.values()]
overall = statistics.mean(scores) if scores else 0.0
return {"agent_role": agent_role, "metrics": results,
"overall_score": overall, "passed": overall >= PER_AGENT_FLOOR}Each role gets checks that match its responsibility:
- Supervisor — were the expected specialists invoked?
- Data retrieval — was the correct tool called with correct parameters?
- Research — was the right knowledge base queried?
- Analysis — did the model produce sufficient synthesis (output tokens as proxy)?
- Compliance — did the guardrail fire when it should have (and not when it should not)?
When a deterministic check fails, the
Evaluate API fires with the agent's trace and a reference answer. The LLM judge returns a score, label, and explanation — telling the team not just that something failed, but why.Full implementation:functions/per_agent_evaluator/includes role-specific rubrics inrubrics.pyand the complete handler with S3 I/O.
Fault isolation in practice
When an E2E score drops 13 percent, per-agent scores surface the likely cause.
Table 1: Per-agent fault isolation. The research agent's faithfulness drop drives the E2E decline.
Metric | Baseline | Candidate | Delta | Verdict |
|---|---|---|---|---|
E2E Correctness | 0.91 | 0.78 | -0.13 | FAIL |
Supervisor Routing | 1.00 | 1.00 | 0.00 | PASS |
Research Faithfulness | 0.92 | 0.78 | -0.14 | FAIL |
Analysis Quality | 0.88 | 0.87 | -0.01 | PASS |
Compliance Adherence | 0.95 | 0.94 | -0.01 | PASS |
The team targets a fix on the research agent rather than retesting the entire system. This is the value of two-tier evaluation — without per-agent visibility, the team would only know "the system got worse."
Compliance canary. In regulated industries, run compliance evaluation first and skip remaining steps if policy adherence drops belowPER_AGENT_FLOOR— the fast-fail pattern avoids wasting compute on a candidate that cannot pass.
Test dataset design
The pipeline uses two dataset formats. The companion repository includes 10 cases of each type in
datasets/ .End-to-end test cases validate the full system — input, expected output, and which agents should participate. Format: one JSON record per line (JSONL), matching Amazon Bedrock model evaluation requirements.
Required fields:
task_id , input , expected_output , expected_agents . Optional: tenant_id for multi-tenant scenarios.Per-agent golden cases target specific agent behaviors with fine-grained assertions.
Required fields vary by role:
- Supervisor —
expected_agents(which specialists should be routed to)
- Data retrieval —
expected_tool_name,expected_params
- Research —
expected_kb_id(which knowledge base should be queried)
- Analysis —
min_output_tokens(synthesis depth proxy)
- Compliance —
should_block(true/false for policy enforcement)
Start with 10–20 hand-crafted cases covering golden-path behavior and known edge cases. Expand to 100+ for production gates. Include adversarial cases close to but not crossing policy thresholds.
Approval gate and promotion
When evaluation completes and all metrics pass, Step Functions pauses for human review. The state machine uses JSONata — the modern Step Functions query language.
{
"QueryLanguage": "JSONata",
"StartAt": "AwaitApproval",
"States": {
"AwaitApproval": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish.waitForTaskToken",
"Arguments": {
"TopicArn": "arn:aws:sns:us-east-1:123456789012:agent-regression-approvals",
"Message": {
"report_url": "{% $states.input.report_s3_url %}",
"run_id": "{% $states.input.run_id %}",
"verdict": "{% $states.input.overall_verdict %}",
"task_token": "{% $states.context.Task.Token %}"
}
},
"Output": {
"approval_status": "{% $states.result.status %}",
"reviewer": "{% $states.result.reviewer %}"
},
"Next": "PromoteCandidate"
},
"PromoteCandidate": {
"Type": "Task",
"Resource": "arn:aws:lambda:us-east-1:123456789012:function:agent-promoter",
"Arguments": {
"run_id": "{% $states.input.run_id %}",
"candidate_config": "{% $states.input.candidate_config %}"
},
"End": true
}
}
}The reviewer receives an SNS notification with the report link and per-agent scores. Approval triggers the Promoter, which calls
UpdateAgentRuntimeEndpoint to atomically switch the production endpoint to the candidate version. Rejection archives the run — no production change occurs.If all metrics fail the threshold check, the state machine skips the approval gate entirely and archives the run (fast-fail).
Full implementation:statemachine/regression_pipeline.asl.jsoncontains the complete 10-state machine including parallel evaluation branches and the verdict-based choice state.
Verification
Deploy the pipeline, create a configuration with 5–10 test cases, and upload to the
config/ prefix. Confirm:- Step Functions execution reaches the approval gate (check the console or
aws stepfunctions describe-execution)
- Baseline and candidate spans appear in S3 under
results/{run_id}/traces.json
- The report shows a comparison table with deltas and verdicts
Table 2: Example regression report — all metrics passing.
Metric | Baseline | Candidate | Delta | Threshold | Verdict |
|---|---|---|---|---|---|
E2E Correctness | 0.91 | 0.89 | -0.02 | 0.85 | PASS |
E2E Completeness | 0.88 | 0.86 | -0.02 | 0.80 | PASS |
Supervisor Routing | 1.00 | 1.00 | 0.00 | 0.95 | PASS |
Research Faithfulness | 0.92 | 0.90 | -0.02 | 0.85 | PASS |
Compliance Adherence | 0.95 | 0.93 | -0.02 | 0.90 | PASS |
Cost Delta | -- | -- | +$12.40 | -- | INFO |
Overall | -- | -- | -- | -- | PASS |
Troubleshooting
- EventBridge not triggering. Verify S3 event notifications are enabled (
eventbridge = truein the Terraform config).
- Runtime stuck in CREATING. Check
/aws/bedrock-agentcore/runtimes/{agent_runtime_id}for container startup errors.
- Missing spans. Verify Transaction Search is enabled and the Dockerfile CMD wraps the entry point with
opentelemetry-instrument.
- Evaluation job timeouts. Allow up to 60 minutes for large datasets; poll with
GetEvaluationJob.
Cost model
A run with 4 subagents, 10 E2E cases, 10 per-agent cases, and 3 repetitions costs approximately $50–100. Scale linearly with dataset size.
Table 3: Estimated cost breakdown for the sample configuration.
Component | Estimated Cost |
|---|---|
Baseline + Candidate inference | ~$24 |
Per-agent evaluation (deterministic + LLM judge) | ~$16 |
E2E evaluation job (Opus judge) | ~$15 |
Pipeline infrastructure | ~$5 |
Total | ~$60 |
Four patterns reduce cost: deterministic-first evaluation (skips 30–50 percent of judge calls), batch inference (about 50 percent cheaper for scheduled runs), skipping per-agent judging when E2E passes cleanly, and AgentCore built-in evaluators (about $0.0024 per 1,000 input tokens). For current rates, see Amazon Bedrock pricing and Amazon Bedrock AgentCore pricing .
Clean up
Remove all pipeline resources:
cd infra
terraform destroyThis deletes Runtimes, Lambda functions, the state machine, EventBridge rules, SNS topic, IAM roles, the ECR repository, and CloudWatch log groups. Your production Runtime and endpoint are not affected — they are referenced, not managed, by this stack.
To also delete the S3 bucket data (datasets, traces, reports), empty the bucket first:
BUCKET=$(terraform output -raw bucket_name)
aws s3 rm "s3://$BUCKET" --recursive
terraform destroyConclusion
This post described how to automate regression testing for multi-agent systems on Amazon Bedrock AgentCore. The two-tier evaluation pattern — end-to-end scoring plus per-agent deterministic checks with LLM judge escalation — catches regressions and isolates which agent caused them.
Deploy the companion repository to try this pattern with the sample financial analysis swarm, then swap in your own agents and rubrics. Start with 10–20 test cases per tier and expand as you gain confidence in your thresholds.
Three extensions build naturally on top: LLM-generated test cases for broader coverage, AgentCore Memory persistence testing across model swaps, and AgentCore Runtime shadow testing against production traffic.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article