Skip to content
Skip to lesson
Back to Topics
LearnAdvanced Agents & RetrievalCode Generation & Sandboxing
HardLLM Agents & Tool Use17 min read

Code Generation & Sandboxing

Build coding agents that turn runtime tracebacks into tested repairs while isolating untrusted code across local OS sandboxes, containers, microVMs, and WebAssembly.

On this page

A coding agent writes a JUnit XML parser, runs it against a test report, and hits KeyError: 'status'. The model assumed <testcase> carries a status attribute, whereas JUnit encodes failures as child elements. That single traceback turns guesswork into a surgical repair: inspect direct child tags, re-run the suite, and verify the fix.

The risk sits inside runs. Execution makes a coding agent far stronger than text completion, yet it also turns a broken or prompt-injected patch into arbitrary code execution. With ambient shell privileges, candidate code can read ~/.ssh or cloud keys, probe 169.254.169.254, plant a .git/hooks/post-checkout trigger, or forge green test exits. Safe coding agents pair an evidence-driven repair loop (isolated from grading) with layered OS and runtime sandboxing across local developer machines (Landlock, Seatbelt, Seccomp-BPF, workspace masking, Unix-socket secret brokering) and cloud hosts (containers, gVisor, Firecracker, WebAssembly). Outer loops live in ReAct and plan-and-execute architectures, and prompt defenses live in prompt-injection defense strategies.

Turn execution failures into repair evidence

Consider a concrete parsing specification: given a JUnit XML report, return classname::name for each failed or errored <testcase> in first-seen order, deduplicated by (classname, name). Match status tags only as direct children in the root namespace, let <skipped> override <failure> or <error>, and reject missing or blank identifiers.

junit-regression.py
from xml.etree import ElementTree as ET

REPORT = """<testsuites><testsuite>
  <testcase classname="router" name="ok"/>
  <testcase classname="router" name="declined"><failure/></testcase>
  <testcase classname="router" name="offline"><error/></testcase>
  <testcase classname="router" name="later"><skipped/></testcase>
  <testcase classname="router" name="both"><failure/><error/></testcase>
  <testcase classname="router" name="declined"><failure/></testcase>
  <testcase classname="router" name="nested"><details><failure/></details></testcase>
</testsuite></testsuites>"""

NAMESPACED = """<testsuite xmlns="urn:example:junit" xmlns:other="urn:other">
  <testcase classname="api" name="bad"><failure/></testcase>
  <testcase classname="api" name="foreign"><other:failure/></testcase>
  <testcase classname="api" name="skip"><skipped/><error/></testcase>
</testsuite>"""

def broken(xml):
    return [case.attrib["name"] for case in ET.fromstring(xml).iter("testcase")
            if case.attrib["status"] == "failed"]

def failed_tests(xml):
    root = ET.fromstring(xml)
    ns = root.tag[:root.tag.index("}") + 1] if root.tag.startswith("{") else ""
    result, seen = [], set()
    for case in root.iter(f"{ns}testcase"):
        children = {child.tag for child in case}
        if f"{ns}skipped" in children:
            continue
        if not children.intersection({f"{ns}failure", f"{ns}error"}):
            continue
        identity = (case.get("classname"), case.get("name"))
        if any(value is None or not value.strip() for value in identity):
            raise ValueError("Failing testcase requires non-empty classname and name")
        if identity not in seen:
            seen.add(identity)
            result.append(f"{identity[0]}::{identity[1]}")
    return result

try:
    broken(REPORT)
except KeyError as error:
Output
Attempt 1 failed: KeyError('status')
Attempt 2 (standard): ['router::declined', 'router::offline', 'router::both']
Attempt 2 (namespaced): ['api::bad']
JUnit XML direct-child parser trace across seven testcases: failure child emits router::declined, error child emits router::offline, combined failure and error emits router::both once; skipped tag, duplicate declined, nested details/failure, and skip-before-error cases are filtered out.
Direct <failure> or <error> children produce the ordered unique list (router::declined, router::offline, router::both); skipped cases, duplicates, and nested non-direct tags are excluded.

Two ElementTree subtleties make failed_tests reliable: an empty <failure/> element is falsy under if case.find("failure"): (so inspecting direct-child tag sets avoids dropping empty tags),[1] and expanding the root XML namespace {uri}tag stops foreign extensions such as <other:failure/> from counting as failures.[2] Feed only four bounded fields back to the model (command, exit code, failing assertion, and byte-capped head/tail output) and strip terminal escape codes, treating all worker logs as untrusted text.

Repo-scale edit-test-verify loops

A single-file parser fits in one prompt; a real repository with hundreds of modules does not. Dumping whole files into context wastes tokens and dilutes attention across unrelated helpers. Production coding agents turn repository repair into a four-stage edit-test-verify loop:

  1. Compact Agent-Computer Interface (ACI): SWE-agent showed that structured file viewers, symbol search commands, inline linter diagnostics, and concise stderr frame extraction raise issue resolution rates substantially compared with raw shell output.[3] Keeping only the failing file, line number, function frame, and assertion diff preserves context across multi-turn repairs.
  2. Static AST symbol-map localization: Decoupling localization from patch synthesis improves accuracy at a fraction of the token cost.[4] Parsing source files with Python's ast module (without importing modules or executing top-level side effects) builds a cross-file call graph with exact line spans. Running personalized PageRank biased toward symbols named in the issue or traceback lifts the failing functions to the top before spending a single generation token.
  3. Fail-first reproduction in an isolated worktree: Before editing source code, run a minimal regression test against the unmodified repository and log the exact failure (ValueError, KeyError, or assertion diff). That baseline proves the test exercises live code rather than an accidental mock. Isolate each candidate trajectory with git worktree (an independent working directory and staging index sharing one Git object store)[5] and git write-tree (immutable index snapshots for instant resets)[6] so parallel attempts never overwrite the primary checkout.
  4. Finite-budget repair with fault classification: Cap code-repair retries (e.g., t <= 3) so oscillating edits escalate to a human reviewer instead of burning tokens. Classify failures strictly: subprocess.TimeoutExpired, ModuleNotFoundError, or sandbox startup errors halt as infrastructure failures (0 repair slots spent) rather than asking the model to rewrite source code or delete timing-sensitive tests.

Separate candidate execution from grading

If untrusted code shares the grader's process or filesystem view, a hostile patch can forge a passing score. Split every runner into a Trusted Supervisor (orchestrates retries, strips secrets, enforces deadlines), an Untrusted Worker (runs candidate code in a credential-free sandbox), and a Trusted Validator (grades outputs outside the candidate's reach).

Also close time-of-check to time-of-use (TOCTOU) drift, where an agent edits files or swaps base commits after tests pass. Hash the canonical manifest (base commit, candidate bytes, image digest, grading version) with SHA-256 and store it in the supervisor before accepting any patch.

artifact-binding.py
def fingerprint(manifest):
    return sha256(json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode()).hexdigest()

tested = {
    "base": "base-v1",
    "files": {"parser.py": "return failure_names(report)"},
    "environment": "image-v1",
    "grading": "tests-v1",
}
verdict = {"artifact": fingerprint(tested), "status": "pass"}
print("Verified digest:", verdict["artifact"][:12])

for field, replacement in (("base", "base-v2"), ("files", {"parser.py": "return []"}), ("grading", "tests-v2")):
    mutated = deepcopy(tested)
    mutated[field] = replacement
    digest = fingerprint(mutated)
    assert digest != verdict["artifact"]
    print(f"Mutated {field:7s} -> {digest[:12]} (matches={digest == verdict['artifact']})")
Output
Verified digest: 7cb446e25d97
Mutated base    -> 101ce2d57a26 (matches=False)
Mutated files   -> 8a730472adf0 (matches=False)
Mutated grading -> 516ea90efecc (matches=False)
Cryptographic manifest digest binding: canonical Manifest M (base image, code, tests) hashes via SHA-256 to H(M) linked to a stored pass verdict. An unchanged manifest matches H(M) and is accepted; modifying base image, parser.py, or test suite changes the hash and is rejected.
H(M) binds a passing verdict to the exact base commit, candidate bytes, runtime image, and grading suite so any post-test edit fails verification.

Local-OS sandboxing tier: Landlock, Seatbelt, Seccomp-BPF, and workspace escapes

Developer CLI agents (such as Claude Code, Codex CLI, and Gemini CLI) must edit a local repository and run native compilers without requiring a rootful Docker daemon. Instead of running with your full user account, they split trust between a host supervisor and an OS-confined worker across four mechanisms:

Linux Landlock and Seccomp-BPF with Bubblewrap

Unlike legacy LSMs (SELinux, AppArmor) that require root setup, Linux Landlock (introduced in Linux 5.13) lets an unprivileged process restrict itself and its future children via three system calls: landlock_create_ruleset, landlock_add_rule, and landlock_restrict_self (paired with prctl(PR_SET_NO_NEW_PRIVS, 1, ...) so setuid binaries cannot escalate).[8] Landlock uses a versioned kernel ABI spanning filesystem access (ABI v1-v3), TCP bind/connect controls (ABI v4, Linux 6.7), and abstract Unix socket/signal scoping (ABI v6, Linux 6.12). Because Landlock checks rights at file-open time, close sensitive descriptors before invoking untrusted code.

Pair filesystem rules with Seccomp-BPF, which attaches a kernel BPF filter to block dangerous syscalls (ptrace, bpf, chroot, keyctl, socket(AF_PACKET, ...), socket(AF_NETLINK, ...)) before dispatch, and Bubblewrap (bwrap) for unprivileged mount, PID, IPC, and network namespaces:[9][10]

bubblewrap-local-sandbox.sh
bwrap \
  --ro-bind /usr /usr --ro-bind /lib /lib --ro-bind /bin /bin \
  --tmpfs /tmp --proc /proc --dev /dev \
  --bind /path/to/repo/src /app/src \
  --ro-bind /path/to/repo/.git /app/.git \
  --unshare-all --new-session --die-with-parent \
  python3 -m unittest discover /app/src

Pass a compiled BPF filter descriptor via --seccomp alongside --die-with-parent (which sends SIGKILL to the worker if the supervisor dies).

macOS Seatbelt (sandbox-exec / SBPL)

On macOS, Seatbelt profiles written in Sandbox Profile Language (SBPL, invoked via sandbox-exec or sandbox_init_with_parameters) start from (deny default) and pass workspace paths as runtime parameters:[11]

agent-sandbox.sb
(version 1)
(deny default)
(allow process-exec (subpath "/usr/bin") (subpath "/usr/local/bin"))
(allow file-read* (subpath "/usr") (subpath "/System") (subpath "/Library/Developer"))
(deny file-read* file-write*
    (subpath (param "HOME_SSH"))
    (subpath (param "HOME_AWS"))
    (subpath (param "HOME_KEYCHAIN")))
(allow file-read* file-write* (subpath (param "PROJECT_DIR")))
(deny network*)

The .git/hooks workspace escape

Even when ~/.ssh, ~/.aws, and network sockets are blocked, granting write access to the whole repository root opens a delayed host escape.[12] An untrusted worker can write an executable script to .git/hooks/post-checkout (or point core.hooksPath / core.fsmonitor in .git/config, or drop a task in .vscode/tasks.json). None of those untracked files appear in a standard git diff, yet the very next time you run git checkout on the host outside the sandbox, Git executes that planted hook with your full developer privileges.

Secret-zero containment via Unix-socket brokering

Blocking network egress stops a worker from phoning home, yet passing GITHUB_TOKEN or API keys in worker environment variables still leaks them: untrusted code only needs print(base64.b64encode(os.environ["GITHUB_TOKEN"].encode())) to bypass regex log scrubbers and dump credentials straight into captured stdout.

The structural defense is secret-zero containment: place zero raw credentials inside the worker's environment or filesystem. Instead, mount a host-owned Unix domain socket into the sandbox. The worker sends unauthenticated structured requests over that socket, and the host-side broker validates the HTTP method (GET only) and allowlisted repository path, attaches the Authorization: Bearer ... header strictly on the outbound host leg, and filters the upstream JSON response to an explicit field allowlist before returning bytes across the socket.

workspace-escape-and-broker-guard.py
import tempfile
from pathlib import Path

class WorkspaceGuard:
    """Enforces workspace root containment and blocks repository/IDE host triggers."""
    def __init__(self, root: Path):
        self.root = root.resolve()
        self.denied = {
            self.root / ".git" / "hooks",
            self.root / ".git" / "config",
            self.root / ".vscode",
            self.root / ".env",
        }

    def can_write(self, target: Path) -> bool:
        resolved = target.resolve()
        try:
            resolved.relative_to(self.root)
        except ValueError:
            return False
        return not any(resolved == d or d in resolved.parents for d in self.denied)

def broker_request(method: str, path: str, upstream_json: dict) -> tuple[int, dict]:
    """Host-side Unix-socket broker: scopes route/method and strips unapproved fields."""
    if method != "GET" or not path.startswith("/repos/org/app/pulls/"):
        return 403, {"error": "route_or_method_forbidden"}
    allowed_fields = ("number", "state", "title")
    return 200, {k: upstream_json[k] for k in allowed_fields if k in upstream_json}

with tempfile.TemporaryDirectory() as tmp:
    root = Path(tmp)
    (root / "src").mkdir()
    (root / ".git" / "hooks").mkdir(parents=True)
    guard = WorkspaceGuard(root)
    checks = [
        ("src/app.py", root / "src" / "app.py", True),
        ("../.ssh/authorized_keys", root / ".." / ".ssh" / "authorized_keys", False),
        (".git/hooks/post-checkout", root / ".git" / "hooks" / "post-checkout", False),
        (".git/config", root / ".git" / "config", False),
        (".vscode/tasks.json", root / ".vscode" / "tasks.json", False),
    ]
    for label, path, expected in checks:
        ok = guard.can_write(path)
        assert ok is expected
        print(f"write {label:25s} -> {'ALLOW' if ok else 'DENY'}")

raw_upstream = {"number": 42, "state": "open", "title": "Fix parser", "debug_token": "ghp_secret"}
print("Broker GET allowed:", broker_request("GET", "/repos/org/app/pulls/42", raw_upstream))
print("Broker POST blocked:", broker_request("POST", "/repos/org/app/pulls/42", raw_upstream))
Output
write src/app.py                -> ALLOW
write ../.ssh/authorized_keys   -> DENY
write .git/hooks/post-checkout  -> DENY
write .git/config               -> DENY
write .vscode/tasks.json        -> DENY
Broker GET allowed: (200, {'number': 42, 'state': 'open', 'title': 'Fix parser'})
Broker POST blocked: (403, {'error': 'route_or_method_forbidden'})

Server-side execution isolation models

When running multi-tenant or unattended agent jobs on cloud hosts, local process policies give way to container, user-space kernel, microVM, or WebAssembly boundaries. Compare them by where untrusted system calls terminate and what stays in the trusted computing base:

Isolation layerHow it mediates executionTrade-offs and remaining attack surface
Linux containers (Docker / runc)Linux namespaces, cgroups v2 quotas, seccomp filters, and dropped capabilities.Near-native Linux speed, but shares the host kernel. Kernel bugs, permissive mounts, or exposed Docker sockets break isolation.[13]
User-space kernel (gVisor)Sentry intercepts syscalls in user space (systrap or KVM platform) and emits a tiny host syscall subset; Gofer/DirectFS mediates files.[14][15]Strong host-kernel reduction with broad Linux compatibility; syscall-heavy or I/O-heavy builds add measurable overhead.
MicroVM (Firecracker)Runs a dedicated guest Linux kernel inside a minimal VMM over KVM, targeting <=125 ms to guest /sbin/init.[16][17]Hardware virtualization isolates the guest kernel from the host; adds rootfs management and end-to-end startup latency for packages and pytest.
WebAssembly (Wasmtime)Checked linear memory, typed control flow, fuel metering, and zero OS access without explicit imports or WASI.[18]Microsecond cold starts and deterministic instruction caps; limited to code compiled to Wasm or running inside a Wasm interpreter.
Side-by-side isolation stack across four sandbox runtimes: Docker/runc shares the host kernel behind seccomp-bpf, gVisor mediates syscalls through user-space Sentry and Gofer, Firecracker isolates a dedicated guest kernel over KVM, and WebAssembly runs import-free guest code inside checked 64 KiB linear memory with a 1,000-fuel cap.
The four server runtimes differ in where untrusted calls terminate: shared host kernel, user-space Sentry kernel, KVM guest kernel, or import-free Wasm linear memory.

Two deployment traps catch teams quickly. First, never mount the Docker socket inside a worker, because an unrestricted Docker daemon lets any caller launch a privileged container or bind-mount /.[13] Second, inspect hosted sandbox defaults: managed platforms such as Modal allow outbound public-IP traffic unless you configure block_network=True or explicit allowlists, and domain-name filters can still be bypassed via domain fronting on shared edges.[19]

Hardened containers, resource limits, and clean teardown

Even inside a container or microVM, combine filesystem, privilege, network, and cgroup limits so no single runaway script exhausts the host:[20]

Concentric defense-in-depth sandbox layers surrounding an unprivileged UID 10001 worker with capabilities dropped. Surrounding kernel limits enforce cgroups v2 (0.5 CPU, 512 MiB RAM, 64 PIDs), disabled networking (loopback only), read-only pinned root filesystem, and a 64 MiB noexec/nosuid /tmp mount, all supervised by an external 30-second hard watchdog.
Layered worker containment pairs cgroup CPU, memory, and PID limits with network isolation, a read-only root filesystem, a bounded noexec scratch mount, and an external 30-second supervisor watchdog.
hardened-worker-launch.sh
docker run --rm \
  --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,nodev,size=64m,mode=1777 \
  --net=none \
  --user 10001:10001 \
  --cap-drop=ALL \
  --security-opt=no-new-privileges \
  --security-opt seccomp=/etc/docker/seccomp-strict.json \
  --pids-limit 64 --memory 512m --memory-swap 512m --cpus 0.5 \
  --workdir /app --entrypoint python \
  candidate-worker:reviewed-example /app/main.py

Each flag shuts down a distinct failure mode: --read-only plus a 64 MiB noexec,nosuid /tmp stops rootfs tampering and bounds scratch disk (remembering that python /tmp/script.py still runs scripts read as text);[21] --net=none strips outbound networking;[22] --pids-limit 64 stops fork bombs with EAGAIN; and equal --memory / --memory-swap caps disable swap before OOM kill.[23][24] For third-party packages, run a two-phase pipeline: install lockfile-pinned wheels in a credential-free prep phase, then execute candidate code offline with --net=none.

Teardown has two subtle concurrency traps:

  1. Processes escaping killpg via setsid. A child calling setsid() joins a fresh session and survives killpg. Rely on PID-namespace init teardown or Linux cgroup v2 cgroup.kill to terminate every descendant atomically, then verify the cgroup is empty.[25][26][27][23]
  2. Stale cleanup killing a replacement worker. If a supervisor crashes before reaping worker-7 in slot A, a reaper cleans slot A and schedules worker-8 there. A delayed retry for generation 7 that resolves mutable slot A instead of immutable worker-7 kills the healthy replacement.
cleanup-identity.py
old_cleanup = {"slot": "A", "generation": 7, "worker_id": "worker-7"}
current_slot = {"slot": "A", "generation": 8, "worker_id": "worker-8"}
live_workers = {"worker-8"}

print(f"Mutable slot lookup targets: {current_slot['worker_id']} (wrong generation!)")
live_workers.discard(old_cleanup["worker_id"])
print(f"Immutable ID discard ({old_cleanup['worker_id']}) keeps worker-8 alive: {'worker-8' in live_workers}")
assert live_workers == {"worker-8"}
Output
Mutable slot lookup targets: worker-8 (wrong generation!)
Immutable ID discard (worker-7) keeps worker-8 alive: True
Two-track timeline showing Slot A reuse after worker-7 exits, disk and env scrub, and worker-8 starts. When a delayed Gen-7 cleanup timer fires while worker-8 owns Slot A, targeting mutable Slot A kills live worker-8, whereas targeting immutable job_id=worker-7 becomes a safe no-op.
Reuse slot A only after confirmed termination and scrub (or quarantine unknown state), and address delayed teardown by immutable worker ID plus generation check.

Deterministic fuel-metered sandboxing with WebAssembly

For pure computation (parsers, data transforms, math expressions), booting a Linux container is unnecessary overhead. Wasmtime runs WebAssembly modules inside checked linear memory with zero ambient OS access unless you link host imports, and fuel metering deducts an integer budget per instruction so infinite loops trap deterministically with OUT_OF_FUEL.[18][28][29][30]

Always set fuel before instantiation (so a hostile (start $init) hook cannot spin forever during module load), cap compilation bytes, and verify every boundary with failing probes:[31]

wasm-host-and-probes.py
import wasmtime as wasm

config = wasm.Config()
config.consume_fuel = True
engine = wasm.Engine(config)

def run_guest(wat, argument, *, fuel=1_000, memory_bytes=65_536):
    if len(wat.encode("utf-8")) > 4_096:
        raise ValueError("WAT source exceeds 4096-byte cap")
    module = wasm.Module(engine, wat)
    if module.imports:
        raise ValueError("Host imports are forbidden")
    with wasm.Store(engine) as store:
        store.set_limits(memory_size=memory_bytes, memories=1, instances=1, tables=0)
        store.set_fuel(fuel)  # Set before instantiation to meter (start) hooks too.
        instance = wasm.Instance(store, module, [])
        run = instance.exports(store).get("run")
        sig = run.type(store) if callable(run) else None
        if sig is None or [str(t) for t in sig.params] != ["i32"] or [str(t) for t in sig.results] != ["i32"]:
            raise ValueError("Expected export run(i32) -> i32")
        return run(store, argument)

def expect_error(err_cls, fn):
    try:
        fn()
    except err_cls as err:
        return err
    raise AssertionError(f"Expected {err_cls.__name__}")

def guest(body, mem=""):
    return f'(module {mem} (func (export "run") (param i32) (result i32) {body}))'

print("run(41) =", run_guest(guest("local.get 0 i32.const 1 i32.add"), 41))
loop_trap = expect_error(wasm.Trap, lambda: run_guest(guest("(loop br 0) i32.const 0"), 0))
start_trap = expect_error(wasm.Trap, lambda: run_guest('(module (func $i (loop br 0)) (start $i) (func (export "run") (param i32) (result i32) local.get 0))', 0))
oob_trap = expect_error(wasm.Trap, lambda: run_guest(guest("i32.const 65536 i32.load", "(memory 1)"), 0))
assert loop_trap.trap_code == start_trap.trap_code == wasm.TrapCode.OUT_OF_FUEL
assert oob_trap.trap_code == wasm.TrapCode.MEMORY_OUT_OF_BOUNDS
assert run_guest(guest("i32.const 1 memory.grow", "(memory 1)"), 0) == -1
expect_error(wasm.WasmtimeError, lambda: run_guest(guest("local.get 0", "(memory 2)"), 0))
expect_error(ValueError, lambda: run_guest('(module (import "host" "secret" (func)) (func (export "run") (param i32) (result i32) local.get 0))', 0))
print(f"Probes verified: loop={loop_trap.trap_code}, start={start_trap.trap_code}, oob={oob_trap.trap_code}, grow=-1")
Output
run(41) = 42
Probes verified: loop=TrapCode.OUT_OF_FUEL, start=TrapCode.OUT_OF_FUEL, oob=TrapCode.MEMORY_OUT_OF_BOUNDS, grow=-1

Notice that memory.grow past the 64 KiB cap returns -1 instead of trapping, whereas declaring (memory 2) fails instantiation immediately and reading address 65536 traps with MEMORY_OUT_OF_BOUNDS. If a guest needs scoped file access via a host import, resolve and verify the real target path on every open call (not once at setup) so symlink swaps cannot redirect reads.

Evaluate correctness and containment separately

An agent that resolves 80% of issues while leaking canary secrets is unsafe in a way accuracy metrics hide. Track functional accuracy and containment independently.[32][33]

For code-generation accuracy, HumanEval's unbiased pass@k estimator draws n≥kn \ge k independent samples, counts cc passing samples, and computes the exact probability that a uniform subset of kk indices without replacement contains at least one pass:[32]

pass@⁡k^=1−(n−ck)(nk),1≤k≤n.\widehat{\operatorname{pass@}k} = 1 - \frac{\binom{n-c}{k}}{\binom{n}{k}}, \qquad 1 \leq k \leq n.

With n=5n = 5 candidates and c=2c = 2 passes, there are (52)=10\binom{5}{2} = 10 unordered pairs and (32)=3\binom{3}{2} = 3 all-failing pairs, giving pass@⁡2^=1−3/10=0.70\widehat{\operatorname{pass@}2} = 1 - 3/10 = 0.70 (whereas the biased plug-in formula 1−(3/5)2=0.641 - (3/5)^2 = 0.64 underestimates success). Inside a multi-turn repair loop, attempt t+1t+1 conditions on attempt tt's traceback, so apply pass@⁡k^\widehat{\operatorname{pass@}k} across nn independent whole trajectories, and on repository benchmarks such as SWE-bench report infrastructure timeouts separately from failing patches.[33][34]

Decomposing single-trajectory solve probability as p=qloc⋅rpatchp = q_{\text{loc}} \cdot r_{\text{patch}} (localization hit rate times conditional patch repair rate) exposes a common scaling trap. Resampling patches k=4k = 4 times on top of one frozen file selection stays capped by qlocq_{\text{loc}}: at qloc=0.60q_{\text{loc}} = 0.60 and rpatch=0.50r_{\text{patch}} = 0.50, stale-localization resampling plateaus at 0.60⋅(1−0.504)=0.5630.60 \cdot (1 - 0.50^4) = 0.563, whereas redrawing full trajectories from localization onward reaches 1−(1−0.30)4=0.7601 - (1 - 0.30)^4 = 0.760, and improving AST localization first to p=0.50p = 0.50 reaches 0.9380.938.

pass-at-k.py
from itertools import combinations
from math import comb, isclose

def pass_at_k(n, c, k):
    misses = comb(n - c, k) if n - c >= k else 0
    return 1 - misses / comb(n, k)

pool = [True, True, False, False, False]  # n=5, c=2
hits = sum(any(pair) for pair in combinations(pool, 2))
assert hits == 7 and isclose(pass_at_k(5, 2, 2), hits / 10)
for k in range(1, 6):
    print(f"pass@{k} (n=5, c=2) = {pass_at_k(5, 2, k):.3f}")
Output
pass@1 (n=5, c=2) = 0.400
pass@2 (n=5, c=2) = 0.700
pass@3 (n=5, c=2) = 0.900
pass@4 (n=5, c=2) = 1.000
pass@5 (n=5, c=2) = 1.000
Ten unordered index pairs are arranged in an upper-triangular grid for five fixed candidates. Candidates 1 and 2 pass; candidates 3, 4 and 5 fail. Each pair contains two colored candidate dots. Seven green-outlined pairs contain at least one pass, and three red-outlined pairs contain only failures. Counting the ten equally likely pairs gives pass@2 = 7/10 = 70% for selection without replacement. This is finite-pool arithmetic, with no agent benchmark execution.
Seven of ten unordered pairs without replacement contain at least one passing candidate, giving pass@2 = 7/10 = 70%.

Before deploying any sandbox, run staging containment probes with dummy credentials: a canary file probe (verify host secrets never reach stdout/stderr), a workspace-escape probe (block writes to .git/hooks/post-checkout and .git/config), an egress probe (confirm active denial to blocked public, private, IPv6, and metadata IPs), a storage probe (confirm ENOSPC on /tmp), and an orphan probe (spawn a setsid child, kill the supervisor, and verify the cgroup empties).

Summary

Reliable coding agents pair concise execution evidence with explicit trust boundaries: isolate grading behind a SHA-256 manifest digest, confine local runs with Landlock, Seatbelt, Seccomp-BPF, read-only .git masking, and Unix-socket secret brokering, bound server workers with cgroups and wall-clock watchdogs or WebAssembly fuel, and score accuracy separately from containment.

Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 5 answered
1.A read-only Python test file expects a nonempty list. Candidate code shares the interpreter, monkey-patches the assertion helper, and exits 0 while returning []. What closes this flaw?
2.A local Linux agent grants Landlock read-write access to /repo and adds a read-only rule on /repo/.git in the same layer. Why can an untrusted patch still escape to the host?
3.Why does secret-zero containment proxy API calls through a host Unix domain socket instead of placing GITHUB_TOKEN in an offline worker's environment?
4.A container has a cgroup CPU quota of 36 ms per 80 ms period across two busy threads and a 4-second external wall deadline. What is its aggregate CPU cap, and what kills an infinite loop?
5.A pool of n = 6 independent trajectories contains c = 2 passes. Using the unbiased without-replacement estimator, what is pass@2?

5 questions remaining.

References

ElementTree: namespaces and element truth-value testing

Python Software Foundation · 2026

https://docs.python.org/3/library/xml.etree.elementtree.html

XML security

Python Software Foundation · 2026

https://docs.python.org/3/library/xml.html#xml-security

SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering

Yang et al. · 2024

https://arxiv.org/abs/2405.15793

Agentless: Demystifying LLM-based Software Engineering Agents

Xia et al. · 2024

https://arxiv.org/abs/2407.01489

git-worktree: Manage multiple working trees

Git Project · 2026

https://git-scm.com/docs/git-worktree

git-write-tree: Create a tree object from the current index

Git Project · 2026

https://git-scm.com/docs/git-write-tree

Vitest configuration: passWithNoTests

Vitest Contributors · 2026

https://vitest.dev/config/passwithnotests

Landlock: unprivileged access control

Linux Kernel Organization · 2026

https://docs.kernel.org/userspace-api/landlock.html

Seccomp BPF (SECCOMP_MODE_FILTER)

Linux Kernel Organization · 2026

https://docs.kernel.org/userspace-api/seccomp_filter.html

Bubblewrap unprivileged sandboxing tool

Containers Project · 2026

https://github.com/containers/bubblewrap

App Sandbox

Apple Developer Documentation · 2026

https://developer.apple.com/documentation/security/app-sandbox

Git Hooks and Workspace Execution Security

Git Project Documentation · 2026

https://git-scm.com/docs/githooks

Docker security

Docker · 2026

https://docs.docker.com/engine/security/

gVisor Security Model

gVisor Contributors · 2026

https://gvisor.dev/docs/architecture_guide/security/

gVisor Platform Guide

gVisor Contributors · 2026

https://gvisor.dev/docs/architecture_guide/platforms/

Firecracker: Lightweight Virtualization for Serverless Applications.

Agache, A., et al. · 2020 · NSDI 2020

https://www.usenix.org/conference/nsdi20/presentation/agache

Firecracker Specification

Firecracker Contributors · 2026

https://github.com/firecracker-microvm/firecracker/blob/main/SPECIFICATION.md

Wasmtime Security

Bytecode Alliance · 2026

https://docs.wasmtime.dev/security.html

Networking and security (Modal Sandboxes Documentation)

Modal · 2026

https://modal.com/docs/guide/sandbox-networking

Running containers

Docker · 2026

https://docs.docker.com/engine/containers/run/

tmpfs mounts

Docker · 2026

https://docs.docker.com/engine/storage/tmpfs/

None network driver

Docker · 2026

https://docs.docker.com/engine/network/drivers/none/

Control Group v2: resource limits and cgroup.kill

Linux Kernel Contributors · 2026

https://cdn.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html

Resource constraints

Docker · 2026

https://docs.docker.com/engine/containers/resource_constraints/

PR_SET_CHILD_SUBREAPER(2const)

Linux man-pages Project · 2026

https://man7.org/linux/man-pages/man2/PR_SET_CHILD_SUBREAPER.2const.html

setsid(2)

Linux man-pages Project · 2026

https://man7.org/linux/man-pages/man2/setsid.2.html

pid_namespaces(7)

Linux man-pages Project · 2026

https://man7.org/linux/man-pages/man7/pid_namespaces.7.html

Interrupting Execution

Bytecode Alliance · 2026

https://docs.wasmtime.dev/examples-interrupting-wasm.html

wasmtime Python package

Bytecode Alliance · 2026

https://pypi.org/project/wasmtime/

wasmtime-py API documentation

Bytecode Alliance · 2026

https://bytecodealliance.github.io/wasmtime-py/

Deterministic Wasm Execution

Bytecode Alliance · 2026

https://docs.wasmtime.dev/examples-deterministic-wasm-execution.html

Evaluating Large Language Models Trained on Code (HumanEval).

Chen, M., et al. · 2021 · arXiv preprint

https://arxiv.org/abs/2107.03374

SWE-bench: Can Language Models Resolve Real-World GitHub Issues?.

Jimenez, C. E., et al. · 2024 · ICLR 2024

https://arxiv.org/abs/2310.06770

SWE-bench Evaluation Guide

SWE-bench Contributors · 2026

https://www.swebench.com/SWE-bench/guides/evaluation/

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.