This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
CodeRunner is a Python WebSocket server that compiles and runs code snippets for LiaScript courses. It has two halves that must stay in sync:
- Server (
server.py+compiler/): receives source files over a WebSocket, compiles them, and streams the running process's stdout back. - Client (
README.md): the README is itself a LiaScript template. Its HTML-comment header defineswindow.CodeRunner(the WebSocket client, including the hardcoded server URL) and the@LIA.eval/@LIA.<language>macros that coursesimport:. The "Implementation" section near the end of the README repeats that header code for copy-paste, so keep both copies identical when you change either (tests/test_weights.pyfails when they differ).
There is no linter config or build step. The tests are end-to-end tests against a Docker image.
pip3 install -r requirements.txt
python3 server.py --port 4000 --host 0.0.0.0 # or set CODERUNNER_PORT / PORT, CODERUNNER_HOST (default 0.0.0.0:8000)
docker build -t liascript/coderunner . # full image with every language toolchain (large, slow)
docker run -p 4000:4000 -e PORT=4000 liascript/coderunner
tests/run.sh liascript/coderunner # all tests (tests/e2e.py) against an image
python3 -m unittest tests.test_scheduler tests.test_weights tests.test_jail # queue, weights and lock alone, no Docker neededThe Docker CMD passes --port $PORT, so PORT must be set. Running exec commands outside the container needs firejail installed, because every command is prefixed with it.
tests/run.sh starts the server like Heroku does: as a non-root user with HOME=/coderunner and no access to /root. Tests that pass as root can fail there. A test is one hello(...) line in tests/e2e.py; run a subset by commenting out lines or by calling python3 tests/e2e.py ws://host:port/ against any running server (needs websocket-client).
To test by hand, point a course at ws://localhost:4000/ (the commented-out CodeRunner.init(...) lines in the README header), or send JSON messages from any WebSocket client.
Each client gets a dict of Projects keyed by the message uid. Each Project owns a tempfile.mkdtemp() directory, in CODERUNNER_RUNS (/runs in the image, by default /tmp). A project lives for one run (the client uses a new uid per run): remove_project deletes it when the run has finished, failed to compile, raised an error or was stopped, and when the client disconnects. A stdin or stop for an unknown uid does not create a project. One JSON message may hold several of these keys, handled in this order:
data: a list of[filename, content]pairs, written into the project dir. Reply:service: "data".compile: a command string, sent tocompiler.run. Reply:service: "compile"withok,messageandproblems.run: a blockingsubprocess.run. Reply:service: "run".exec(+filter, a glob or null): starts apexpectprocess in a thread and streamsservice: "stdout"chunks. When the process ends it sendsservice: "stop", which carries the base64 images, videos andfilter-matched files found in the project dir.stdin: queued and sent to the running process.stop: kills the process.
Limits and errors:
- Returned images, videos and files are limited to
MAX_FILE_SIZE(10 MB) each andMAX_TOTAL_SIZE(25 MB) per run, because they are held in memory as base64. Larger files are skipped and named in theerrorof thestopmessage. The dyno has 512 MB of RAM. - File names in
datamust stay inside the project dir (no absolute paths, no../). - A run is stopped after
MAX_OUTPUT_SIZE(2 MB) of output. A message larger thanMAX_MESSAGE_SIZE(4 MB) closes the connection; the limit sits inNewWebSocketHandler.read_bytes, because the library reads a message as a whole. - Removing a project calls
kill_processes_in: it kills every process whose working directory is inside the project dir, which also catches programs that detached withsetsidornohup. safe_message_receivedwraps the handler: an exception does not end the connection, it is answered asservice: "stop"withok: falseanderror, which the client shows and which ends the run.Process.read_linewaits up to 50 ms for output. Do not set that timeout to 0: the loop inspawn()then spins on a full core per running program.
The queue (scheduler.py, used through scheduler in server.py):
- A run needs a slot for
compile,runandexecand keeps it untilremove_project. A compile commandnoneneeds none, the slot is then taken forexec. At mostMAX_RUNS_PER_CLIENT(2) runs per connection hold a slot, at mostMAX_RUNSon the server (two per CPU,CODERUNNER_MAX_RUNS). A connection may haveMAX_PROJECTS_PER_CLIENT(20) runs, running or waiting. - Slots are limited by memory: every run has a weight in MB, and the weights of all runs with a slot have to fit into
capacity(): 85 % of the memory (CODERUNNER_MEMORY_MB, default the limit of the container), less what everything else uses. So many light runs (assembler, C) or a few heavy ones (dotnet, kotlinc) run at once. - The weight starts as an estimate from the command (
weights.py: the heaviest program in it, a compiled./programcounts asNATIVE, an unknown program asDEFAULT) and changes with the phase: the compiler, then the program. AfterSETTLEsecondsmeasure_memoryreplaces it once a second by what the processes of the run really use (PSS of all processes with a working directory in the project folder). A lighter run may overtake one that does not fit, until that one has waited 15 s. WEIGHTSinweights.pyis measured:tools/measure_weights.pyruns every example ofREADME.mdin a container with the memory of the production server and prints the table. Run it again after changing the image or adding a language;tests/test_weights.pyfails if a program of a README macro has no weight.- Free slots go to the connection that was served least recently, so one client with many queued runs does not hold up the others.
- With a free slot the work runs in the thread of the connection, as before. A run that had to wait runs in a thread of its own (
work), and the client gets astdoutmessage that the server is busy; it is sent as output so that old copies of the template show it. - While runs wait, a run without input or output for
IDLE_LIMITseconds (30,CODERUNNER_IDLE_LIMIT) is stopped with an error (evict). Without it a few programs waiting for input would block all slots for 300 s. A run incompileorrunisbusyand never evicted. - The run time limit itself is the
timeout -k 5 300of the sandbox prefix (60 s fordotnet run); when it fires, the run ends and frees its slot. tests/run.shstarts a second server with 2 slots and a 3 s idle limit for the queue tests (QUEUE_URL) and a third one with 300 MB for the test of the weights (MEMORY_URL);e2e.pyskips them against any other server.
The plain string "ping" is a keepalive that the client sends every 15 s. Non-WebSocket HTTP requests get a 200 OK (Heroku health check; see NewWebSocketHandler.handshake).
The client flow (in the README @LIA.eval_ macro) is data → compile → exec. The compile command none skips compilation.
compiler/compiler.py: run picks a language module by the prefix of the compile command (gcc , javac , rustc , cobc , …). Each module (compiler/<lang>.py) runs the compiler and parses its output into Problem dicts (file, type, row 0-based, col, text). formatting() then groups these per file, in the order of the files list, so the LiaScript editor can annotate the right code block. helper.c_like_find_all handles the common file:row:col: error: msg format.
Unknown compile commands fall through to a generic path where any stderr output means failure. To add proper error annotation for a language, add a module and a prefix branch in compiler.py.
Sandboxing, in compiler/helper.py: every command starts as prefix + command, which is firejail … timeout 300 python3 -I jail.py command. compile and run go through sandboxed(), which wraps the whole command line in sh -c '…' so that commands after ;, && or | are covered too. dotnet exec is special-cased in Project.exec (timeout 60 nice -19, then jail.py). Inside Docker, firejail silently does nothing (locally and on Heroku: no namespaces, no setuid). What separates the runs is jail.py.
All runs belong to one user, so without a lock a program can read and change the folders of all other runs and the code of the server, read the environment of the server and end it. jail.py uses Landlock, which needs no rights and works on Heroku (Linux 6.17, Landlock 7). The rules are in its docstring; in short: a run reads everything except the folders of other runs, writes to its own folder, /dev, $HOME, /tmp, /var/tmp and the caches in /opt that are open to all (chmod a+rwX), and can signal or inspect only processes of its own run (Linux 6.12, the server reports at its start what the kernel offers). The network stays open, on purpose. CPU, memory and disk are not limited by it; the container stays the outer wall.
What follows from it:
- The folders of the runs are in
/runs(CODERUNNER_RUNS), not in/tmp. So/tmpcan stay open to all: the JVM (jansi of kotlinc, JNA, hsperfdata) and Roslyn write there whateverTMPDIRsays. With the folders in/tmpthe lock closes/tmp, and Kotlin and SelectScript fail.TMPDIRis.tmpin the folder of the run, for the tools that follow it. server.pysetsHOMEto a folder of its own in/tmp, which all runs share. On HerokuHOMEis the folder of the server, and a run may write to its home.- A helper that outlives its run and serves the next ones has the rights of the run that started it. So dotnet builds without its compiler server (
UseSharedCompilation=falseinserver.py): a C# build takes 2.4 s instead of 0.75 s. The server cannot be shared safely, any run could let it read the files of the others. Callingcscdirectly takes 0.6 s and 100 MB, but has to copy what the project file sets (references, implicit usings, defines); not built. - A new tool that writes outside of the folder of its run needs its cache in
$HOME, or a folder in/optwithchmod a+rwX. - A run cannot read
/proc/<pid>/cmdlineof other processes, only their names. Tests that watch the server from inside a run go by the name (NAMEDintests/e2e.py). - Tests:
tests/test_jail.pytries every version of Landlock the kernel offers. Intests/e2e.py:a run is locked into its folder. To check a change, run all examples of the README and compare the output with and without the lock.
This usually touches three places:
Dockerfile: install the toolchain (apt list, or a dedicatedRUNblock for tools not packaged on Ubuntu 26.04).README.mdheader: add the@LIA.<lang>shortcut, which is@LIA.eval(\["file"]`, `compile cmd`, `run cmd`). Add an_withShellvariant for REPLs. Also add a### Lang : `@LIA.`` example section under "Languages", and mirror the header change in the "Implementation" section.- Optionally
compiler/<lang>.py+ a dispatch branch for error parsing.
Heroku runs the container as a non-root user with HOME=/coderunner. Install toolchains outside of /root (in /opt or /usr/local/bin) and keep caches and package repositories out of $HOME, or they are missing or downloaded again on every run. See the Julia, Nim, Clojure (CLJ_CONFIG, :mvn/local-repo), .NET (NUGET_PACKAGES) and Gleam blocks in the Dockerfile. Toolchains not from apt are pinned with an ARG …_VERSION.
The image is based on Ubuntu 26.04 (GCC 15, Python 3.14, OpenJDK 25, .NET 10):
- Python 2.7 and GNU Smalltalk no longer exist there. They are installed from the 22.04 and 24.04 archives, which
/etc/apt/preferences.d/olderpins below 26.04, so nothing else comes from them. - GCC 15 defaults to C23 and turns loose pointer types into errors. Old C code built from source (Io) needs
-std=gnu17 -fpermissive. - pip needs
PIP_BREAK_SYSTEM_PACKAGESandPIP_IGNORE_INSTALLED, because apt owns the system Python packages. - Courses with an older copy of the template still send
net8.0projects. The warm-up restores that targeting pack too, andDOTNET_ROLL_FORWARD=LatestMajorruns them on .NET 10. - The dotnet templates start the built program (
dotnet bin/Debug/net10.0/project.dll), notdotnet run: that loads the build system once more, which costs 0.8 s and about 110 MB for as long as the program runs.compiler/dotnet.pytherefore has to report a failed build as failed. GC settings (DOTNET_gcServer,DOTNET_GCConserveMemory, …) were measured and do not help. The compiler server is off because of the lock, see there. - Q# runs through
tools/qsharp(Python packageqdk); the dotnet based Q# SDK is discontinued. @LIA.solidityruns the contractMainwith Foundry (forge build main.sol, thenforge script main.sol --tc Main). solcjs stays in the image for older copies of the template, which only compile (solcjs --abi)./usr/local/bin/forgeis a start script: it links forge-std into the folder of the run (with a path outside of the project forge warns about absolute paths on every run), allows one thread (164 -> 106 MB) and passes the output through a pipe when stderr is a terminal, because forge shows a spinner there. TheFOUNDRY_*settings in theDockerfilekeep forge offline with the solc of the image.compiler/solidity.pyremoves the build steps that forge reports from the message.- All users share one
$HOME, and their files have the same names (main.nim). A tool that keeps a cache by file name there mixes up users who compile at the same moment: with Nim half of the builds failed or produced the program of somebody else. Nim now gets a cache per run (nimcachein/opt/nim/config/config.nims). Caches by content (Go, Zig, V) are safe. The testnim: users at the same moment get their own programintests/e2e.pyshows how to check a new language. - A running program's terminal answers no queries.
PYTHON_BASIC_REPLandIRBRCkeeppython3 -iandirbusable; test new REPLs withshell(...)intests/e2e.py.
Settings that reduce CPU time and memory, all in the Dockerfile unless noted. Each one was measured in the image with 512 MB and 8 CPUs; measure again before adding one, many plausible settings do nothing.
OPENBLAS_NUM_THREADS=1,OMP_NUM_THREADS=1: numpy otherwise starts one spinning BLAS thread per CPU (a matplotlib plot: 1.7 s of CPU time, now 0.3 s; the run time stays the same).ERL_AFLAGS="+sbwt none …": no busy waiting of the Erlang schedulers (Erlang, Elixir: 0.5 s -> 0.2 s of CPU time).- Start scripts in
/usr/local/binforkotlinc,scalacandjavac: serial GC and only the C1 JIT, for kotlinc also a heap of 256 MB instead of 512 MB. Only the compilers: C1 alone slows programs that compute a lot, so programs of users keep the JVM defaults.JAVA_TOOL_OPTIONSis no alternative, the JVM prints a note for it into the output. - AOT caches of JDK 25 in
/opt/aotforkotlinc,scalac,javacandclojure(-XX:AOTCache): the classes of the compiler as they are in memory after loading, written by a training run in theDockerfile.kotlincis started directly for it (java … K2JVMCompiler), because the preloader of its own script reads the whole jar into memory and loads classes in a way the cache does not cover. With flags and cache, CPU time and memory of one compile: kotlinc 4.5 -> 1.3 s and 467 -> 197 MB, scalac 3.2 -> 0.9 s and 228 -> 141 MB, javac 0.6 -> 0.2 s and 81 -> 58 MB, clojure 0.5 -> 0.2 s. The training run needs the same JVM options as the start script. A cache that does not fit a start (another class path, like Clojure with adeps.edn, another GC) is not used, and the JVM says so in the output of the program: the start scripts therefore pass-Xlog:aot=off.-XX:AOTMode=onmakes the JVM fail instead and so shows whether a cache is used. The caches take 190 MB of the image. S2c(SelectScript) with serial GC and C1: 0.9 -> 0.5 s. An AOT cache does nothing for it.OCAMLRUNPARAM=s=1M: Coq otherwise sets a minor heap of 256 MB and fills it (a small proof: 290 -> 146 MB, for 0.19 -> 0.24 s of CPU time).QSHARP_PYTHON_TELEMETRY=none: the Q# package otherwise reports to Microsoft and waits for it at the end of every run (0.83 -> 0.12 s).- A precompiled
<iostream>next to the header (iostream.gch): g++ uses it when it is the first include and the command has no-std=,-O2,-gor-pthread(0.14 -> 0.08 s). Otherwise it reads the header as before. - README:
@LIA.erlangends with-s erlang halt,-s init stoptakes a second longer (1.1 -> 0.1 s, no CPU time, but the run keeps its slot). GOCACHEin/opt, filled at build time: with the cache in$HOMEthe first build after every start of the server compiled the standard library (3.1 s and 313 MB instead of 0.1 s and 93 MB). The same for Zig (ZIG_GLOBAL_CACHE_DIR) does not pay off: a cache filled at build time is only hit in part (149 MB per build instead of 95 MB with the cache that fills itself in$HOME).- README:
@LIA.haskelllinks dynamically (ghc -dynamic: 270 -> 189 MB while compiling). - dotnet: see "Toolchains and Heroku".
- Without effect: Julia (
--startup-file=no,-O0,--gcthreads=1;--compile=minmakes a loop 300 times slower), GHC RTS options,rustc -C codegen-units=1,GOFLAGS=-p=1,NODE_OPTIONS=--max-old-space-sizefor solcjs,Rscript --vanilla, a matplotlib font cache,nim --hints:off. Nothing to gain: Mono (mcsneeds 0.07 s), Racket (#lang racketneeds 137 MB,#lang racket/base69 MB, the choice of the course).
Pushing to the heroku branch triggers .github/workflows/heroku-deploy.yaml: it builds the image (with the GitHub Actions build cache), runs tests/run.sh against it, then pushes and releases it to Heroku. Heroku's registry rejects OCI indexes and attestations, so the build uses --provenance=false --sbom=false and oci-mediatypes=false; a plain docker build && docker push fails with error from registry: unsupported. Work happens on master, which is merged into heroku to deploy. The production URL used by the template is hardcoded in the README header (window.CodeRunner.init("wss://…herokuapp.com/")).