Skip to content

Latest commit

 

History

History
134 lines (93 loc) · 18.5 KB

CLAUDE.md

File metadata and controls

134 lines (93 loc) · 18.5 KB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

What this is

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 defines window.CodeRunner (the WebSocket client, including the hardcoded server URL) and the @LIA.eval / @LIA.<language> macros that courses import:. 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.py fails when they differ).

Running

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 needed

The 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.

WebSocket protocol (server.py: message_received)

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 to compiler.run. Reply: service: "compile" with ok, message and problems.
  • run: a blocking subprocess.run. Reply: service: "run".
  • exec (+ filter, a glob or null): starts a pexpect process in a thread and streams service: "stdout" chunks. When the process ends it sends service: "stop", which carries the base64 images, videos and filter-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 and MAX_TOTAL_SIZE (25 MB) per run, because they are held in memory as base64. Larger files are skipped and named in the error of the stop message. The dyno has 512 MB of RAM.
  • File names in data must stay inside the project dir (no absolute paths, no ../).
  • A run is stopped after MAX_OUTPUT_SIZE (2 MB) of output. A message larger than MAX_MESSAGE_SIZE (4 MB) closes the connection; the limit sits in NewWebSocketHandler.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 with setsid or nohup.
  • safe_message_received wraps the handler: an exception does not end the connection, it is answered as service: "stop" with ok: false and error, which the client shows and which ends the run.
  • Process.read_line waits up to 50 ms for output. Do not set that timeout to 0: the loop in spawn() 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, run and exec and keeps it until remove_project. A compile command none needs none, the slot is then taken for exec. At most MAX_RUNS_PER_CLIENT (2) runs per connection hold a slot, at most MAX_RUNS on the server (two per CPU, CODERUNNER_MAX_RUNS). A connection may have MAX_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 ./program counts as NATIVE, an unknown program as DEFAULT) and changes with the phase: the compiler, then the program. After SETTLE seconds measure_memory replaces 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.
  • WEIGHTS in weights.py is measured: tools/measure_weights.py runs every example of README.md in 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.py fails 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 a stdout message 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_LIMIT seconds (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 in compile or run is busy and never evicted.
  • The run time limit itself is the timeout -k 5 300 of the sandbox prefix (60 s for dotnet run); when it fires, the run ends and frees its slot.
  • tests/run.sh starts 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.py skips 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 dispatch (compiler/)

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.

The lock of a run (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 /tmp can stay open to all: the JVM (jansi of kotlinc, JNA, hsperfdata) and Roslyn write there whatever TMPDIR says. With the folders in /tmp the lock closes /tmp, and Kotlin and SelectScript fail. TMPDIR is .tmp in the folder of the run, for the tools that follow it.
  • server.py sets HOME to a folder of its own in /tmp, which all runs share. On Heroku HOME is 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=false in server.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. Calling csc directly 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 /opt with chmod a+rwX.
  • A run cannot read /proc/<pid>/cmdline of other processes, only their names. Tests that watch the server from inside a run go by the name (NAMED in tests/e2e.py).
  • Tests: tests/test_jail.py tries every version of Landlock the kernel offers. In tests/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.

Adding or fixing a language

This usually touches three places:

  1. Dockerfile: install the toolchain (apt list, or a dedicated RUN block for tools not packaged on Ubuntu 26.04).
  2. README.md header: 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.
  3. Optionally compiler/<lang>.py + a dispatch branch for error parsing.

Toolchains and Heroku

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/older pins 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_PACKAGES and PIP_IGNORE_INSTALLED, because apt owns the system Python packages.
  • Courses with an older copy of the template still send net8.0 projects. The warm-up restores that targeting pack too, and DOTNET_ROLL_FORWARD=LatestMajor runs them on .NET 10.
  • The dotnet templates start the built program (dotnet bin/Debug/net10.0/project.dll), not dotnet 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.py therefore 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 package qdk); the dotnet based Q# SDK is discontinued.
  • @LIA.solidity runs the contract Main with Foundry (forge build main.sol, then forge script main.sol --tc Main). solcjs stays in the image for older copies of the template, which only compile (solcjs --abi). /usr/local/bin/forge is 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. The FOUNDRY_* settings in the Dockerfile keep forge offline with the solc of the image. compiler/solidity.py removes 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 (nimcache in /opt/nim/config/config.nims). Caches by content (Go, Zig, V) are safe. The test nim: users at the same moment get their own program in tests/e2e.py shows how to check a new language.
  • A running program's terminal answers no queries. PYTHON_BASIC_REPL and IRBRC keep python3 -i and irb usable; test new REPLs with shell(...) in tests/e2e.py.

Tuning

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/bin for kotlinc, scalac and javac: 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_OPTIONS is no alternative, the JVM prints a note for it into the output.
  • AOT caches of JDK 25 in /opt/aot for kotlinc, scalac, javac and clojure (-XX:AOTCache): the classes of the compiler as they are in memory after loading, written by a training run in the Dockerfile. kotlinc is 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 a deps.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=on makes 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, -g or -pthread (0.14 -> 0.08 s). Otherwise it reads the header as before.
  • README: @LIA.erlang ends with -s erlang halt, -s init stop takes a second longer (1.1 -> 0.1 s, no CPU time, but the run keeps its slot).
  • GOCACHE in /opt, filled at build time: with the cache in $HOME the 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.haskell links dynamically (ghc -dynamic: 270 -> 189 MB while compiling).
  • dotnet: see "Toolchains and Heroku".
  • Without effect: Julia (--startup-file=no, -O0, --gcthreads=1; --compile=min makes a loop 300 times slower), GHC RTS options, rustc -C codegen-units=1, GOFLAGS=-p=1, NODE_OPTIONS=--max-old-space-size for solcjs, Rscript --vanilla, a matplotlib font cache, nim --hints:off. Nothing to gain: Mono (mcs needs 0.07 s), Racket (#lang racket needs 137 MB, #lang racket/base 69 MB, the choice of the course).

Deployment

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/")).