# A long job with a price limit and a signed receipt

Some work takes minutes or hours. A **background job** runs it in its own sandbox on our servers – you submit it, disconnect, and come back for the result. A **price limit** guarantees it never costs more than you allow, and a **signed receipt** proves later what ran and what it produced.

## What you'll build

A script that submits a CPU-heavy computation (counting prime numbers) as a job with a hard price limit, waits for it without polling, downloads the result file, and saves and checks the receipt signed by WBX. The same pattern fits data processing, model evaluation or report generation.

## What you need

- A WBX Sandbox **API key** in `WBXSANDBOX_API_KEY`.
- Python: `pip install "wbxsandbox[verify]"` (the extra installs `cryptography` for checking signatures). TypeScript: `npm install wbxsandbox` and Node.js 20+. curl: `jq` and OpenSSL 3.
- About **10 minutes**; the job itself runs a minute or two.

## How the price limit works

A job is billed per second of run time at the price of its compute class. With `max_cost` the server computes the *worst case* **before** accepting the job: the whole `timeout_s` plus about 7 minutes reserved for starting the sandbox and uploading the results, times the number of attempts (1 unless you set retries), at that price. Here that is 900 s + 420 s on the 2 vCPU / 512 MB `base` template – about 0.025 in EUR or USD, 0.57 in CZK. If the worst case could exceed the limit, the job is refused right away (`422 budget_too_low`, and the message says which timeout would fit); once accepted, it cannot cost more. The amount is in your account's billing currency (CZK, EUR or USD) – the examples use `0.05`, which suits EUR or USD; for CZK use `1.50`.

## Steps

1. ### The whole script

   Only files matching `artifacts` survive the job – everything else is deleted with its sandbox. `required_artifacts` makes the job fail if the result file is missing, and `idempotency_key` makes it safe to run the script twice: the second submission returns the same job instead of starting another one.

   **Python**

   ```
   # long_job.py
   import json
   from wbxsandbox import run_job, receipt_keys, verify_receipt

   MAX_COST = "0.05"          # in your billing currency (for CZK use "1.50")
   COMMAND = r"""
   mkdir -p output
   python3 - <<'EOF'
   import json, math, time
   t = time.time()
   count = sum(1 for n in range(2, 2_000_000) if all(n % d for d in range(2, math.isqrt(n) + 1)))
   json.dump({"primes_below_2M": count, "seconds": round(time.time() - t, 1)}, open("output/primes.json", "w"))
   print("done", count)
   EOF
   """

   job = run_job(command=COMMAND, template="base", timeout_seconds=900, max_cost=MAX_COST,
                 artifacts=["output/"], required_artifacts=["output/primes.json"],
                 idempotency_key="primes-demo-1")
   print("submitted", job.id)    # keep the ID – get_job(job_id) finds it from any other program

   job.wait()                    # server-side waiting, no polling
   s = job.summary()
   print(s["status"], "exit", s.get("exit_code"), "cost", s.get("cost"), "files", s.get("artifact_names"))
   if s["status"] != "completed":
       print(job.digest("errors")["text"])     # the error lines of the log
       raise SystemExit(1)

   print(json.loads(job.download("output/primes.json")))   # SHA-256 is checked

   # the receipt signed by WBX – keep it with your results
   signed = job.signed_receipt()
   with open(f"{job.id}.receipt.json", "w") as f:
       json.dump({"signed_receipt": signed}, f)
   key = next(k["public_key"] for k in receipt_keys() if k["key_id"] == signed["key_id"])
   receipt = verify_receipt(signed, key)["execution_receipt"]   # ValueError if anything was changed
   print("receipt OK:", receipt["status"], [(a["name"], a["sha256"][:12]) for a in receipt["artifacts"]])
   ```

   **TypeScript**

   ```
   // long_job.mts (an ES module – top-level await)
   import { verify } from "node:crypto";
   import { writeFile } from "node:fs/promises";
   import { WBX } from "wbxsandbox";

   const MAX_COST = "0.05"; // in your billing currency (for CZK use "1.50")
   const COMMAND = `
   mkdir -p output
   python3 - <<'EOF'
   import json, math, time
   t = time.time()
   count = sum(1 for n in range(2, 2_000_000) if all(n % d for d in range(2, math.isqrt(n) + 1)))
   json.dump({"primes_below_2M": count, "seconds": round(time.time() - t, 1)}, open("output/primes.json", "w"))
   print("done", count)
   EOF
   `;

   const wbx = new WBX();
   const job = await wbx.jobs.create({
     command: COMMAND, template: "base", timeoutSeconds: 900, maxCost: MAX_COST,
     artifacts: ["output/"], requiredArtifacts: ["output/primes.json"],
     idempotencyKey: "primes-demo-1",
   });
   console.log("submitted", job.id); // keep the ID – wbx.jobs.get(id) finds it from any other program

   await job.wait(); // server-side waiting, no polling
   const s = await job.summary();
   console.log(s.status, "exit", s.exit_code, "cost", s.cost, "files", s.artifact_names);
   if (s.status !== "completed") {
     console.log((await job.digest({ mode: "errors" })).text); // the error lines of the log
     process.exit(1);
   }

   const data = await job.download("output/primes.json"); // SHA-256 is checked
   console.log(JSON.parse(new TextDecoder().decode(data)));

   // the receipt signed by WBX – keep it with your results
   const signed = await job.signedReceipt();
   await writeFile(`${job.id}.receipt.json`, JSON.stringify({ signed_receipt: signed }));
   const { keys } = (await (await fetch(`${wbx.baseURL}/v1/receipt-keys`)).json()) as
     { keys: { key_id: string; public_key_pem: string }[] };
   const key = keys.find((k) => k.key_id === signed.key_id);
   if (!key) throw new Error(`unknown signing key ${signed.key_id}`);
   const payload = Buffer.from(signed.payload, "base64");
   if (!verify(null, payload, key.public_key_pem, Buffer.from(signed.signature, "base64"))) {
     throw new Error("receipt signature does not match");
   }
   const receipt = JSON.parse(payload.toString("utf8")).execution_receipt;
   console.log("receipt OK:", receipt.status, receipt.artifacts.map((a: { name: string; sha256: string }) => [a.name, a.sha256.slice(0, 12)]));
   ```

   **curl**

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

   # the command as a JSON string (jq does the quoting)
   CMD=$(cat <<'SH'
   mkdir -p output
   python3 -c 'import json, math; c = sum(1 for n in range(2, 2_000_000) if all(n % d for d in range(2, math.isqrt(n) + 1))); json.dump({"primes_below_2M": c}, open("output/primes.json", "w"))'
   SH
   )
   JOB=$(jq -n --arg cmd "$CMD" '{command: $cmd, template: "base", timeout_s: 900, max_cost: "0.05",
           artifacts: ["output/"], required_artifacts: ["output/primes.json"], idempotency_key: "primes-demo-1"}' |   # for CZK use max_cost "1.50"
         curl -s -X POST $API/v1/jobs "${H[@]}" -d @- | jq -r .id)
   echo "submitted $JOB"

   # wait (the server answers as soon as the job ends, at most after 60 s)
   until curl -s -X POST $API/v1/jobs/wait "${H[@]}" -d "{\"job_ids\": [\"$JOB\"], \"timeout_s\": 60}" | jq -e .done >/dev/null; do :; done

   curl -s $API/v1/jobs/$JOB/summary "${H[@]}" | jq '{status, exit_code, cost, artifact_names}'
   curl -s $API/v1/jobs/$JOB/artifacts/output/primes.json "${H[@]}"

   # signed receipt, checked with the public key of WBX
   curl -s "$API/v1/jobs/$JOB/receipt?signed=1" "${H[@]}" > $JOB.receipt.json
   KEY_ID=$(jq -r .signed_receipt.key_id $JOB.receipt.json)
   curl -s $API/v1/receipt-keys | jq -r --arg k "$KEY_ID" '.keys[] | select(.key_id == $k) | .public_key_pem' > wbx.pem
   jq -r .signed_receipt.payload $JOB.receipt.json | base64 -d > payload.bin
   jq -r .signed_receipt.signature $JOB.receipt.json | base64 -d > sig.bin
   openssl pkeyutl -verify -pubin -inkey wbx.pem -rawin -in payload.bin -sigfile sig.bin && jq .execution_receipt.artifacts payload.bin
   ```
2. ### Disconnect and come back

   Nothing ties the job to your script: stop it after `submitted job_…` and pick the job up later – from another program, another machine or the portal (*Jobs*).

   **Python**

   ```
   from wbxsandbox import get_job
   job = get_job("job_…").wait()
   print(job.summary()["status"])
   ```

   **TypeScript**

   ```
   const job = await (await wbx.jobs.get("job_…")).wait();
   console.log((await job.summary()).status);
   ```

   The log, result files and receipt are kept for 7 days after the job ends, also when its sandbox is long gone.

## How to tell it works

- The script prints `completed exit 0 cost …` with a cost at or below your limit, then `{'primes_below_2M': 148933, …}` (148,933 primes below two million – the same number every time).
- `receipt OK` appears, and the file `job_….receipt.json` is next to your script. Change one character in its payload and the check fails – that is the point.
- The portal shows the job under *Jobs* with its log, result file and a *Download signed receipt* button.

## Common problems

| Status and code | Meaning and fix |
| --- | --- |
| `422 budget_too_low` | The worst case – (`timeout_s` + about 7 minutes reserved for start and result upload) × the number of attempts, at your class price – is above `max_cost`. The message says which `timeout_s` would fit – lower it, or raise the limit. Remember the limit is in your billing currency. |
| `422 cost_unavailable` | A price limit or budget is set, but it cannot be guaranteed: prices are not available for your account, or the limit is in another currency than your account is billed in (for example `max_cost_eur` on an account billed in CZK or USD). Use `max_cost` in your billing currency; contact support if it persists. |
| `402 budget_exceeded` | The job would exceed your monthly or daily budget (portal → *Billing*, or `get_budget()`). Raise the budget or wait for the next day / month. |
| `429 queue_full` | You already have the maximum of queued jobs (1000) – wait for some to start. |
| `409 idempotency_conflict` | The same `idempotency_key` was used for a different job – use a new key when you change the command. |
| Job `expired`, error `timeout` | The command ran longer than `timeout_s` and was stopped (the job ends as `expired`, not `failed`); the cost is still within the limit. Raise `timeout_s` (and the limit) or make the work smaller. |
| Job `failed`, error `nonzero_exit` | Your command failed – read `job.digest("errors")` or *Jobs* → log. |
| Job `failed`, error `artifact_missing` | A file from `required_artifacts` was not created. Paths are relative to the working directory (`/home/user`). |
| `409 receipt_not_final` | A signed receipt exists only after the job has ended – wait first. |
| Job stays `queued` | Your concurrent-sandbox limit is in use (running sandboxes count too) or no server of the class is free. It starts as soon as there is room; it is never moved to a weaker class. |

## Next steps

- [A batch of 100 tasks](https://sandbox.wbx.cz/docs/guides/batch.md): Many jobs, one call, one price limit.
- [Execution receipts](https://sandbox.wbx.cz/docs/jobs/receipts.md): Every field of the receipt and how signing works.
- [Budgets](https://sandbox.wbx.cz/docs/jobs/budget.md): Monthly and daily limits for all jobs together.
- [Background jobs](https://sandbox.wbx.cz/docs/jobs.md): All job options in one place.

Source: https://sandbox.wbx.cz/docs/guides/long-job
