Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions benchmarks/agent-env/run-negatives.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
#!/usr/bin/env bash
# Score one arm against the negative-question set, on an estate it already deployed.
#
# ./benchmarks/agent-env/run-negatives.sh chant
# ./benchmarks/agent-env/run-negatives.sh cdk cdk-neg-1
#
# These questions are not aws-bench's. They are ours, they live in
# benchmarks/tasks/ec2-multiregion-negatives, and they exist because the one
# question of that shape upstream already asks — which security groups are
# unused — is the only place on the board where every arm that keeps a state
# file scores zero. Pulumi, Terraform and CDK are 0 for 66 attempts between
# them; the agent holding nothing but the AWS CLI gets it 28% of the time.
#
# One question is an anecdote. The point of adding two more of the same shape is
# to find out whether that result is about the shape or about that question, and
# the honest version of that experiment requires publishing the answer either
# way — including chant scoring badly, which it does on the existing one about
# half the time.
#
# Written against the estate before any arm ran them, so nothing here is tuned
# to a result. Scored separately from the eight-question board rather than
# folded in: a different question set is a different experiment, and the arms'
# existing numbers are over eight questions, not ten.
set -euo pipefail

ARM="${1:?usage: run-negatives.sh <arm> [job-name]}"
JOB="${2:-${ARM}-neg-1}"

REPO="$(cd "$(dirname "$0")/../.." && pwd)"
EXPORTS="$HOME/.aws-bench/agent-env"
cd "$REPO"

export FLOCI_PORT="${FLOCI_PORT:-4566}"
export AWS_ENDPOINT_URL="http://localhost:${FLOCI_PORT}"
export AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test
export AWS_DEFAULT_REGION=us-east-1 AWS_REGION=us-east-1

# Same arm contract the scored runs use, read from one place so the two cannot
# drift. An arm named here that arms.py does not know fails loudly.
read -r SRC TARGET BRIEFING < <(python3 - "$ARM" <<'PY'
import sys
sys.path.insert(0, "benchmarks/agent-env")
from arms import ARMS
arm = ARMS.get(sys.argv[1])
if arm is None:
sys.exit(f"unknown arm: {sys.argv[1]}")
print(arm.source, arm.workdir, arm.briefing)
PY
)

AGENT_ENV=()
case "$ARM" in
pulumi) AGENT_ENV=(--ae PULUMI_CONFIG_PASSPHRASE=floci
--ae "PULUMI_BACKEND_URL=file://$TARGET") ;;
cdk) AGENT_ENV=(--ae CDK_DEFAULT_ACCOUNT=000000000000
--ae CDK_DEFAULT_REGION=us-east-1) ;;
alchemy) AGENT_ENV=(--ae DO_NOT_TRACK=1) ;;
alchemy-effect) AGENT_ENV=(--ae DO_NOT_TRACK=1 --ae CI=1) ;;
esac

# No deploy and no wipe. This scores an estate that is already up, which is what
# makes the run cheap enough to be worth doing — but it means the estate has to
# be the one this arm deployed, so the gate that decides that runs first.
echo "==> [$ARM] estate: is the deployed estate intact?"
python3 benchmarks/agent-env/estate-check.py

echo "==> [$ARM] scoring the negative questions, k=3"
AWS_BENCH_EMULATOR=floci \
AWS_BENCH_EMULATOR_ENDPOINT="http://localhost:${FLOCI_PORT}" \
AWS_BENCH_EMULATOR_CONTAINER_ENDPOINT="http://host.docker.internal:${FLOCI_PORT}" \
AWSBENCH_SCAN_METHOD=fastscan \
uv run aws-bench run --env-name awsbench \
-p benchmarks/tasks/ec2-multiregion-negatives \
--scenario-path benchmarks/scenarios \
-a claude-code -m claude-haiku-4-5-20251001 -k 3 -n "${N_CONCURRENT:-6}" \
--job-name "$JOB" \
--extra-instruction-path "benchmarks/arms/$BRIEFING" \
--mounts '[
{"type":"bind","source":"'"$EXPORTS"'/toolchain","target":"/opt/awsbench-toolchain","read_only":true},
{"type":"bind","source":"'"$EXPORTS"'/workspaces/'"$ARM"'","target":"/opt/awsbench-arm","read_only":true}
]' \
--ak toolchain=/opt/awsbench-toolchain \
--ak arm_src=/opt/awsbench-arm \
--ak "arm_workdir=$TARGET" \
${AGENT_ENV[@]+"${AGENT_ENV[@]}"} \
--no-verify-env --yes

echo "==> [$ARM] audit: did the arm use its own tooling?"
python3 benchmarks/agent-env/audit.py "jobs/$JOB"
148 changes: 148 additions & 0 deletions benchmarks/scenarios/ec2-multiregion/cleanup/cleanup.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
#!/bin/bash
# Cleanup hook for ec2-multiregion — teardown counterpart to deploy/deploy.sh
# (cdk deploy --all -> cdk destroy --all). Runs in the scenario container before
# the framework's own teardown (trial.py::_run_cleanup), which is authoritative.
#
# This scenario's agent tasks create EC2 instances, route table associations, and
# other resources that are NOT CloudFormation-managed. If left in place they cause
# DependencyViolation errors during CDK destroy (subnets/VPCs/IGWs can't be deleted)
# and survive as orphans that fail the post-cleanup scan.
#
#
# Best-effort/idempotent: never fails the phase (exit 0 always).
set -uo pipefail

cd /app/cdk_app || { echo "[cleanup.sh] FATAL: /app/cdk_app missing" >&2; exit 0; }

export CDK_DEFAULT_ACCOUNT="$PRIMARY"
REGIONS="us-east-1 us-west-1 us-west-2"

echo "[cleanup.sh] ec2-multiregion teardown for account ${PRIMARY}"

# ===========================================================================
# Phase 1: Clean resources before CDK destroy
# ===========================================================================
# Agent tasks launch EC2 instances (creating VolumeAttachments), associate
# subnets to route tables (creating SubnetRouteTableAssociations), and may
# create/attach internet gateways. These block VPC/subnet deletion.
cleanup_residuals() {
for region in $REGIONS; do
echo "[cleanup.sh] [Phase 1] Cleaning residuals in ${region}..."

# 1a. Terminate all EC2 instances (releases VolumeAttachments and ENIs)
instance_ids=$(aws ec2 describe-instances --profile PRIMARY --region "$region" \
--filters "Name=instance-state-name,Values=pending,running,stopping,stopped" \
--query 'Reservations[].Instances[].InstanceId' --output text 2>/dev/null || true)
if [ -n "$instance_ids" ] && [ "$instance_ids" != "None" ]; then
echo "[cleanup.sh] Terminating instances in ${region}: ${instance_ids}"
aws ec2 terminate-instances --profile PRIMARY --region "$region" \
--instance-ids $instance_ids >/dev/null 2>&1 || true
aws ec2 wait instance-terminated --profile PRIMARY --region "$region" \
--instance-ids $instance_ids 2>/dev/null || true
fi

# 1b. Disassociate non-main route table associations
# (removes SubnetRouteTableAssociations created by the agent)
assoc_ids=$(aws ec2 describe-route-tables --profile PRIMARY --region "$region" \
--query 'RouteTables[].Associations[?!Main].RouteTableAssociationId' \
--output text 2>/dev/null || true)
if [ -n "$assoc_ids" ] && [ "$assoc_ids" != "None" ]; then
for assoc in $assoc_ids; do
echo "[cleanup.sh] Disassociating route table association: ${assoc}"
aws ec2 disassociate-route-table --profile PRIMARY --region "$region" \
--association-id "$assoc" 2>/dev/null || true
done
fi

# 1c. Detach internet gateways (safety net for IGWs left attached)
for igw in $(aws ec2 describe-internet-gateways --profile PRIMARY --region "$region" \
--query 'InternetGateways[].InternetGatewayId' --output text 2>/dev/null || true); do
[ -z "$igw" ] || [ "$igw" = "None" ] && continue
vpc_id=$(aws ec2 describe-internet-gateways --profile PRIMARY --region "$region" \
--internet-gateway-ids "$igw" \
--query 'InternetGateways[0].Attachments[0].VpcId' --output text 2>/dev/null || true)
if [ -n "$vpc_id" ] && [ "$vpc_id" != "None" ]; then
echo "[cleanup.sh] Detaching IGW ${igw} from VPC ${vpc_id}"
aws ec2 detach-internet-gateway --profile PRIMARY --region "$region" \
--internet-gateway-id "$igw" --vpc-id "$vpc_id" 2>/dev/null || true
fi
done
done
}
cleanup_residuals || echo "[cleanup.sh] Phase 1 incomplete; continuing"

# ===========================================================================
# Phase 2: CDK destroy
# ===========================================================================
npx cdk destroy --profile PRIMARY --all --force --concurrency 10 || \
echo "[cleanup.sh] cdk destroy incomplete; framework cleanup will finish teardown"

# ===========================================================================
# Phase 3: Post-destroy residual cleanup
# ===========================================================================
# CDK's CustomVpcRestrictDefault Lambda leaves behind a CloudWatch log group.
cleanup_post_destroy_residuals() {
for region in $REGIONS; do
echo "[cleanup.sh] [Phase 3] Cleaning post-destroy residuals in ${region}..."

# 3a. Delete Lambda log groups from CDK custom resources
log_groups=$(aws logs describe-log-groups --profile PRIMARY --region "$region" \
--log-group-name-prefix "/aws/lambda/ec2-multiregion" \
--query 'logGroups[].logGroupName' --output text 2>/dev/null || true)
if [ -n "$log_groups" ] && [ "$log_groups" != "None" ]; then
for lg in $log_groups; do
echo "[cleanup.sh] Deleting log group: ${lg}"
aws logs delete-log-group --profile PRIMARY --region "$region" \
--log-group-name "$lg" 2>/dev/null || true
done
fi
done
}
cleanup_post_destroy_residuals || echo "[cleanup.sh] Phase 3 incomplete; continuing"

# ===========================================================================
# Phase 4: Remove orphaned CDK bootstrap buckets
# ===========================================================================
# When CDKToolkit is deleted or in a bad state but its S3 bucket persists
# (non-empty versioned bucket), future bootstraps fail with "Resource already
# exists". Always remove CDK assets buckets — the deploy will re-bootstrap.
cleanup_orphaned_cdk_buckets() {
for region in $REGIONS; do
# Find CDK assets buckets for this account+region
buckets=$(aws s3api list-buckets --profile PRIMARY \
--query "Buckets[?starts_with(Name, 'cdk-') && contains(Name, '${region}')].Name" \
--output text 2>/dev/null || true)

[ -z "$buckets" ] || [ "$buckets" = "None" ] && continue

for bucket in $buckets; do
# Only target CDK bootstrap assets buckets (pattern: cdk-QUALIFIER-assets-ACCOUNT-REGION)
echo "$bucket" | grep -q "assets" || continue

echo "[cleanup.sh] [Phase 4] Deleting CDK bucket: ${bucket} in ${region}"

# Empty current objects
aws s3 rm "s3://${bucket}" --recursive --profile PRIMARY --region "$region" 2>/dev/null || true

# Delete versioned objects
aws s3api list-object-versions --bucket "$bucket" --region "$region" --profile PRIMARY \
--query '{Objects: Versions[].{Key:Key,VersionId:VersionId}}' --output json 2>/dev/null | \
aws s3api delete-objects --bucket "$bucket" --region "$region" --profile PRIMARY \
--delete file:///dev/stdin 2>/dev/null || true

# Delete markers
aws s3api list-object-versions --bucket "$bucket" --region "$region" --profile PRIMARY \
--query '{Objects: DeleteMarkers[].{Key:Key,VersionId:VersionId}}' --output json 2>/dev/null | \
aws s3api delete-objects --bucket "$bucket" --region "$region" --profile PRIMARY \
--delete file:///dev/stdin 2>/dev/null || true

# Delete bucket
aws s3api delete-bucket --bucket "$bucket" --region "$region" --profile PRIMARY 2>/dev/null || \
echo "[cleanup.sh] Could not delete bucket ${bucket} (may still have objects)"
done
done
}
cleanup_orphaned_cdk_buckets || echo "[cleanup.sh] Phase 4 incomplete; continuing"

echo "[cleanup.sh] Done."
exit 0
30 changes: 30 additions & 0 deletions benchmarks/scenarios/ec2-multiregion/deploy/deploy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/bin/bash
set -euo pipefail

cd /app/cdk_app

# aws-bench has written ~/.aws/config with one profile per account tag.
# CDK assumes the role declared in the profile (auto-refreshing on expiry)
# when invoked with --profile.
export CDK_DEFAULT_ACCOUNT="$PRIMARY"

npm run build

# Bootstrapping is idempotent.
for region in us-east-1 us-west-1 us-west-2; do
npx cdk bootstrap --profile PRIMARY "aws://${PRIMARY}/${region}"
done

# One retry for transient create races: IAM propagation can lag role creation
# enough that Lambda CreateFunction fails ("The role defined for the function
# cannot be assumed by Lambda"), rolling the stack back to ROLLBACK_COMPLETE.
# On the retry, cdk deletes the creation-failed stack and recreates it;
# already-completed stacks are no-op'd.
cdk_deploy() {
if ! npx cdk deploy "$@"; then
echo "cdk deploy failed; retrying once for transient CFN/IAM races..." >&2
npx cdk deploy "$@"
fi
}

cdk_deploy --profile PRIMARY --all --require-approval never --concurrency 10
28 changes: 28 additions & 0 deletions benchmarks/scenarios/ec2-multiregion/scenario.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
schema_version = "1.0"

[scenario]
name = "ec2-multiregion"
description = "Small EC2-only environment used for end-to-end env-setup validation. Two stacks (ec2_ks84v1fh1, ec2_ls9fuhb52) plus QARolesStack across us-east-1, us-west-1, and us-west-2."
account_tags = ["PRIMARY"]
regions = ["us-east-1", "us-west-1", "us-west-2"]

[environment]
build_timeout_sec = 600.0
cpus = 2
memory_mb = 4096

[deploy]
timeout_sec = 1800.0

[verify]
timeout_sec = 120.0

[cleanup]
timeout_sec = 5400.0

[[quotas]]
account_tag = "PRIMARY"
region = "us-east-1"
service_code = "ec2"
quota_code = "L-1216C47A"
desired_value = 8
27 changes: 27 additions & 0 deletions benchmarks/scenarios/ec2-multiregion/scenario/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Slim Debian-based image with Node 24 pre-installed to run CDK (TypeScript)
FROM --platform=linux/amd64 public.ecr.aws/docker/library/node:24-slim

WORKDIR /app

# Build-time deps: curl + unzip for AWS CLI installer; git for CDK asset
# hashing. --no-install-recommends keeps the layer small.
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
ca-certificates \
curl \
git \
unzip \
&& rm -rf /var/lib/apt/lists/*

# AWS CLI v2 (CDK shells out to it for some asset / bootstrap operations).
RUN curl -fsSL "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" \
&& unzip -q awscliv2.zip \
&& ./aws/install \
&& rm -rf aws awscliv2.zip

# CDK CLI globally so deploy.sh can call `npx cdk`.
RUN npm install -g aws-cdk

# Copy the CDK app last so edits to TS source don't invalidate the layers above.
COPY cdk_app/ /app/cdk_app/
RUN cd /app/cdk_app && npm install
11 changes: 11 additions & 0 deletions benchmarks/scenarios/ec2-multiregion/scenario/cdk_app/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"app": "npx ts-node lib/app.ts",
"output": "cdk.out",
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import * as cdk from 'aws-cdk-lib';
import { EnvironmentProps } from './lib/shared';
import { EC2_ks84v1fh12 } from './stacks/ec2_ks84v1fh1';
import { EC2_ls9fuhb522 } from './stacks/ec2_ls9fuhb52';
import { QARolesStack } from './stacks/qa_roles_stack';

export function createEnvironment(app: cdk.App, envId: string, props: EnvironmentProps): void {
new QARolesStack(app, `${envId}-QARoles-us-east-1`, { env: { account: props.account, region: 'us-east-1' } });
new EC2_ks84v1fh12(app, `${envId}-EC2-ks84v1fh12-us-east-1`, { env: { account: props.account, region: 'us-east-1' } });
new EC2_ls9fuhb522(app, `${envId}-EC2-ls9fuhb522-us-west-1`, { env: { account: props.account, region: 'us-west-1' } });
new EC2_ls9fuhb522(app, `${envId}-EC2-ls9fuhb522-us-west-2`, { env: { account: props.account, region: 'us-west-2' } });
}
11 changes: 11 additions & 0 deletions benchmarks/scenarios/ec2-multiregion/scenario/cdk_app/lib/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import * as cdk from 'aws-cdk-lib';
import { createEnvironment } from '../environment';

const app = new cdk.App();

const account = process.env.CDK_DEFAULT_ACCOUNT;
if (!account) throw new Error('CDK_DEFAULT_ACCOUNT is not set.');

createEnvironment(app, 'ec2-multiregion', { account });

app.synth();
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as cdk from 'aws-cdk-lib';

export interface EnvironmentProps {
readonly account: string;
}

export class StackUtils {
static exportStack(stack: cdk.Stack, name: string, value: string, description?: string): cdk.CfnOutput {
return new cdk.CfnOutput(stack, name, {
value,
exportName: `${stack.stackName}-${name}`,
description,
});
}
}
Loading