Build a SWE Agent

Updated at:

This topic uses a real SWE-bench task as an example to describe how to run the full loop of a SWE agent fixing a defect, producing a patch, and checking whether the defect is fixed on FC Agent Sandbox.

Background information

A SWE agent (software engineering agent) automatically completes development tasks such as fixing issues and generating pull requests (PRs): you give it the defect description of a real repository, it reads code, modifies files, and runs tests in a sandbox, and then produces a patch. The industry-standard way to evaluate how well it performs is to run a benchmark such as SWE-bench. Each task provides an image that contains the repository as it was, and test cases determine whether the patch really fixes the issue.

This topic uses a real SWE-bench-style task as an example to show how to run the full loop on FC Agent Sandbox: the agent fixes a defect, produces a patch, and grading determines whether the issue is fixed. The topic then extends the loop to batch evaluation and describes how to plug in images of your own repositories. The code samples can be copied and run as is.

Use cases

  • Your team needs a reproducible evaluation base to compare the defect-fixing capability of different models and different prompts on real repository defects under unified criteria.

  • The agent executes code and tests in the repository, so a strongly isolated environment is required to avoid affecting local or continuous integration (CI) machines.

  • A batch evaluation run covers dozens or hundreds of instances that must be isolated per instance and recycled immediately after the run, with controllable cost.

  • You need private evaluation datasets for in-house repositories while reusing the same agent and grading pipeline.

Prerequisites

  • You have activated FC Agent Sandbox, and obtained the E2B_API_KEY for the target region. For more information, see Create an API Key and Use FC Agent Sandbox with the SDK. This topic uses the China (Shanghai) region as an example, where the endpoint domain is cn-shanghai.e2b.fc.aliyuncs.com (the SDK derives the API endpoint https://api.cn-shanghai.e2b.fc.aliyuncs.com).

    The API key is bound to a region. Using it across regions returns 401.
  • A valid model API key (this topic uses an OpenAI-compatible endpoint).

  • Python 3.10 or later.

How it works

The solution is divided into an orchestration layer, a sandbox layer, and an image layer: models and credentials exist only in the orchestration layer, and the sandbox only runs bash. The responsibilities and data flow of each layer are as follows:

image

Step 1: Install dependencies and configure credentials

Create a project directory, install dependencies, and configure FC Agent Sandbox and model credentials:

mkdir swe-demo && cd swe-demo
python -m venv .venv
.venv/bin/pip install pyyaml \
  "mini-swe-agent[e2b] @ git+https://github.com/aliyun-fc/mini-swe-agent@v2.4.6-fc.1"

# Sandbox: the SDK derives the endpoint from the domain (https://api.<domain>), so api_url is not configured separately
export E2B_API_KEY="<YOUR-E2B-API-KEY>"
export E2B_DOMAIN="cn-shanghai.e2b.fc.aliyuncs.com"
# Model credentials are used only in the orchestration layer and never enter the sandbox. The variable name is
# determined by the `openai/` prefix of model_name below; the value is the key of your compatible endpoint. Only the litellm standard variables let the single-task script and the batch entry share one set of credentials
export OPENAI_API_KEY="<YOUR-MODEL-API-KEY>"
export MSWEA_CONFIGURED=true MSWEA_SILENT_STARTUP=1

After the dependencies are installed, verify the installation:

.venv/bin/python -c "import minisweagent; print(minisweagent.__version__)"
# 2.4.6+fc.1
If the network is restricted, run git clone https://github.com/aliyun-fc/mini-swe-agent, git checkout v2.4.6-fc.1, and then run pip install -e ".[e2b]".

Step 2: Configure the execution environment (built-in e2b)

The agent loop uses the community-standard implementation mini-SWE-agent, and the prompts and submission protocol follow the official ones. Only the execution backend is replaced with FC Agent Sandbox. The version installed in the previous step has e2b built in, so one line of configuration is enough:

environment:
  environment_class: e2b

When it uses an image for the first time, it registers the image as a persistent template (Template.build), and hits the cache afterwards. Each instance starts a sandbox, commands run through commands.run, and patches are returned over the official protocol.

FC Agent Sandbox differs from local docker in five ways, and the built-in class handles all of them. You run into these when implementing your own execution backend or troubleshooting failures:

Difference

Consequence if not handled

Handling

The sandbox does not create the working directory automatically (docker run -w does)

Fails at the process creation stage, with no exit code, so every command is recorded as an infrastructure exception

Run mkdir -p <cwd> at startup. Probe once and warn first, otherwise a misconfigured working directory is silently created as an empty directory, the agent submits an empty patch, and grading gives 0; require_existing_cwd: true turns this into a fail-fast at startup

git refuses to operate when the owner does not match the running user

dubious ownership, git diff produces no output, which means no patch can be submitted

Run git config --global --add safe.directory <cwd>

Non-zero exits are thrown as exceptions by the SDK

Test failures or grep with no match are normal signals that get treated as execution failures

Convert to returncode and return the output as is

Timeout exceptions carry no stdout/stderr

Thousands of lines produced before the timeout are lost, and slow tests in large repositories are the most likely to time out

Collect output in streams. After a timeout, return the partial output and mark it as timed out

The repository is owned by root, and images usually have no sudo

Non-root users cannot even write files

run_as_user: root (consistent with the official docker harness)

Template building has three more points, which matter especially when you integrate your own images or implement the backend yourself:

  • The template name is determined by both the image address and the specification. The built-in implementation hashes the image address plus cpu_count/memory_mb. If the template name excludes the specification, changing the memory still yields a template of the old specification.

  • Concurrent first builds of the same image must be mutually exclusive. Otherwise every worker finds the template missing and tries to create the same name. In a test, 3 of 4 concurrent builds failed (409 ... resource conflict), and each failed build left a template record behind.

  • Failed build names do not self-heal. The alias endpoint returns no status, so the existence check keeps reporting "exists", while starting a sandbox is rejected and rebuilding reports "build allowed only once". Recovery must branch on the real status: if another build is in progress, wait; error or missing, delete and rebuild. Deletion is asynchronous, so wait for the alias to disappear. The name comes from the content, so do not increment a version number manually.

Step 3: Configure the image and working directory

The example configuration demo.yaml is as follows:

# demo.yaml -- layered on top of the official mini-SWE-agent swebench.yaml; prompts and submission protocol follow the official ones
environment:
  environment_class: e2b
  image: fc-e2b-registry.cn-shanghai.cr.aliyuncs.com/swebench/sweb.eval.x86_64:envd_v_0_0_41_getmoto_s_moto-7365-latest_202607231510
  cwd: /testbed          # Must change together with the dataset; see What to change when switching datasets
  require_existing_cwd: true   # Fail at startup when the working directory is not in the image, instead of creating an empty directory and silently scoring 0
  run_as_user: root
  timeout: 120
  memory_mb: 8192        # Evaluation images are large, the default 2048 cannot start
model:
  model_name: openai/<YOUR-MODEL>
  model_kwargs:
    api_base: <OpenAI-compatible endpoint>
    temperature: 0.0
  cost_tracking: ignore_errors   # Models on self-hosted endpoints are not in the price table, otherwise cost calculation raises an error
agent:
  # Keep 250 from the official swebench.yaml. When it was lowered to 40, 3 of 4 instances hit the cap,
  # and one of them had already fixed the issue but could not submit, so it scored 0. A lower cap underestimates scores
  step_limit: 250
  # Step limits do not control time: an instance ran for 35 minutes without finishing, holding a concurrency
  # slot and a billable sandbox. The field name is wall_time_limit_seconds; a typo raises no error and is silently ignored
  wall_time_limit_seconds: 1800
  cost_limit: 0     # Models on self-hosted endpoints are not in the price table, so a cost cap is meaningless

require_existing_cwd is disabled by default (consistent with upstream), but the batch entry mini-extra swebench enables it automatically when running on e2b; the single-task script must set it explicitly. Repository-based datasets should always enable it, because it is the only safety net against this kind of silent failure.

Step 4: Drive the agent (run.py)

The driver script run.py reads the problem description, runs the agent, and outputs the patch:

# run.py
import argparse, json
from pathlib import Path

import yaml
from minisweagent.agents.default import DefaultAgent
from minisweagent.config import builtin_config_dir
from minisweagent.environments import get_environment
from minisweagent.models.litellm_model import LitellmModel
from minisweagent.utils.serialize import recursive_merge

p = argparse.ArgumentParser()
p.add_argument("-c", "--config", type=Path, default=Path("demo.yaml"))
p.add_argument("-t", "--task", type=Path, default=Path("task.md"))
p.add_argument("-o", "--output", type=Path, default=Path("out.patch"))
p.add_argument("--traj", type=Path, default=Path("traj.json"))
a = p.parse_args()

# The official swebench.yaml provides the prompts and submission protocol; the local yaml only overrides the image, model, and limits
official = yaml.safe_load((builtin_config_dir / "benchmarks" / "swebench.yaml").read_text())
cfg = recursive_merge(official, yaml.safe_load(a.config.read_text()))

env = get_environment(cfg["environment"])      # environment_class: e2b

# Do not inject api_key here: let litellm resolve it from the standard environment variable (`openai/` prefix -> OPENAI_API_KEY).
# This way the script and the official batch entry share one set of credentials. A custom variable that only this script
# recognizes leaves the batch run ending with Missing credentials.
agent = DefaultAgent(LitellmModel(**cfg["model"]), env,
                     **recursive_merge(cfg.get("agent", {}), {"output_path": a.traj}))
try:
    result = agent.run(a.task.read_text())
finally:
    env.cleanup()

patch = result.get("submission") or ""
a.output.write_text(patch)
print(json.dumps({"exit_status": result.get("exit_status"), "patch_bytes": len(patch),
                  "model_calls": agent.n_calls, "template": env.template,
                  "sandbox_id": env.sandbox.sandbox_id},
                 ensure_ascii=False))
Do not drive batch evaluation with the interactive command line. The mini command asks for one interactive confirmation when the agent finishes, and -y does not skip it. In a non-interactive environment it ends with EOFError instead of submitting, so every patch is lost even though the agent had already solved the task. For scripting, drive DefaultAgent.

Step 5: Grade the patch (grade.py)

Grading uses the same criteria as the official SWE-bench: FAIL_TO_PASS all pass, and PASS_TO_PASS show no regression.

Grade in a fresh sandbox instead of reusing the agent working sandbox. After the agent finishes, that sandbox is no longer the original state: it may have extra packages installed (tests could pass by accident), modified test files or conftest.py, and leftover temporary files. Creating a new sandbox from the same immutable image clears these traces, but it does not guarantee that HEAD in the image is the base_commit of this task. Reset explicitly according to the metadata and verify before grading. The template is already cached, so a new sandbox takes only a few seconds.

# grade.py
import argparse, json, re, shlex
from collections import Counter
from pathlib import Path

import yaml
from minisweagent.config import builtin_config_dir
from minisweagent.environments import get_environment
from minisweagent.utils.serialize import recursive_merge

def as_list(v):
    if isinstance(v, str):
        try:
            return json.loads(v)
        except json.JSONDecodeError:
            return [v] if v else []
    return list(v or [])

def files_of(names):        # test case name -> file name
    # Keep only names with a file prefix (pytest node id). In multilingual datasets a case name may be a plain
    # case description or a test class name with no file prefix, and passing the whole string as a file name makes pytest report file not found.
    return {n.strip().strip("'\"").split("::")[0] for n in names
            if "::" in n or n.strip().strip("'\"").endswith(".py")}

def patched_files(diff):    # files touched by the patch
    return sorted(set(re.findall(r"^\+\+\+ b/(\S+)", diff, flags=re.M)))

p = argparse.ArgumentParser()
p.add_argument("--instance", type=Path, default=Path("instance.json"))
p.add_argument("--config", type=Path, default=Path("demo.yaml"))
p.add_argument("--patch", type=Path)
p.add_argument("--gold", action="store_true", help="Self-check with the gold patch shipped in the dataset")
a = p.parse_args()

inst = json.loads(a.instance.read_text())[0]
patch = inst["patch"] if a.gold else a.patch.read_text()
if not patch.strip():
    raise SystemExit(json.dumps({"resolved": False, "reason": "empty patch"}))

# Apply the same layering as run.py: image, working directory, and environment variables all come from one place (the acceptance script below reads it too).
# If the grader builds its own environment it drifts from the agent state -- keeping an old cwd after changing it is the typical case;
# and dropping BASH_ENV from the official config raises No module named pytest, which is misread as an unusable image.
cfg = recursive_merge(
    yaml.safe_load((builtin_config_dir / "benchmarks" / "swebench.yaml").read_text()),
    yaml.safe_load(a.config.read_text()),
)
f2p, p2p = as_list(inst["FAIL_TO_PASS"]), as_list(inst["PASS_TO_PASS"])

env = get_environment(dict(cfg["environment"], timeout=1800))
try:
    # 1) Do not trust the current HEAD in the image; reset to the only correct defect baseline from the task metadata
    base_commit = inst.get("base_commit") or ""
    assert base_commit, "metadata missing base_commit"
    out = env.execute({"command": f"git reset --hard {shlex.quote(base_commit)} && git clean -fd"},
                      timeout=300)
    assert out["returncode"] == 0, f"Cannot reset to base_commit: {out['output'][-200:]}"

    # 2) Apply the patch being graded; failing to apply it is also a result
    env.sandbox.files.write("/tmp/model.patch", patch)
    out = env.execute({"command": "git apply -v /tmp/model.patch"}, timeout=300)
    if out["returncode"] != 0:
        out = env.execute({"command": "patch -p1 -i /tmp/model.patch"}, timeout=300)
        assert out["returncode"] == 0, f"Cannot apply the patch: {out['output'][-200:]}"

    # 3) Restore the test files to the baseline first, then apply test_patch -- test content must not be tampered with by the agent
    tf = patched_files(inst["test_patch"])
    if tf:
        env.execute({"command": f"git checkout -- {' '.join(map(shlex.quote, tf))} || true"})
    env.sandbox.files.write("/tmp/test.patch", inst["test_patch"])
    out = env.execute({"command": "git apply -v /tmp/test.patch"}, timeout=300)
    assert out["returncode"] == 0, f"Cannot apply test_patch: {out['output'][-200:]}"

    # 4) Run the whole test file, then match names in the -rA report.
    # Do not pass case names as pytest command line arguments: parameterized names may contain spaces and parentheses, which report not found.
    # Do not tail-truncate the report either: large repositories produce thousands of lines, and truncation misses cases that passed.
    files = sorted(set(tf) | files_of(f2p + p2p))
    cmd = ("python -m pytest -rA --no-header -q " + " ".join(map(shlex.quote, files))
           + " > /tmp/res.log 2>&1; grep -E '^(PASSED|FAILED|ERROR) ' /tmp/res.log;"
             " echo '===TAIL==='; tail -3 /tmp/res.log")
    res = env.execute({"command": cmd}, timeout=1800)
    report = res["output"]

    # When the grading command produces nothing, do not treat it as "tests did not pass" -- that charges infrastructure failures to the model score.
    # Command timeouts under high concurrency are real and must be distinguished from test failures. Output already produced
    # before the timeout is kept, which shows whether it stalled during collection or on a specific case.
    if not report.strip() or res["returncode"] == -1:
        raise SystemExit(json.dumps({"resolved": False, "graded": False,
                                     "reason": "Grading incomplete (likely a timeout). Lower the concurrency and rerun",
                                     "exception_info": res.get("exception_info", ""),
                                     "partial_output": report.strip()[-300:]},
                                    ensure_ascii=False))

    passed = Counter(re.findall(r"^PASSED (\S+)", report, flags=re.M))

    def score(names):
        """Count exact matches directly; group the rest by truncated header, then satisfy the verdict by **count**.

        You cannot treat "the header appears in the passed list" as passed: one parameterized header may cover
        4 cases with only 2 passed, while the verdict asks for 2 of them -- counting all as passed would also count the failed ones.
        Conversely "any failure under the header fails them all" would kill the cases that passed. Satisfying by count is the
        only choice that does not systematically favor either side (truncated output cannot tell which parameter is which).
        """
        groups, ok = {}, []
        for name in names:
            n = name.strip().strip("'\"")
            if passed.get(n):
                ok.append(name)
            else:
                groups.setdefault(n.split()[0] if n.split() else n, []).append(name)
        for head, members in groups.items():
            avail = sum(c for p, c in passed.items() if p.startswith(head))
            ok += members[:avail]
        return ok

    f2p_ok, p2p_ok = score(f2p), score(p2p)
    print(json.dumps({
        "resolved": len(f2p_ok) == len(f2p) and len(p2p_ok) == len(p2p) and bool(f2p),
        "FAIL_TO_PASS": f"{len(f2p_ok)}/{len(f2p)}",
        "PASS_TO_PASS": f"{len(p2p_ok)}/{len(p2p)}",
        "summary": report.strip().splitlines()[-1][:120],
    }, ensure_ascii=False))
finally:
    env.cleanup()

Step 6: Run and self-check grading

task.md is the problem description body; instance.json is a single-element array whose fields come from the upstream dataset:

[{"instance_id": "getmoto__moto-7365",
  "problem_statement": "DynamoDB's `update_item` performs floating-point arithmetic ...",
  "base_commit": "7f6c9cb1...",
  "FAIL_TO_PASS": ["tests/test_dynamodb/test_dynamodb_update_expressions.py::test_update_item_add_float"],
  "PASS_TO_PASS": ["tests/test_dynamodb/test_dynamodb_update_expressions.py::test_update_different_map_elements_in_single_request"],
  "test_patch": "diff --git a/tests/... (verbatim from the upstream dataset)",
  "patch": "diff --git a/moto/... (gold patch shipped in the dataset, for grader self-check only)"}]

Let the grader self-check before running the agent. Run the grading flow once with the gold patch shipped in the dataset, which must return resolved: true. This step costs no model tokens:

.venv/bin/python grade.py --gold
# {"resolved": true, "FAIL_TO_PASS": "1/1", "PASS_TO_PASS": "1/1", "summary": "2 passed, 21 warnings in 0.71s"}

If the self-check fails, the pipeline itself is broken (image, working directory, test injection method, or case name matching), and the agent score is meaningless. After the self-check passes, run the agent and grade it:

.venv/bin/python run.py
# {"exit_status": "Submitted", "patch_bytes": 1843, "model_calls": 32,
#  "template": "fc-e2b-registry-...-46a01131", "sandbox_id": "sbx-..."}

.venv/bin/python grade.py --patch out.patch
# {"resolved": true, "FAIL_TO_PASS": "1/1", "PASS_TO_PASS": "1/1", "summary": "2 passed, 21 warnings in 0.76s"}

The first run registers the image as a template (idempotent; later runs hit the cache in 1-2 seconds). Models are stochastic, so model_calls and patch_bytes vary.

Scale out to batch evaluation

You do not have to write concurrent orchestration to go from one task to N tasks: mini-SWE-agent ships a batch evaluation entry mini-extra swebench, which handles per-instance isolation, concurrency, writing preds.json, and recycling sandboxes after the run. Only one thing is left for concurrent orchestration: provide the image address for each task.

Resolution layer: the image address must come from a lookup table

Evaluation image tags usually carry build batch information (such as ..._202607231510) and cannot be derived from instance_id, so a lookup table is required. mini-extra swebench reads the image_name field of an instance first, so writing the resolved result into this field is enough:

# prepare.py -- produce a local dataset carrying image_name
import json
from pathlib import Path

# The manifest is tab-separated text; the first two columns are instance_id and image address (see Obtain the image list)
IMAGES = dict(l.rstrip("\n").split("\t")[:2] for l in open("swegym-images.tsv"))
instances = json.loads(Path("instances.json").read_text())

out = Path("dataset"); out.mkdir(exist_ok=True)
with (out / "train.jsonl").open("w") as f:
    for inst in instances:
        if inst["instance_id"] not in IMAGES:     # drop instances without an image mapping before the run
            continue
        inst["image_name"] = IMAGES[inst["instance_id"]]
        f.write(json.dumps(inst, ensure_ascii=False) + "\n")
--subset accepts a directory (put train.jsonl or parquet files in it). Giving a single file path directly reports Couldn't find any data file.

Resolution is a pure table lookup with no network or sandbox overhead, so it can be completed once before the evaluation starts. Instances that fail to resolve should be dropped before the evaluation starts rather than failing midway.

Batch execution

Run batch evaluation on the dataset produced by the resolution layer:

.venv/bin/mini-extra swebench \
    --subset ./dataset --split train \
    -c swebench.yaml -c demo.yaml \
    --workers 6 -o ./results

-c is a list. A custom configuration replaces the defaults, so the official swebench.yaml must be listed first explicitly -- writing only -c demo.yaml fails with a missing prompt error: ValidationError: system_template Field required. demo.yaml's image does not need a value at this point; it is injected per instance.

Two easily missed points:

  • Credentials must use the standard variable names that litellm recognizes. The batch entry does not inject api_key; litellm resolves it by provider (openai/... → OPENAI_API_KEY). A wrong variable name retries 3 times with a 60-second wait each before reporting Missing credentials.

  • the batch exit code is always 0, even when every instance fails -- exceptions are recorded in each instance's exit_status and the batch still finishes (see the constraint table below). So the outer layer must check whether preds.json is empty in model_patch instead of relying on the exit code. In a test, all three instances failed on a credential error, yet the exit code was still 0 and preds.json entries are complete but all patches are empty.

Results are written to results/preds.json (instance_id → model_patch), and each instance has its own trajectory record that stores sandbox_id and template, so you can trace back to that specific run.

The batch entry injects the image address per instance only (the image_name field of the instance). cwd and run_as_user have no per-instance injection channel, so the whole batch shares one configuration. Therefore a single batch can only use images from the same family, while different datasets use different working directories (see What to change when switching datasets). Datasets whose working directory differs per instance (the "one directory per repository name" and "repository name at the root" types) cannot be merged into one batch. Split them by image family, and use one demo.yaml per family.

Four orchestration constraints. The built-in entry already handles the first two; you still need to set the last two:

Constraint

Status

A single instance failure does not take down the batch

Built-in: the exception is recorded in that instance's exit_status, and the rest continue

Sandboxes must be recycled

Built-in: all five paths -- normal exit, agent exception, startup command failure, environment object discarded, and the process terminated by SIGTERM -- call kill. The last one means release immediately and do not wait for running instances: the scheduler sends SIGKILL after its own grace window (30 seconds by default in Kubernetes, which is not enough for one step in a large repository), so waiting first may leave no time to send the kill request. Kill requests are dispatched concurrently with a 20-second total limit; set the graceful shutdown window accordingly. Work in running instances is lost, but preds.json is written per instance, so rerunning the same command only fills in the unfinished ones. Falling back on TTL adds cost and keeps holding concurrency slots

Set limits on the agent side

You must configure step_limit, cost_limit, wall_time_limit_seconds yourself, otherwise one hard task can consume the whole batch budget. A misspelled field name raises no error and is silently ignored

Tiered output truncation

You must configure it: 15k characters for terminal output, 20k for a single file, and 50k for batch output, so the context is not filled up

Keep the concurrency around 6. Concurrent first builds of the same image are already mutually exclusive by template name in the built-in environment class (see Template building above), so they need no extra handling. Only one reason remains to limit concurrency: for large images, creating a sandbox at 10-way concurrency may time out, and a serial retry succeeds. Therefore, when sandbox creation fails, retry once serially before declaring the instance unusable. Otherwise concurrency pressure is misattributed to the image.

Decouple grading from the agent

The agent phase only produces preds.json. The grading phase reads it and judges each entry in a fresh sandbox, concurrently. After you change the grading logic, re-grading does not require rerunning the agent, which saves a full round of model calls.

The first thing to do with any new dataset is to grade all gold patches shipped in the dataset. The pass rate must be close to 100%. Only this step exposes the following seven classes of problems, all of which silently lower scores without raising an error:

Problem

Symptom

Action

The dataset field contains the literal \n (a backslash followed by n, not a newline)

bash treats it as an escape, the command is mangled, and the whole reset fails

Restore newlines for that field only, not globally

The grading basis is truncated by tail -N

Test reports in large repositories run to thousands of lines, passed cases are missed, and scores come out low

Filter the verdict lines first, then take the summary tail separately

Parameterized case names contain spaces or newlines

pytest truncates case names at the first whitespace, so exact matches all miss

Match on the truncated prefix and satisfy the verdict by count

Case names passed to pytest as command line arguments

Names with spaces or parentheses report not found, and the run ends with no tests ran

Run the whole test file, then match names in the report

The image HEAD does not match the base_commit recorded in the metadata

The patch may be applied to the wrong code state, so the test results do not relate to the task

Run git reset --hard <base_commit> and git clean -fd before grading, and stop grading if the reset fails

pytest is still missing after the environment is activated correctly

A repository-native test entry is misjudged as a broken image. The representative images of Django and SymPy fall into this class

Read the real test command given by the dataset or the repository, instead of hard-coding pytest for every Python repository

A grading command that times out or produces empty output is treated as "tests did not pass"

Large test sets time out under high concurrency and the instance is recorded as 0 passed, while a serial rerun passes everything

When the output is empty or the exit code is abnormal, mark the result as grading incomplete, exclude it from the denominator, and rerun with lower concurrency

The last three classes are the easiest to miss: when the baseline or the executor is wrong, the test results do not belong to the target task at all, and a timeout reads as weak model capability instead of an infrastructure failure. None of the three may be recorded as an ordinary score of 0.

Evaluation images

The China (Shanghai) region provides 80,298 open-source evaluation images in 19 image families. The repository state and dependencies are ready, so you only need to obtain the image address and build a template. No manual transfer is required. All image addresses share the prefix fc-e2b-registry.cn-shanghai.cr.aliyuncs.com/swebench/.

Images solve only the environment. A task can enter a trustworthy evaluation only when all three of the following are in place: the image can start, the task metadata is available (problem description, correct baseline, and verdict test cases), and the grading pipeline passes the gold self-check in the real runtime. On these three criteria, this batch of images falls into three categories:

Category

Images

Status

What you need to do

1. Grading criteria verified

29,112

All three elements are in place, and the self-check with the gold patch shipped in the dataset passes

Change the image address and working directory to start the evaluation. Scale-SWE also requires a different test injection method, see below

2. Metadata complete, grading pipeline or runtime to be completed

30,431

The sandbox starts, the task description is available, and the association is verified, but the grader, the repository test entry, the baseline reset, or the full gold self-check is not finished

Complete the real run recipe of the dataset and finish the gold self-check

3. Images only

20,755

The image starts, but the mapping between tasks and images cannot be established

Use them only as repository environments with pre-installed dependencies. To grade them, you must find the metadata yourself

Total

80,298

If you only need to validate the pipeline first, choose category 1. The images and task descriptions in category 2 are complete, but the results cannot yet be treated as trustworthy scores: some lack a grading implementation, and some have a grader but still lack the repository-native command, the correct baseline, or enough gold validation. Category 3 cannot be associated with tasks automatically.

The metadata datasets are hosted on HuggingFace, and the sandbox may not be able to access them directly. We recommend that you export the required fields (problem_statement / base_commit / FAIL_TO_PASS / PASS_TO_PASS / test_patch / gold patch) to a local file in an environment with internet access first, and then deliver them with the evaluation task. Do not pull them during a batch evaluation, because a failed pull blocks the whole batch.

1. Grading criteria verified: 29,112 images

The metadata of the three datasets in the following table is publicly available, the image-to-dataset association fields have been verified entry by entry rather than sampled, and grading with the gold patches shipped in the datasets passes completely.

Dataset

Images

Repositories

Task type

Metadata dataset

Association field

Working directory

Scale-SWE

19,473

1,180

Real PR fixes: the repository is reset to the parent commit of the PR, and the agent must implement that PR

AweAI-Team/Scale-SWE

instance_id is the instance name in the image tag

/workspace/<repo>. Take the workdir field of the dataset

SWE-rebench V2 (python subset)

7,238

689

Real PR fixes

nebius/SWE-rebench-V2. Filter by language=python

image_name is the original image address and matches it verbatim

The repository is at the root directory, named after the repository itself (such as /OpenTripPlanner), and must be probed at runtime

SWE-Gym

2,401

11

Real issue fixes in the standard SWE-bench form

SWE-Gym/SWE-Gym

instance_id (the image tag is force-lowercased, so normalize the case when comparing)

/testbed

All three use FAIL_TO_PASS + PASS_TO_PASS as the grading basis, but the way test cases are injected differs:

  • SWE-Gym and SWE-rebench V2 (python): exactly the same as grade.py in this topic: apply test_patch to inject the test cases, then run pytest. The test command for the python subset of SWE-rebench V2 is always pytest --no-header, so the criteria line up directly. Switching datasets only requires changing the image address and probing the working directory at runtime.

  • Scale-SWE: has no test_patch. FAIL_TO_PASS points to an injected new test file whose content is in the f2p_script field (or in the f2p_patch applied to an existing test file). The reset relies on pre_commands. You must rewrite the part that injects test cases in grade.py, and the order cannot be reversed either -- the pre_commands's git clean -fd deletes untracked files, so writing tests before the reset is wasted.

Repository diversity varies a lot: Scale-SWE covers 1,180 repositories, the python subset of SWE-rebench V2 covers 689, and SWE-Gym covers only 11, mostly pandas, moto, and similar. Look at the Repositories column when building a cross-repository generalization baseline. SWE-Gym alone has a ceiling: however many tasks it has, they concentrate on the same few repositories.

2. Metadata complete, grading pipeline or runtime to be completed: 30,431 images

The images in the following table can start, the task descriptions are available, and the association fields are verified to 100% (SWE-smith is 99.7%), but the grader, the repository test entry, the baseline reset, or the full gold self-check is incomplete in at least one item.

Dataset

Count

Task type

Metadata dataset

Association field

Grading method and outstanding work

SWE-bench (full official test split)

2,294

Real issue fixes covering 12 Python repositories

princeton-nlp/SWE-bench's test split

instance_id: 2,294 images and 2,294 official tasks match in both directions with zero difference

The existing test_patch + F2P/P2P grader can be reused, but this dataset cannot move up to category 1 yet. In the China (Shanghai) region, Template Build, sandbox startup, /testbed, git, and Python checks pass for 12/12; after the environment is activated correctly through BASH_ENV, pytest is available for 10/12; HEAD == base_commit holds for 9/12, and representative gold passes for 7/12. Django and SymPy need the repository-native commands, and Requests, Xarray, and Pytest must first be reset to the official base_commit. After these gaps are closed, complete the full gold self-check

SWE-rebench V2 (19 languages other than python)

24,836

Real PR fixes with the widest repository coverage (3,614 repositories in the whole family)

nebius/SWE-rebench-V2

image_name is the original image address

Also FAIL_TO_PASS + PASS_TO_PASS, but case name shapes vary with the test framework, so grading must branch by language. Through install_config.test_cmd and log_parser the dataset specifies the run command and parsing method per instance

CyberGym

1,507

Vulnerability discovery: trigger and fix known vulnerabilities in real open-source projects (from OSS-Fuzz / ARVO)

sunblaze-ucb/cybergym

task_id. Remove the -vul suffix at the end of the image tag to get an exact match

Does not use FAIL_TO_PASS. It judges whether the vulnerability can be triggered and whether it no longer triggers after the fix, which requires a fuzz reproduction pipeline

SWE-bench Pro

731

Enterprise repository issue fixes with longer context, covering Go, Node, and other languages

ScaleAI/SWE-bench_Pro, or AweAI-Team/AweAgent-Meta-SWE-Bench-Pro

dockerhub_tag

Also FAIL_TO_PASS + PASS_TO_PASS, and must branch by repo_language. Prefer the AweAI version: same number of rows, but it additionally provides run_script_sh / parser_py, including the run and parsing scripts

SWE-bench Multilingual

300

Real issue fixes covering 41 repositories and 9 non-Python languages: C, C++, Go, Java, JavaScript, TypeScript, PHP, Ruby, and Rust

SWE-bench/SWE-bench_Multilingual

instance_id: 300 images and 300 official tasks match in both directions with zero difference

Also FAIL_TO_PASS + PASS_TO_PASS, and the working directory is /testbed, but the pytest grader cannot be reused. Run the official eval.sh per instance, then parse the real test logs according to task.yaml's log_parser / eval_type. The script exit code alone is not enough. Rust gold passes, Go is limited by dependency source network access, and some Maven tasks depend on SNAPSHOT artifacts that are no longer published. It stays in category 2 until the full gold self-check is complete

SWE-smith

363 environment images (corresponding to 79,418 upstream tasks)

Synthetic defect fixes. One image carries multiple tasks of the same repository

SWE-bench/SWE-smith-py and six other language subsets (py / java / js / ts / rs / cpp / php). Upstream also has a go subset with no corresponding image

image_name

The grading basis is the same as SWE-bench, but you must implement the task selection mechanism yourself: in /testbed, run git checkout <instance_id> to switch to the corresponding defect state

SEC-bench

300

Security vulnerability reproduction and fixes (CVE)

SEC-bench/SEC-bench

instance_id

Does not use FAIL_TO_PASS. Check the sanitizer report and the exit code. The dataset ships work_dir / build_sh / secb_sh and provides both the run and verdict scripts

Terminal-Bench 2.x

89

Terminal tasks (not code fixes): complete an instruction in the shell, with no git repository and no patch

harborframework/terminal-bench-2.0

The task directory name is the image tag

Run the task's own tests/test.sh, no grading implementation is needed. But the agent loop must change, because it produces no patch

SWE-Atlas QnA

11

Repository Q&A, no patch produced

ScaleAI/SWE-Atlas-QnA

docker_image

Scored against a rubric, which requires model judging rather than running tests

For SWE-smith, the image count and the task count are not the same thing. The 363 images are environment images, one per repository, backing 79,418 upstream tasks selected by switching branches. Once you implement the task selection mechanism, it becomes the largest task source in this asset set.

The full official SWE-bench is all Python, but Python must not be equated with pytest. After sampling one image from each of the 12 repositories, all images built and started, but only 10 repositories provide pytest once the environment is activated correctly. Django and SymPy need the repository-native harness. For the other three images, the HEAD does not match the official base_commit, so the existing generic pytest grader completes only 7/12 representative gold self-checks, which is not enough to claim that the whole family can be evaluated directly.

Multilingual datasets must branch by language. Taking SWE-rebench V2 as an example, case name shapes vary with the test framework: python uses pytest node ids (tests/test_x.py::TestA::test_b), TS / JS use jest or mocha case descriptions, and Java uses test class names. Applying one pytest parsing logic to all languages makes every non-python instance fail. The swerebenchv2-languages.tsv (id -> language) in the manifest can be used for filtering. Test command shapes are more concentrated than languages: Go always uses go test, Rust always uses cargo test, Java uses either Maven or Gradle, and JS / TS use npm-based jest / mocha / vitest and so on. Four or five parser groups cover most cases. SWE-bench Pro is similar: branch by repo_language.

SWE-bench Multilingual relies on the per-instance eval.sh and the task.yaml's log_parser / eval_type are authoritative. When running, merge the PATH of the image PID 1 to find pre-installed toolchains such as Cargo. Do not unconditionally set the BASH_ENV=/root/.bashrc that Python images commonly use. Parse real test logs rather than the script exit code, otherwise failed tests are reported as passed.

3. Images only: 20,755 images that you must match with metadata

The images in the following table also work (template building, sandbox creation, and in-container operations are all normal), but the platform does not provide the association between tasks and verdict test cases. Before using them, find a metadata source and establish the mapping to the images yourself. Otherwise you can only use them as real repository environments with pre-installed dependencies, without automatic grading.

Dataset

Images

Image content

Why you must match the metadata yourself

TMax

14,490

General terminal task environments (various domains, including audio/video and data processing)

The task identifiers in the upstream dataset and the image tags (12 hexadecimal characters) come from different sources, with no overlap in tests, so no mapping can be established

TerminalTraj

5,646

Terminal task container with only tmux / asciinema pre-installed. The task description is not in the image

Upstream distributes task packages (tar). You must unpack them and derive the image identifier from the Dockerfile of each task

ProgramBench

200

Clean-room implementation tasks: repository code is removed, keeping only the target artifact and the instructions

No public metadata dataset found. Note also that these tasks are implement-from-scratch rather than defect fixes, so the agent prompts must be adjusted accordingly

SEC-bench Pro

183

Security task environments

Image tags are numeric identifiers with no matching record in the known public datasets

DeepSWE

114

SWE-bench-style repository environments

Image tags are irreversible random strings, so upstream instances cannot be looked up

NL2RepoBench

104

Implement repository features from natural language descriptions

No public metadata dataset found

Frontier

17

Performance optimization tasks: the image contains training and timing scripts, with no git repository

No public metadata dataset found. Verdicts are based on benchmark scores rather than test results

Toolathlon

1

Tool-calling task environments

Upstream publishes only trajectory data, not the task set

Obtain the image list

Whichever category you use, you need a mapping from instance_id (or the image tag) to the image address: Image tags carry build batch information and cannot be derived from instance_id.

To avoid maintaining a large number of download links whenever images are added, each batch publishes only one complete package, swe-images-<release-date>.tar.gz. The files split by plan, dataset, and language remain inside the package for scripts to select as needed, but are no longer listed as separate download items in this topic.

Current batch

Images

Complete package

Status

20260903

80,298

swe-images-20260903.tar.gz

Published

The package content stays stable:

File in the package

Content

all-images.tsv

Full four-column list: instance_id / image address / dataset / category

tier-{A,B,C}-images.tsv

One-to-one with the three categories above. The third column can be narrowed to a single dataset

<family>-images.tsv

Per-dataset instance_id<TAB>image address, including swebench-images.tsv and swebmultilingual-images.tsv

swerebenchv2-languages.tsv

The language routing table for SWE-rebench V2

image-registry.json

Working directory, running user, grading method, and metadata source, read by the runner

MANIFEST.tsv

Line count, byte count, and SHA-256 for every file in the package

README.md

Statistics of the current batch, dataset association methods, and known boundaries

tar -xzf swe-images-20260903.tar.gz
cd swe-images-20260903

A new batch always uses a new date-based file name and never overwrites a published package. Future releases only need to upload one complete package and update one row in the table above.

instance_id shapes differ by dataset. Check the actual content before you write a filter script, and do not apply the same regular expression across datasets:

Dataset

instance_idShape

Example

SWE-bench (full official test split)

owner__repo-number

django__django-11099

SWE-Gym

owner__repo-number

getmoto__moto-7365

SWE-bench Multilingual

owner__repo-number

apache__druid-13704

Scale-SWE

user_repo_prnumber

geopandas_geopandas_pr2027

SWE-rebench V2

owner-repo:PR-commit prefix

keras-team-keras:19955-ca9519b

# Look up the image address of one task
grep '^getmoto__moto-7365' swegym-images.tsv | cut -f2

# Select all tasks of a repository (use the id shape of that dataset itself)
grep '^pandas-dev__' swegym-images.tsv | cut -f1 > my-instances.txt
grep '^geopandas_geopandas_' scaleswe-images.tsv | cut -f1 >> my-instances.txt

# Take only one dataset from the category-1 list (the third column is the dataset name)
awk -F'\t' '$3=="scaleswe"{print $2}' tier-A-images.tsv | head

# Verify download integrity (use shasum -a 256 -c on macOS)
awk -F'\t' 'NR>1{print $4"  "$1}' MANIFEST.tsv > sums && sha256sum -c sums

What to change when switching datasets

Evaluation images from different sources are not homogeneous, so their working directories differ:

Image source pattern

Working directory

How to obtain it

Standard Python form such as SWE-bench or SWE-Gym

/testbed

Fixed value. Use BASH_ENV=/root/.bashrc to activate the conda environment testbed, then choose the real test command per repository. Django and SymPy still provide no pytest after a correct activation, and must not be misjudged as broken images

SWE-bench Multilingual

/testbed

Fixed value. It uses non-Python toolchains, so merge the PATH of PID 1. Do not assume that /root/.bashrc exists, and do not apply pytest

One directory per repository name

/workspace/<repo>

Take the workdir field of the dataset. It differs per instance

Single application directory

/app

Fixed value

Named after the original repository name at the root

such as /OpenTripPlanner, /ApplicationInsights-node.js

cannot be derived from the image tag (the tag is lowercase while the directory keeps the original case), so probe at runtime

The last case must be probed inside the sandbox:

for d in /*/; do [ -d "$d/.git" ] && echo "${d%/}" && break; done   # For example, this probes /cfn-lint

Fill the probed value back into demo.yaml. Resolve once, because run.py and grade.py accept only a concrete value. In batch evaluation this step belongs to the resolution layer: complete it once before the evaluation starts, instead of probing per instance. The acceptance script below supports setting cwd to auto, and probes and prints the value for you.

The image address and the working directory must be changed in pairs. When require_existing_cwd: true is configured, a wrong value fails at startup:

RuntimeError: Working directory /testbed was not in the image and has been created empty.
For a repository-based task this means it is misconfigured: ...

Without this switch, such errors are not reported at all: a missing working directory is silently created as an empty directory, the agent runs a full round inside it, submits an empty patch, and grading records 0. Therefore, after switching datasets, the first thing to do is to run grade.py --gold once with the gold patch shipped in the dataset, which also confirms that the working directory really contains the target repository.

Two practices to avoid:

  • Hard-coding the working directory in the evaluation configuration. This holds only for some datasets and breaks after you switch. Use the lookup table described above.

  • Selecting the grading executor from the language tag in the image metadata. A batch of images often mixes Go, Node, Java, and Python repositories, so branch on the repo_language field of the dataset.

Use your own images

This approach applies to in-house repositories, internal frameworks, and private evaluation datasets. After the images are integrated, the agent and grading pipeline described above can be reused as is, and only the image layer is replaced.

For the complete process of turning your own image into a usable template, see Build and manage templates by using OpenAPI, which covers the mandatory platform requirements for images (linux/amd64 architecture, /etc/passwd and /etc/group writable, and the fixed path that commands.run and PTY depend on: /bin/bash, and so on). Two common scenarios have dedicated topics:

On top of that, five more points matter for evaluation scenarios:

Constraint

Symptom

Solution

A template name allows only one build

Retrying after a build failure returns 409: template build is not allowed in current status CREATE_FAILED, and the name cannot be rebuilt until the failed record is cleaned up

Delete the failed template record and then rebuild with the same name: the name is released as soon as the deletion succeeds, but deletion is asynchronous, so wait for the alias to disappear. Derive the template name from the image content hash instead of incrementing a version number manually

The build stage does not support execution steps

Declaring run_cmd / set_user / set_workdir returns 400: steps are not supported

Dependencies and the environment must be ready in the source image. Handle permissions and the working directory at runtime with user="root" instead

The build fails when the source image does not meet the envd injection conditions

During the build stage, the platform injects envd into the image. If the image does not meet the prerequisites, the log prints template build failed: envd inject failed, and the log still shows Build finished (in a test, building python:3.11-slim directly triggers this)

Check the image requirements against Build and manage templates by using OpenAPI (linux/amd64, /etc/passwd and /etc/group writable, and a fixed-path /bin/bash). Note that Build finished does not mean success. Check whether the log contains envd inject failed

On a build failure, the SDK may not return for a long time

After a failure, the client keeps polling the build status. With a large volume of logs, it may take a long time to raise ReadTimeout

Set a timeout outside Template.build. Do not rely on it returning by itself. The built-in e2b environment class already does this (build_timeout defaults to 30 minutes)

Sandbox creation times out for large images

Under high concurrency, this reports TimeoutException

Keep the concurrency around 6 and retry once serially on failure

After an image is integrated, do not stop acceptance at "the sandbox can be created". Sample the images and run through the following five steps. Failing any one of them means the image cannot be evaluated directly:

  1. Template building and sandbox creation succeed.

  2. The repository directory exists, is a git repository, and HEAD resolves.

  3. HEAD matches the base_commit of the instance metadata. If they differ, the grader must be able to reset explicitly.

  4. The real test executor of this repository works, instead of an executor guessed from the language.

  5. The verdict cases can really be collected or run (pytest datasets can use pytest --collect-only -q).

The following script implements the pytest path of these steps. It runs in a single sandbox and costs no model tokens. When you sample tens or hundreds of images, it is an order of magnitude cheaper than grade.py --gold, because the latter applies a patch and runs the full test file. When cwd is set to auto, the script probes the repository directory inside the sandbox (see What to change when switching datasets).

It is a pre-check script for the pytest grader, not a universal acceptance tool for every Python dataset: the test executor is hard-coded to python -m pytest, and case names are parsed as pytest node ids. When sampling one image from each of the 12 official SWE-bench repositories, this path satisfies pytest, the correct base_commit, and representative gold for only 7/12. Django and SymPy need the repository-native harness, and Requests, Xarray, and Pytest need a baseline reset first. For Go, Java, or JS datasets, change both execution and parsing. Do not use it to accept SWE-bench Multilingual. That dataset must use the per-instance eval.sh and the corresponding log_parser / eval_type.

# preflight.py
import argparse, json, re, shlex, sys
from pathlib import Path

import yaml
from minisweagent.config import builtin_config_dir
from minisweagent.environments import get_environment
from minisweagent.utils.serialize import recursive_merge

PROBE = 'for d in /*/; do [ -d "$d/.git" ] && echo "${d%/}" && break; done'

def as_list(v):
    """Same rule as grade.py: the field may be a JSON string or a plain string."""
    if isinstance(v, str):
        try:
            return json.loads(v)
        except json.JSONDecodeError:
            return [v] if v else []
    return list(v or [])

def test_files(instance):
    """The files that contain the verdict cases. Keep only names with a file prefix, using the same rule as grade.py."""
    names = as_list(instance.get("FAIL_TO_PASS")) + as_list(instance.get("PASS_TO_PASS"))
    return sorted({n.strip().strip("'\"").split("::")[0] for n in names
                   if "::" in n or n.strip().strip("'\"").endswith(".py")})

p = argparse.ArgumentParser("preflight")
p.add_argument("-c", "--config", type=Path, default=Path("demo.yaml"))
p.add_argument("--instance", type=Path, default=Path("instance.json"))
a = p.parse_args()

# Apply the same layering as run.py and grade.py, so environment variables are consistent by construction
cfg = recursive_merge(
    yaml.safe_load((builtin_config_dir / "benchmarks" / "swebench.yaml").read_text()),
    yaml.safe_load(a.config.read_text()),
)
instance = json.loads(a.instance.read_text())[0]
env_cfg = cfg["environment"]
report = {}

# With cwd set to auto, the sandbox starts in / (which always exists). After the repository directory is probed, each command passes cwd to override it, all in one sandbox.
# With a concrete value, require_existing_cwd catches the misconfiguration at construction time.
auto = env_cfg.get("cwd") == "auto"
env = get_environment(dict(env_cfg, cwd="/" if auto else env_cfg["cwd"], timeout=600))
report |= {"template": env.template, "sandbox_id": env.sandbox.sandbox_id}
try:
    cwd = env_cfg["cwd"]
    if auto:
        found = env.execute({"command": PROBE})["output"].strip().splitlines()
        cwd = found[-1].strip() if found else ""
        report["probed_cwd"] = cwd or "(no git repository at the root)"
        if not cwd:
            raise SystemExit(json.dumps(report | {"ok": False}, ensure_ascii=False))
    report["cwd"] = cwd

    head = env.execute({"command": "git rev-parse HEAD"}, cwd)
    report["is_git_repo"] = head["returncode"] == 0
    report["head"] = head["output"].strip()[:40]

    # Report a missing field explicitly. Silently skipping it makes readers think this item passed, while whether the
    # image matches the metadata is a common cause of "all grades 0 without any error".
    expected = instance.get("base_commit") or ""
    report["base_commit_match"] = report["head"] == expected if expected else "(no base commit in metadata, not checked)"

    ver = env.execute({"command": "python -m pytest --version"}, cwd)
    report["pytest"] = ver["output"].strip().splitlines()[0][:60] if ver["returncode"] == 0 else ""

    # The image may keep history after HEAD, which means the answer can be found in git. Report only, do not fail.
    future = env.execute({"command": "git rev-list --all --not HEAD --count"}, cwd)
    report["future_commits"] = future["output"].strip()[:12] if future["returncode"] == 0 else "?"

    # The verdict file may not exist on the baseline -- test_patch creates it. pytest aborts collection entirely when it
    # receives a non-existent path, so these must be separated, otherwise tasks with new test files are misjudged as broken environments.
    wanted = test_files(instance)
    present = []
    if wanted:
        probe = env.execute({"command": "for f in " + " ".join(map(shlex.quote, wanted))
                                        + '; do [ -f "$f" ] && echo "$f"; done'}, cwd)
        present = [ln.strip() for ln in probe["output"].strip().splitlines() if ln.strip() in wanted]
    report["test_files"] = f"{len(present)}/{len(wanted)} present on the baseline"

    if present:
        out = env.execute({"command": "python -m pytest --collect-only -q "
                                      + " ".join(map(shlex.quote, present))}, cwd, timeout=600)
        found = re.search(r"(\d+) tests? collected", out["output"])
        report["collected"] = int(found.group(1)) if found else 0
    else:
        report["collected"] = None   # verdict files are all created by test_patch, so nothing can be collected on the baseline
finally:
    env.cleanup()

report["ok"] = bool(report["is_git_repo"] and report["base_commit_match"] is not False
                    and report["pytest"] and report["collected"] != 0 and wanted)
print(json.dumps(report, ensure_ascii=False))
sys.exit(0 if report["ok"] else 1)
.venv/bin/python preflight.py
# {"template": "fc-e2b-registry-...-46a01131", "sandbox_id": "sbx-...", "cwd": "/testbed", "is_git_repo": true, "head": "7f6c9cb1...", "base_commit_match": true,
#  "pytest": "pytest 8.3.2", "future_commits": "486", "test_files": "1/1 present on the baseline",
#  "collected": 1, "ok": true}

Three points matter when reading this output:

  • A verdict file missing on the baseline is normal, test_patch creates it, so "0 collected" must not be treated as unusable.

  • base_commit_match is false means the image and this metadata record are not a pair, and the verdict cases do not belong to this repository state.

  • future_commits being non-zero means the answer may be inside the image: some datasets keep the history after HEAD (in tags or other branches), so the agent can read the fix directly from git history. In a test, one SWE-Gym moto image had 237 tags, its future commits were dated 18 months after HEAD, and the class names added by the gold patch could be found directly with git grep. SWE-rebench V2 images report 0. This inflates scores and is completely invisible -- the same class of problem as a misconfigured working directory, only in the opposite direction. The pre_commands of Scale-SWE already strip refs and reflog during the reset. For other datasets, either strip them yourself in env_startup_command, or at least know that scores contain this component.

Acceptance must run under exactly the same environment variables as the grader. Four common misjudgments make normal images look unusable:

Cause of misjudgment

Consequence

The acceptance run omits BASH_ENV

The conda environment is not activated, so python -m pytest reports No module named pytest

Equating "correctly sets BASH_ENV" with "the repository must provide pytest"

Normal images that use the repository-native harness, such as Django and SymPy, are still misjudged

Go is installed in /usr/local/go/bin, which is not in the default PATH

Normal Go repository images are judged as having no test executor

Java projects do not install a global mvn/gradle but ship ./gradlew as the wrapper

Normal images are misjudged

The script above and grade.py read the same configuration, so the BASH_ENV in the configuration is not missed. It still validates only the pytest path and cannot replace reading the real test command per repository. This is why environment activation and grading routing must be verified separately.

Apply in production

  • Credential management: E2B_API_KEY and the model API key are injected through environment variables or a secret management service. Do not hard-code them or commit them to a code repository. Model calls stay in the orchestration layer, and no credential goes into the sandbox.

  • Restrict egress: allowlist sandbox traffic with deny_out: ["0.0.0.0/0"], and permit only code hosting, image registries, and model endpoints. Note that domain filtering works only for the Host header on port 80 and the SNI on port 443. Other ports support CIDR only. allow takes precedence over deny. A rejected TCP connection looks like a successful connection from inside the sandbox, so judge it by the application-layer response.

  • Two levels of timeout: distinguish sandbox-level TTL from command-level timeout. Do not use timeout=0, because a stuck process never recovers. For long tasks, use on_timeout="pause" together with auto_resume. A paused sandbox is neither billed nor does it occupy concurrency.

  • The patch is the only output: the sandbox needs only read access to the repository. After the orchestration layer receives the patch, rebuild a clean repository to verify it and run the tests, then create a PR only if they pass. Do not push or create PRs inside the sandbox.

  • Destroy promptly: call sandbox.kill() in the finally block. Per-second billing counts only running time. But finally and atexit cannot cover a process interrupted by a signal, so the batch entry must release sandboxes immediately on SIGTERM without waiting for running instances (the built-in mini-extra swebench already does this). In any case, set the sandbox TTL to the maximum waste you can accept: however the process dies, the platform recycles the sandbox when the TTL expires, which is the last line of defense.

  • Traceability: record sandbox_id, the template name, and the source image address (the built-in e2b environment class already records them in serialize()), to make reproduction and troubleshooting easier.

  • Cost accounting: the orchestration layer records the start and end times itself, and combines them with get_info() to read the specification and compute the cost.

Related documents