WBX Sandbox
Tutorials

Prepare once, run many agents

Installing dependencies takes minutes; starting a sandbox takes seconds. Prepare one sandbox with everything your agents need, then clone it: each copy starts with the same files and packages, but runs on its own – ideal for trying several approaches in parallel.

What you'll build

A script that prepares a sandbox with scikit-learn and a small training script, clones it into three copies, trains a model with a different setting in each copy at the same time and prints the results. It keeps the prepared state as a snapshot, starts one more sandbox from it the way a later run would, and finally cleans up everything it created.

Two words. A snapshot is a saved copy of a sandbox disk – files and installed packages, never memory or running programs. A clone is a new sandbox started from such a copy; one clone call makes 1–10 of them on the same server. Copies keep the source's lifetime and network settings, compute class, on_timeout, idle_timeout_s and keep_days; environment variables (env) are not copied.

What you need

  • A WBX Sandbox API key in WBXSANDBOX_API_KEY; pip install wbxsandbox or npm install wbxsandbox.
  • Room for four sandboxes at once (the source plus three copies). On a plan with fewer concurrent sandboxes the script still works – some copies fail and it shows why (see partial success).
  • About 15 minutes.

Steps

  1. The whole script

    Read it top to bottom: prepare → clone (keeping the snapshot) → run the variants in parallel → start a sandbox from the snapshot → clean up. The finally block deletes every sandbox and the snapshot even if something fails in the middle.

    # clone_variants.py
    from concurrent.futures import ThreadPoolExecutor
    from wbxsandbox import Sandbox, Snapshot
    
    TASK = '''
    import sys, time
    from sklearn.datasets import load_iris
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import cross_val_score
    c = float(sys.argv[1])
    X, y = load_iris(return_X_y=True)
    t = time.time()
    score = cross_val_score(LogisticRegression(C=c, max_iter=1000), X, y, cv=5).mean()
    print(f"C={c}: accuracy {score:.3f} in {time.time() - t:.2f} s")
    '''
    VARIANTS = ["0.1", "1.0", "10.0"]
    
    src = Sandbox.create(template="base", timeout=1800)
    copies, snap, extra = [], None, None
    try:
        # 1. prepare once
        src.run("pip install --quiet scikit-learn", timeout=600).check()
        src.files.write("/home/user/work/task.py", TASK)
    
        # 2. three copies; keep the snapshot for later runs
        copies = src.clone(count=3, keep_snapshot=True, snapshot_name="sklearn-ready", timeout=900)
        snap = Snapshot.get(copies.snapshot_id)
        print(f"{len(copies)} copies from snapshot {snap.id}")
        for e in copies.errors:                       # only on partial success (HTTP 207)
            print(f"copy {e.get('index')} failed: {e.get('status')} {e.get('code')} {e.get('error')}")
        src.kill()                                    # the copies don't need the source any more
    
        # 3. one variant per copy, all at the same time
        def run(pair):
            sb, c = pair
            return sb.run(f"python3 task.py {c}", cwd="/home/user/work", timeout=300)
        with ThreadPoolExecutor() as pool:
            for r in pool.map(run, zip(copies, VARIANTS)):
                print(r.stdout.strip() if r.ok else f"failed: {r.stderr.strip()[-500:]}")
    
        # 4. later (another day, another program): a fresh sandbox from the snapshot
        extra = snap.create_sandbox(timeout=600)
        print(extra.run("python3 task.py 0.5", cwd="/home/user/work", timeout=300).stdout.strip())
    finally:
        # 5. clean up: sandboxes first, then the snapshot (it is billed as storage until deleted)
        for sb in [*copies, extra, src]:
            if sb:
                sb.kill()                             # no error if it is already gone
        if snap:
            snap.delete()
    // clone_variants.mts (an ES module – top-level await)
    import { WBX, type Sandbox } from "wbxsandbox";
    
    const TASK = `
    import sys, time
    from sklearn.datasets import load_iris
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import cross_val_score
    c = float(sys.argv[1])
    X, y = load_iris(return_X_y=True)
    t = time.time()
    score = cross_val_score(LogisticRegression(C=c, max_iter=1000), X, y, cv=5).mean()
    print(f"C={c}: accuracy {score:.3f} in {time.time() - t:.2f} s")
    `;
    const VARIANTS = ["0.1", "1.0", "10.0"];
    
    const wbx = new WBX();
    const src = await wbx.sandboxes.create({ template: "base", timeoutSeconds: 1800 });
    let copies: Sandbox[] = [];
    let snapId: string | undefined;
    let extra: Sandbox | undefined;
    try {
      // 1. prepare once
      (await src.commands.run("pip install --quiet scikit-learn", { timeoutMs: 600_000 })).check();
      await src.files.write("/home/user/work/task.py", TASK);
    
      // 2. three copies; keep the snapshot for later runs
      const clone = await src.clone({ count: 3, keepSnapshot: true, snapshotName: "sklearn-ready", timeoutSeconds: 900 });
      copies = clone.sandboxes;
      snapId = clone.snapshotId;
      console.log(`${copies.length} copies from snapshot ${snapId}`);
      for (const e of clone.errors) console.log(`copy ${e.index} failed: ${e.status} ${e.code} ${e.error}`);
      await src.kill(); // the copies don't need the source any more
    
      // 3. one variant per copy, all at the same time
      const results = await Promise.all(copies.map((sb, i) =>
        sb.commands.run(`python3 task.py ${VARIANTS[i]}`, { cwd: "/home/user/work", timeoutMs: 300_000 })));
      for (const r of results) console.log(r.ok ? r.stdout.trim() : `failed: ${r.stderr.trim().slice(-500)}`);
    
      // 4. later (another day, another program): a fresh sandbox from the snapshot
      if (snapId) {
        extra = await (await wbx.snapshots.get(snapId)).createSandbox({ timeoutSeconds: 600 });
        console.log((await extra.commands.run("python3 task.py 0.5", { cwd: "/home/user/work", timeoutMs: 300_000 })).stdout.trim());
      }
    } finally {
      // 5. clean up: sandboxes first, then the snapshot (it is billed as storage until deleted)
      for (const sb of [...copies, extra, src]) if (sb) await sb.kill(); // no error if already gone
      if (snapId) await wbx.snapshots.delete(snapId);
    }
    H=(-H "Authorization: Bearer $WBXSANDBOX_API_KEY" -H "Content-Type: application/json")
    API=https://sandbox.wbx.cz
    
    # 1. prepare once: the package and the task script
    SRC=$(curl -s -X POST $API/v1/sandboxes "${H[@]}" -d '{"template": "base", "timeout_s": 1800}' | jq -r .id)
    curl -s -X POST $API/v1/sandboxes/$SRC/exec "${H[@]}" \
      -d '{"cmd": "pip install --quiet scikit-learn", "timeout_ms": 600000}' | jq .exit_code
    cat > task.py <<'PY'
    import sys
    from sklearn.datasets import load_iris
    from sklearn.linear_model import LogisticRegression
    from sklearn.model_selection import cross_val_score
    c = float(sys.argv[1])
    X, y = load_iris(return_X_y=True)
    print(f"C={c}: accuracy {cross_val_score(LogisticRegression(C=c, max_iter=1000), X, y, cv=5).mean():.3f}")
    PY
    curl -s -X PUT "$API/v1/sandboxes/$SRC/files?path=/home/user/work/task.py" \
      -H "Authorization: Bearer $WBXSANDBOX_API_KEY" -H "Content-Type: application/octet-stream" --data-binary @task.py
    
    # 2. three copies, snapshot kept – 201 = all created, 207 = only some (see "errors")
    curl -s -o clone.json -w 'HTTP %{http_code}\n' -X POST $API/v1/sandboxes/$SRC/clone "${H[@]}" \
      -d '{"count": 3, "keep_snapshot": true, "snapshot_name": "sklearn-ready", "timeout_s": 900}'
    jq '.errors' clone.json
    SNAP=$(jq -r .snapshot_id clone.json)
    jq -r '.sandboxes[].id' clone.json > copies.txt
    
    # 3. one variant per copy, all at the same time
    VARIANTS=(0.1 1.0 10.0); i=0
    for ID in $(cat copies.txt); do
      jq -n --arg c "${VARIANTS[$i]}" '{cmd: ("python3 task.py " + $c), cwd: "/home/user/work", timeout_ms: 300000}' |
        curl -s -X POST $API/v1/sandboxes/$ID/exec "${H[@]}" -d @- | jq -r '.stdout + .stderr' &
      i=$((i + 1))
    done; wait
    
    # 4. later: a fresh sandbox from the snapshot – the package and task.py are already there
    EXTRA=$(curl -s -X POST $API/v1/sandboxes "${H[@]}" -d "{\"from_snapshot\": \"$SNAP\", \"timeout_s\": 600}" | jq -r .id)
    curl -s -X POST $API/v1/sandboxes/$EXTRA/exec "${H[@]}" \
      -d '{"cmd": "python3 task.py 0.5", "cwd": "/home/user/work", "timeout_ms": 300000}' | jq -r .stdout
    
    # 5. clean up
    for ID in $SRC $EXTRA $(cat copies.txt); do curl -s -X DELETE $API/v1/sandboxes/$ID "${H[@]}"; done
    curl -s -X DELETE $API/v1/snapshots/$SNAP "${H[@]}"
  2. Run it

    python3 clone_variants.py        # or: npx tsx clone_variants.mts

    Preparing takes a minute or two (the pip install); the clone itself takes seconds to tens of seconds depending on the disk size; the three trainings run at the same time.

How to tell it works

  • The script prints 3 copies from snapshot snap_…, then one accuracy line per variant and one for C=0.5 from the sandbox started from the snapshot. scikit-learn was installed only once – the copies did not install anything.
  • During the run the portal shows the copies on Sandboxes and the snapshot on Snapshots; after the run both lists are back to what they were.

Partial success (HTTP 207)

When only some copies can be created – most often because your plan allows fewer concurrent sandboxes – the clone still succeeds with status 207. The created copies are in the result, the failed ones in errors, one entry per copy: {"index", "name", "status", "code", "error"}. The SDKs return the copies and the errors (copies.errors in Python, errors in TypeScript) and throw an exception only when no copy could be created. That is why the script pairs copies with variants and prints the errors instead of assuming three copies.

Common problems

Status and codeMeaning and fix
207 + 429 quota in errorsSome copies did not fit into your concurrent-sandbox limit. Kill the source after cloning (further copies can start from the kept snapshot with from_snapshot, no running source needed), use fewer copies, or a higher plan.
429 snapshot_limitYou keep as many snapshots as your plan allows – delete old ones (portal → Snapshots, or find them with Snapshot.list() and delete with snap.delete(); TypeScript: wbx.snapshots.list() and wbx.snapshots.delete(id)).
403 feature_disabledSnapshots or clones are turned off for your account – contact support.
409 sandbox_archivedThe source has slept so long it was archived – wake it (resume()) and clone again.
503 snapshot_node_unavailable, 503 clone_network_unknownThe server holding the sandbox or snapshot is busy or being updated – retry in a minute.
400 on cloneFor example count outside 1–10, a template or from_snapshot in the clone request, or an invalid name.
A copy cannot find somethingOnly the disk is copied: start servers again in each copy and pass env again – it is never copied.

If a clone with keep_snapshot creates no copy at all, the SDK raises an error but the snapshot is kept – its ID is in the error body (snapshot_id); delete it in the portal or with Snapshot.get(snapshot_id).delete() (TypeScript: wbx.snapshots.delete(snapshotId)). Snapshots hold everything on the disk, including tokens or .env files a tool saved there. Remove secrets before the snapshot, and delete snapshots you no longer need: they are billed as storage until you do.

Next steps