# A batch of 100 tasks with dependencies and a CSV report

When the same work has to run many times – 100 files, 100 parameter settings, 100 customers – submit it as a **batch**: one call, each task in its own clean sandbox, a limit on how many run at once, one price limit for the whole batch, and a report at the end. A task that fails does not stop the others.

## What you'll build

A batch of 101 jobs: job 0 prepares the data (100 chunks of numbers), jobs 1–100 each wait for it, take their chunk and count the prime numbers in it. You get a CSV report with one row per job and the 100 results collected into one file on your computer.

**Job or batch?** A *job* is one command in its own sandbox that runs without an open connection and keeps its result files. A *batch* is up to 1000 jobs submitted together; jobs inside it can depend on each other (`depends_on`) and take result files of earlier jobs as input.

## What you need

- A WBX Sandbox **API key** in `WBXSANDBOX_API_KEY`; `pip install wbxsandbox` or `npm install wbxsandbox` (curl: `jq`).
- About **15 minutes**. The batch runs at most 10 jobs at a time; on a plan with fewer concurrent sandboxes the jobs simply wait their turn.

## Steps

1. ### The whole script

   Every job writes into `output/`; `save_artifacts` keeps that folder as the job's result files. A worker gets the prepared file through `inputs` with `from_index: 0` – it appears in the worker's `input/` folder, checked by SHA-256 – and `depends_on: [0]` makes it start only after job 0 has completed. If job 0 fails, its dependants are cancelled with `dependency_failed` instead of running on missing data.

   **Python**

   ```
   # batch_primes.py
   import json
   from wbxsandbox import run_batch, batch_input, get_job

   MAX_TOTAL_COST = "1.00"     # for the whole batch, in your billing currency (for CZK use "25")

   PREPARE = """mkdir -p output && python3 -c '
   import json, random
   random.seed(1)
   json.dump([[random.randint(2, 10**6) for _ in range(2000)] for _ in range(100)], open("output/chunks.json", "w"))'"""

   WORKER = """mkdir -p output && python3 -c '
   import json, math, os
   i = int(os.environ["CHUNK"])
   nums = json.load(open("input/chunks.json"))[i]
   primes = sum(1 for n in nums if all(n % d for d in range(2, math.isqrt(n) + 1)))
   json.dump({"chunk": i, "numbers": len(nums), "primes": primes}, open("output/result.json", "w"))
   print("chunk", i, "primes", primes)'"""

   jobs = [{"command": PREPARE}]
   for i in range(100):
       jobs.append({"command": WORKER, "env": {"CHUNK": str(i)}, "depends_on": [0],
                    "inputs": [batch_input(0, "output/chunks.json")]})

   batch = run_batch(jobs, defaults={"template": "mini", "timeout_seconds": 120, "save_artifacts": True},
                     max_concurrency=10, max_total_cost=MAX_TOTAL_COST, name="primes-demo")
   print("batch", batch.id, "with", len(batch.job_ids), "jobs")

   batch.wait()                                         # server-side waiting, no polling
   s = batch.summary()
   print(s["status"], "succeeded", s["succeeded"], "failed", s["failed"], "cost", s["cost"])

   with open("report.csv", "w") as f:
       f.write(batch.report_csv())                       # one row per job

   results = []
   for row in batch.report()["jobs"]:
       if row["index"] > 0 and row["status"] == "completed":
           results.append(json.loads(get_job(row["job_id"]).download("output/result.json")))
   json.dump(results, open("results.json", "w"), indent=1)
   print(len(results), "results, primes in total:", sum(r["primes"] for r in results))
   ```

   **TypeScript**

   ```
   // batch_primes.mts (an ES module – top-level await)
   import { writeFile } from "node:fs/promises";
   import { WBX, type BatchJobParams } from "wbxsandbox";

   const MAX_TOTAL_COST = "1.00"; // for the whole batch, in your billing currency (for CZK use "25")

   const PREPARE = `mkdir -p output && python3 -c '
   import json, random
   random.seed(1)
   json.dump([[random.randint(2, 10**6) for _ in range(2000)] for _ in range(100)], open("output/chunks.json", "w"))'`;

   const WORKER = `mkdir -p output && python3 -c '
   import json, math, os
   i = int(os.environ["CHUNK"])
   nums = json.load(open("input/chunks.json"))[i]
   primes = sum(1 for n in nums if all(n % d for d in range(2, math.isqrt(n) + 1)))
   json.dump({"chunk": i, "numbers": len(nums), "primes": primes}, open("output/result.json", "w"))
   print("chunk", i, "primes", primes)'`;

   const jobs: BatchJobParams[] = [{ command: PREPARE }];
   for (let i = 0; i < 100; i++) {
     jobs.push({ command: WORKER, env: { CHUNK: String(i) }, dependsOn: [0],
                 inputs: [{ fromIndex: 0, name: "output/chunks.json" }] });
   }

   const wbx = new WBX();
   const batch = await wbx.batches.create({
     jobs, defaults: { template: "mini", timeoutSeconds: 120, saveArtifacts: true },
     maxConcurrency: 10, maxTotalCost: MAX_TOTAL_COST, name: "primes-demo",
   });
   console.log("batch", batch.id, "with", batch.jobIds.length, "jobs");

   await batch.wait(); // server-side waiting, no polling
   const s = await batch.summary();
   console.log(s.status, "succeeded", s.succeeded, "failed", s.failed, "cost", s.cost);

   await writeFile("report.csv", await batch.reportCsv()); // one row per job

   const results: { chunk: number; primes: number }[] = [];
   for (const row of (await batch.report()).jobs) {
     if (row.index === 0 || row.status !== "completed") continue;
     const job = await wbx.jobs.get(row.job_id);
     results.push(JSON.parse(new TextDecoder().decode(await job.download("output/result.json"))));
   }
   await writeFile("results.json", JSON.stringify(results, null, 1));
   console.log(results.length, "results, primes in total:", results.reduce((a, r) => a + r.primes, 0));
   ```

   **curl**

   ```
   H=(-H "Authorization: Bearer $WBXSANDBOX_API_KEY" -H "Content-Type: application/json")
   API=https://sandbox.wbx.cz

   PREPARE='mkdir -p output && python3 -c "import json, random; random.seed(1); json.dump([[random.randint(2, 10**6) for _ in range(2000)] for _ in range(100)], open(\"output/chunks.json\", \"w\"))"'
   WORKER='mkdir -p output && python3 -c "import json, math, os; i = int(os.environ[\"CHUNK\"]); nums = json.load(open(\"input/chunks.json\"))[i]; p = sum(1 for n in nums if all(n % d for d in range(2, math.isqrt(n) + 1))); json.dump({\"chunk\": i, \"numbers\": len(nums), \"primes\": p}, open(\"output/result.json\", \"w\"))"'

   # 101 jobs: job 0 prepares, jobs 1–100 depend on it and take its file as input
   BATCH=$(jq -n --arg prep "$PREPARE" --arg work "$WORKER" '{
       name: "primes-demo", max_concurrency: 10, max_total_cost: "1.00",   # for CZK use "25"
       defaults: {template: "mini", timeout_s: 120, save_artifacts: true},
       jobs: ([{command: $prep}] + [range(100) | {command: $work, env: {CHUNK: tostring}, depends_on: [0],
              inputs: [{from_index: 0, name: "output/chunks.json"}]}])
     }' | curl -s -X POST $API/v1/batches "${H[@]}" -d @- | jq -r .batch.id)
   echo "batch $BATCH"

   until curl -s -X POST $API/v1/jobs/wait "${H[@]}" -d "{\"batch_ids\": [\"$BATCH\"], \"timeout_s\": 60}" | jq -e .done >/dev/null; do :; done

   curl -s $API/v1/batches/$BATCH "${H[@]}" | jq '{status, succeeded, failed, cost}'
   curl -s "$API/v1/batches/$BATCH/report?format=csv" "${H[@]}" -o report.csv
   # the result file of one job (here the job with index 1)
   J1=$(curl -s $API/v1/batches/$BATCH/report "${H[@]}" | jq -r '.jobs[] | select(.index == 1) | .job_id')
   curl -s $API/v1/jobs/$J1/artifacts/output/result.json "${H[@]}"
   ```

   Why `1.00`: the batch is accepted only if the worst case of all jobs together fits the limit. For each job that is its `timeout_s` (120 s) plus about 7 minutes reserved for starting the sandbox and uploading results, on the 1 vCPU / 256 MB `mini` template – 101 × 540 s comes to about 0.53 in USD, 0.48 in EUR and 12 in CZK. The real cost is a small fraction of that, because the jobs take seconds.
2. ### Run it and open the report

   ```
   python3 batch_primes.py        # or: npx tsx batch_primes.mts
   ```

   `report.csv` has the columns `index, job_id, status, exit_code, duration_s, cost, attempts, artifacts, error_code, error` – open it in any spreadsheet. `results.json` holds the 100 worker results.

## How to tell it works

- The summary says `completed succeeded 101 failed 0` and a cost at or below your limit.
- `report.csv` has 101 rows plus the header; every row is `completed` with `exit_code` 0 and `artifacts` 1.
- Run it again: `random.seed(1)` makes the data the same, so the total number of primes is the same every time.
- In the portal, *Jobs* lists the batch with its progress while it runs.

## Common problems

| Status and code | Meaning and fix |
| --- | --- |
| `422 budget_too_low` | The worst case of all jobs together is above `max_total_cost`: for each job (`timeout_s` + about 7 minutes reserved for start and result upload) × its number of attempts, at its class price. The message gives the worst case – lower the timeouts, submit fewer jobs, or raise the limit (in your billing currency). |
| `402 budget_exceeded` | The batch would exceed your monthly or daily budget; the whole batch is reserved at once. |
| `429 queue_full` | This batch would put more than 1000 of your jobs in the queue – wait or submit fewer. |
| `400 invalid_batch` | For example more than 1000 jobs, or `max_concurrency` outside 1–100. |
| `400 invalid_depends_on` | `depends_on` points outside the batch or forms a cycle. |
| Rows with `dependency_failed` | Job 0 failed, so its dependants did not run. Look at job 0 first (`get_job(id).digest("errors")`). |
| Rows with `nonzero_exit`, or `expired` with `timeout` | That job's command failed, or ran too long and was stopped. The batch ends as `partial`; fix the command and start just the failed jobs again (`job.retry()`) or a new batch. |
| Jobs stay `queued` long | At most `max_concurrency` jobs of the batch run at once, and never more than your plan's concurrent sandboxes. Running sandboxes of your own count too. |

## Next steps

- [Batches reference](https://sandbox.wbx.cz/docs/jobs/batches.md): Summary fields, report, cancelling and idempotency.
- [Passing files between jobs](https://sandbox.wbx.cz/docs/jobs/inputs.md): Inputs from earlier jobs and from the same batch.
- [Repository tests in CI](https://sandbox.wbx.cz/docs/guides/ci-tests.md): Get notified by a signed webhook instead of waiting.

Source: https://sandbox.wbx.cz/docs/guides/batch
