Repository avatar
Other Tools
v0.4.0
active

fastjudge0

io.github.arbazkhan971/fastjudge0

Rust Judge0 engine with isolate --cg sandboxing across 11 languages (19,729 cases/min on 16 vCPU).

Documentation

FastJudge0

CI Parity Container License: MIT Throughput

Benchmarks · Architecture · Quickstart · AI Agents & MCP · Security · FAQ · Contributing

A drop-in, Judge0-compatible code execution engine written in Rust.
Sustains 19,700+ test-case submissions/min on a single 16-vCPU VM (17×–75× faster than stock Judge0 1.13.1), using the exact same isolate --cg Linux sandbox and compilers — with zero Rails, Redis, or Postgres queue overhead in the hot path.

FastJudge0 vs Stock Judge0 Benchmark


Why We Built This

Stock Judge0 is great for compatibility, but under a 2,000-student coding exam (where 50%+ of traffic was Java), it treats every single test case as an independent Rails request → Postgres row → Resque background job → isolate --init → javac compile → JVM boot → isolate --cleanup.

A 10-case Java submission burns ~11 CPU-seconds and queues hundreds of jobs on 12–16 vCPUs (~387 cases/min).

FastJudge0 keeps Judge0's exact wire API, compilers (judge0/judge0:1.13.1 base image), and Linux isolate --cg sandbox while redesigning the execution path in Rust so one single VM sustains nearly 20,000 test cases/min at $0 extra compute cost.


Measured Benchmarks (c6a.4xlarge, 16-vCPU AMD EPYC 7R13, cgroup v1)

Head-to-head comparison on an identical c6a.4xlarge (judge0/judge0:1.13.1, WORKERS=16), running real 10-case batches (array allocation, sorting, XOR checksum — no trivial print(1) microbenchmarks):

WorkloadStock Judge0 1.13.1FastJudge0 (Rust)SpeedupFastJudge0 p95 LatencyErrors
Python 3.8 (0% cache, unique code)1,567 / min117,713 / min75.1×0.24s (vs 11.47s)0
Java 13 (0% cache, unique code)387 / min7,843 / min20.2×3.67s (vs 46.41s)0
Java 13 (40% template mix)387 / min11,209 / min28.9×3.45s (vs 46.41s)0
C++ GCC 9.2 (0% cache, unique code)756 / min13,221 / min17.5×2.07s (vs 23.81s)0
Sustained Mixed Surge (51% Java, 44% Py, 5% C++)—19,729 / min (15,280 in 46.5s)~20×+2.27s (p50: 0.61s)0
Crash Recovery (OS SIGKILL → healthy verdict)16.63s (16 jobs orphaned)0.274s health / 1.131s verdicts14.7×—0

Ideal Use Cases

  • Online Assessments & Coding Interviews: Survive cohort exam bursts without autoscaling fleets of Judge0 VMs.
  • AI Coding Agents & RL / RLVR Reward Evaluators: Run tens of thousands of unit-test verifications per minute locally or on a single beefy box with low p95 tail latency (0.24s Python / 2.1s C++).
  • Competitive Programming & Interactive Playgrounds: Drop-in speed upgrade for existing Judge0 API clients.

Architecture: How It Gets 17×–75× Without Losing isolate

flowchart LR
  Client["Client (Judge0 HTTP API)"] --> API["FastJudge0 (Rust / Axum / Tokio)"]
  API -->|"Native: Bash, C, C++, Go, Java, JS, PHP, Py, Rust, TS, SQL"| Group["Group batch by (lang, source, flags)"]
  API -->|"Rare languages (Kotlin, Ruby, C#...)"| Upstream["Transparent Proxy -> Stock Judge0"]
  Group -->|"Compiled (Java, C, C++, Go, Rust, TS)"| CC["Compile-Once /dev/shm Cache (OnceCell dedup, timeouts never cached)"]
  CC --> Pool["Pre-warmed isolate --cg Box Pool (in-RAM clean)"]
  Group -->|"Interpreted / SQL"| Pool
  Pool --> Harness{"N >= 2 cases?"}
  Harness -->|"Yes"| Multi["In-Sandbox Batch Harness (1 JVM+URLClassLoader / fork() per case)"]
  Harness -->|"No (1 case / Run)"| Single["Direct isolate --cg --run"]
  Multi -->|"On TLE / OOM / Crash"| Fallback["Automatic Per-Case isolate Fallback"]
  1. Compile Once + /dev/shm Artifact Cache: Compiled submissions (Java, C, C++, Go, Rust, TypeScript) compile once per program with concurrent OnceCell deduplication stored in tmpfs (/dev/shm). Only genuine compile errors are cached — compilation timeouts (TO) are never cached.
  2. In-Sandbox Multi-Case Execution (Zero Cross-Case State Bleed):
    • Java (62): Boots one OpenJDK 13 JVM inside isolate --cg (-XX:TieredStopAtLevel=1 -Xshare:auto -XX:+UseSerialGC) and loads each test case inside a fresh URLClassLoader(..., PlatformClassLoader) + SecurityManager trapping System.exit() — guaranteeing static-field isolation across cases. Any TLE, OutOfMemoryError, or StackOverflowError halts the batch JVM and falls back automatically to individual per-case isolate --cg runs for remaining cases.
    • Python (71): Compiles AST once inside isolate, then os.fork()s per test case with strict RLIMIT_CPU and wall-time wait4() enforcement.
    • C (50), C++ (54), Go (60), Rust (73), SQLite (82): Executes all N cases inside one sandbox against ./a.out, ./main, or a fresh db.sqlite per case.
    • Bash (46), JavaScript (63), PHP (68), TypeScript (74): Execute concurrently across the pre-warmed isolate --cg pool (tsc compiles TypeScript once and runs via Node 12).
  3. Pre-Warmed isolate Box Pool: Initializes WORKERS cgroup v1 boxes on boot (in ~33 ms total), resetting cgroup limits cleanly and wiping box workspaces in memory instead of spawning --init/--cleanup cgroup teardown on every test case.
  4. Full Judge0 1.13.1 Wire Compatibility + Upstream Proxy: Implements /submissions (both single and /submissions/batch), /submissions/:token (GET & DELETE), /languages (/languages/all, /languages/:id), /statuses, /about, /config_info, /workers, ?base64_encoded=true|false|1|0, ?fields=... (* or comma-separated subset), ?authn_token=... / X-Auth-Token, redirect_stderr_to_stdout, and per-submission resource limits (cpu_time_limit, cpu_extra_time, wall_time_limit, memory_limit, stack_limit, max_processes_and_or_threads, max_file_size), returning terminal verdicts inline on POST while transparently proxying unsupported languages to an optional UPSTREAM_JUDGE0_URL.

Security & Isolation Model

  • Host Sandbox Boundary: Untrusted student/agent code always executes inside Linux kernel isolate --cg namespaces, cgroups (cpu, time-wall, cg-mem, nproc, fsize), and read-only mounts — identical to stock Judge0.
  • Cross-Submission Isolation: Distinct programs never share a sandbox or process. Box directories are wiped before every lease.
  • Cross-Test-Case Isolation (Same Program, Multiple Inputs): Since test cases within a single grading batch belong to the same submission, FastJudge0 runs them inside one isolate --cg container using:
    • Python: separate os.fork() child process per test case (RLIMIT_CPU + wait4).
    • C/C++/SQL: separate child process / fresh db.sqlite per test case.
    • Java: separate URLClassLoader(..., PlatformClassLoader) + System.exit trap per case, with automatic per-case isolate --cg fallback if any case times out, OOMs, or overflows the stack.

Parity Verification (24/24 Pass vs Stock Judge0 1.13.1)

Verified side-by-side against judge0/judge0:1.13.1 via benchmarks/parity_test.py:

  • Python (71): 10-case Accepted, Wrong Answer, SyntaxError (11), ZeroDivisionError (11), mixed TLE batch ([3, 5, 3]), sys.exit(0/1), UTF-8 output (नमस्ते 🚀).
  • Java (62): 10-case Accepted, Wrong Answer, Compile Error (6), NullPointerException (11), static-field isolation (static int c = 0; c++; prints 1 on every case), System.exit(0/1), mixed TLE automatic per-case isolate fallback ([3, 5, 3]).
  • C++ (54) / C (50): Accepted, Wrong Answer, Compile Error, TLE (5), SIGSEGV (7 reported directly rather than masked as 11 by a bash wrapper).
  • SQL (82), JavaScript (63), Bash (46): Accepted & Wrong Answer.
  • Wire / Proxy: POST /submissions/?base64_encoded=false&wait=false, GET, DELETE (200 OK), and PHP (68) transparent upstream proxy (Accepted).

Quickstart

Prerequisites: Linux host with cgroup v1 (systemd.unified_cgroup_hierarchy=0 — same kernel requirement as Judge0 isolate) and Docker.

Option A — One-Command Prebuilt Container (ghcr.io)

docker run -d --name fastjudge0 \
  --privileged --shm-size=4g --restart always \
  -p 2358:2358 \
  ghcr.io/arbazkhan971/fastjudge0:latest

Option B — Build from Source (docker compose)

git clone https://github.com/arbazkhan971/fastjudge0.git
cd fastjudge0
docker compose up -d --build

Verify health & run Python:

curl -s http://127.0.0.1:2358/healthz
# {"engine":"fastjudge0-rust","status":"ok"}

curl -s -X POST "http://127.0.0.1:2358/submissions/?base64_encoded=false" \
  -H "Content-Type: application/json" \
  -d '{"language_id":71,"source_code":"print(6*7)","stdin":""}'

Drop-in Acceleration Alongside Existing Judge0

Bind FastJudge0 to your public port (with --privileged --shm-size=4g) and keep your existing Judge0 container on 127.0.0.1:2359 (or :2358) with COUNT=2:

UPSTREAM_JUDGE0_URL=http://127.0.0.1:2358

Native languages (~99% of exam workloads) execute in Rust + isolate; every other Judge0 language transparently proxies upstream.


For AI Agents (Zero-Wrapper Built-in MCP, A2A & llms.txt)

FastJudge0 is agent-native at both repo and runtime level — agents can auto-discover capabilities from the running binary or directly from GitHub:

1. Built-in Runtime Discovery & Native Streamable HTTP MCP (/mcp)

When FastJudge0 is running, point any MCP Streamable HTTP or A2A agent directly at it (no Python wrapper needed):

2. Repo, SDKs & Registry Discovery Manifests

{
  "mcpServers": {
    "fastjudge0": {
      "command": "python3",
      "args": ["/path/to/fastjudge0/examples/mcp_server.py"],
      "env": {
        "FASTJUDGE0_URL": "http://127.0.0.1:2358"
      }
    }
  }
}

Configuration

VariableDefaultDescription
BIND_ADDR0.0.0.0Listen IP
PORT2358Listen port
WORKERShost CPU countNumber of pre-warmed isolate sandboxes
BOX_ID_START900Starting isolate box ID (keep disjoint from Stock Judge0)
CACHE_DIR/dev/shm/fastjudge0-cacheContent-addressed compiled binary/.class cache directory
CACHE_MAX_ENTRIES2048Max cached programs before FIFO eviction
BATCH_HARNESS_ENABLEDtrueSet false for strict per-case isolate execution while keeping compile cache + box pool
TOKEN_TTL_SECS900In-memory submission token retention for GET/DELETE
MAX_QUEUE_SIZE2000Max concurrent in-flight batches before 503 backpressure
AUTHN_HEADER / AUTHN_TOKENX-Auth-Token / (unset)Optional shared auth header check
UPSTREAM_JUDGE0_URL(unset)Optional Stock Judge0 base URL for rare languages & legacy tokens
CPU_TIME_LIMIT / WALL_TIME_LIMIT / MEMORY_LIMIT5.0 / 10.0 / 128000Default per-case limits (seconds / KB)

FAQ & Honest Trade-Offs

  • Why does FastJudge0 require Linux cgroup v1 (systemd.unified_cgroup_hierarchy=0)?
    The upstream judge0/judge0:1.13.1 base image bundles isolate 1.8.1, which reads cgroup v1 memory + cpuacct controllers. Booting the host kernel with systemd.unified_cgroup_hierarchy=0 (standard for Judge0 deployments) gives full --cg accounting.
  • What if I cannot share an isolate box across test cases of the same submission?
    Set BATCH_HARNESS_ENABLED=false. FastJudge0 still runs your compile-once /dev/shm cache and pre-warmed box pool while isolating every single test case in its own isolate --cg --run call.
  • What happens to languages beyond the 11 native fast-path ones?
    Set UPSTREAM_JUDGE0_URL=http://127.0.0.1:2359 pointing to a lightweight stock Judge0 instance (COUNT=2); Kotlin, Ruby, C#, Swift, Haskell, etc. proxy automatically without changing clients.

Roadmap & Project Docs

  • Native fast paths & batch harnesses for Go (60), Rust (73), TypeScript (74), and PHP (68)

  • Prometheus GET /metrics/prometheus + Accept: text/plain content negotiation

  • Zero-dependency Python & TypeScript SDKs (sdks/python, sdks/typescript) + OpenAI/Anthropic schemas

  • Pre-built multi-arch (amd64 + arm64) images on ghcr.io

  • Security Model & Vulnerability Disclosure: SECURITY.md

  • Release History: CHANGELOG.md

  • Developer & Agent Contributing Guide: CONTRIBUTING.md · AGENTS.md

Contributions are very welcome — see CONTRIBUTING.md.


License

MIT © Arbaz Khan

OCI
ghcr.io/arbazkhan971/fastjudge0:0.4.0
Install Command
docker pull ghcr.io/arbazkhan971/fastjudge0:0.4.0:undefined