Run and lint solutions on the site
Test and publish the site / test (push) Successful in 1m23s
Test and publish the site / publish (push) Failing after 4m22s

A new admin-only solve page, /p/<name>/solve, edits a problem's code in
C++ or Python (a dropdown switches between them), runs it on custom
input or against the saved tests with per-test verdicts (AC, WA, RE,
TLE, unchecked) and compile errors, marks lint diagnostics in the
editor, and saves the code back as a commit ("Edit <name>"). Drafts
stay in the browser per problem and language until saved. LeetCode
problems are C++ only, since their tests run through driver.h.

Code never runs in the site, which holds the Claude, Gitea and S3
secrets. A separate runner service (cmd/usacorunner, Dockerfile.runner)
does it in a container meant to have no environment, an internal-only
network, a read-only root apart from /tmp, and memory, CPU and pids
limits, with tini to reap orphans. Runs copy the CLI: the same g++
flags with -DLOCAL and the repo's headers, <io>.in on disk and on
stdin, <io>.out or stdout as the output, and usaco test's comparison.
Unlike the CLI they have CPU, memory, file and wall-clock limits.

C++ lint is g++'s warnings plus clang-tidy with a new .clang-tidy
(bugprone, performance and a few readability checks; template.cpp is
clean). Python lint is a syntax check plus ruff. template.py is the
Python starter, with a stdio() helper like template.rs's.

CI builds, smoke-tests and rolls out the runner image before the site.
The web_server stack needs a usaco-runner service before that rollout
can succeed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-20 11:24:22 +01:00
co-authored by Claude Opus 5.5
parent 107ecab9da
commit c972fa9fd9
33 changed files with 4477 additions and 23 deletions
+207
View File
@@ -0,0 +1,207 @@
package runner
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os/exec"
"regexp"
"strings"
"time"
)
// maxBody caps a request. It also bounds every expected output, which
// compareCap relies on.
const maxBody = 2 << 20
// maxTests is the most tests one run may carry.
const maxTests = 100
// server is the service behind Handler.
type server struct {
// slots holds one token per run or lint in progress, so at most
// MAX_PARALLEL compilers and programs compete for the container's CPUs
// and the timings stay meaningful.
slots chan struct{}
budget time.Duration
}
// Handler serves the runner's API:
//
// POST /run RunRequest -> RunResponse
// POST /lint LintRequest -> LintResponse
// GET /health 200 and which tools are installed
//
// A request the runner cannot take (an unknown lang, an io or file name
// that is not a bare name, over 100 tests, a time limit over 10s) is 400,
// or 413 when over 2 MB, and one that
// could not get a slot within its budget is 503, all as {"error": "..."}.
// A program that fails to compile is a 200: that is a result, not an error.
func Handler(maxParallel int) http.Handler {
return newServer(maxParallel, requestBudget).routes()
}
func newServer(maxParallel int, budget time.Duration) *server {
if maxParallel < 1 {
maxParallel = 1
}
return &server{slots: make(chan struct{}, maxParallel), budget: budget}
}
func (s *server) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /run", s.handleRun)
mux.HandleFunc("POST /lint", s.handleLint)
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "tools": Tools()})
})
return mux
}
// Tools reports which of the runner's programs are on PATH. Only g++ and
// python3 are needed to run code; the linters are optional.
func Tools() map[string]bool {
tools := map[string]bool{}
for _, bin := range []string{"g++", "python3", "clang-tidy", "ruff"} {
_, err := exec.LookPath(bin)
tools[bin] = err == nil
}
return tools
}
func (s *server) handleRun(w http.ResponseWriter, r *http.Request) {
var req RunRequest
if !decode(w, r, &req) {
return
}
if err := validate(req.Lang, req.Files); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
if req.IO != "" && !bareName.MatchString(req.IO) {
writeError(w, http.StatusBadRequest, fmt.Sprintf("io %q is not a bare file name", req.IO))
return
}
if len(req.Tests) > maxTests {
writeError(w, http.StatusBadRequest, fmt.Sprintf("%d tests: at most %d per run", len(req.Tests), maxTests))
return
}
if req.TimeLimitMs < 0 || req.TimeLimitMs > 10_000 {
writeError(w, http.StatusBadRequest, "timeLimitMs must be between 0 and 10000")
return
}
start := time.Now()
resp, err := withSlot(s, r.Context(), w, func(ctx context.Context) (RunResponse, error) { return run(ctx, req) })
if err != nil {
return
}
log.Printf("[run] %s, %d tests: %s in %dms", req.Lang, len(req.Tests), summary(resp), time.Since(start).Milliseconds())
writeJSON(w, http.StatusOK, resp)
}
func (s *server) handleLint(w http.ResponseWriter, r *http.Request) {
var req LintRequest
if !decode(w, r, &req) {
return
}
if err := validate(req.Lang, req.Files); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
resp, err := withSlot(s, r.Context(), w, func(ctx context.Context) (LintResponse, error) { return lint(ctx, req) })
if err != nil {
return
}
writeJSON(w, http.StatusOK, resp)
}
// withSlot runs f once a slot is free, under the request's budget, which
// starts on arrival so time spent queueing counts against it. On failure
// it has already answered.
func withSlot[T any](s *server, parent context.Context, w http.ResponseWriter, f func(context.Context) (T, error)) (T, error) {
var zero T
ctx, cancel := context.WithTimeout(parent, s.budget)
defer cancel()
select {
case s.slots <- struct{}{}:
case <-ctx.Done():
writeError(w, http.StatusServiceUnavailable, "the runner is busy: try again in a moment")
return zero, ctx.Err()
}
defer func() { <-s.slots }()
out, err := f(ctx)
if err != nil {
log.Printf("[runner] %v", err)
writeError(w, http.StatusInternalServerError, err.Error())
return zero, err
}
return out, nil
}
// bareName is a file name with no directory part that cannot be "." or
// "..", hidden, or an option to a tool.
var bareName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
func validate(lang string, files map[string]string) error {
if _, ok := languages[lang]; !ok {
return fmt.Errorf("unknown lang %q (want %s or %s)", lang, Cpp, Python)
}
for name := range files {
if !bareName.MatchString(name) || len(name) > 128 {
return fmt.Errorf("file %q is not a bare file name", name)
}
if reserved[name] {
return fmt.Errorf("file %q is the runner's own", name)
}
}
return nil
}
func decode(w http.ResponseWriter, r *http.Request, v any) bool {
err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBody)).Decode(v)
var tooBig *http.MaxBytesError
switch {
case errors.As(err, &tooBig):
writeError(w, http.StatusRequestEntityTooLarge, fmt.Sprintf("the request is over %d MB", maxBody>>20))
return false
case err != nil:
writeError(w, http.StatusBadRequest, "bad JSON: "+err.Error())
return false
}
return true
}
// summary is the log line's verdict count: "compile error", "3 AC, 1 WA".
func summary(resp RunResponse) string {
if !resp.Compile.OK {
return "compile error"
}
counts := map[string]int{}
for _, r := range resp.Results {
counts[r.Verdict]++
}
var parts []string
for _, v := range []string{Accepted, WrongAnswer, RuntimeError, TimeLimit, Unchecked} {
if counts[v] > 0 {
parts = append(parts, fmt.Sprintf("%d %s", counts[v], v))
}
}
if len(parts) == 0 {
return "compiled"
}
return strings.Join(parts, ", ")
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, map[string]string{"error": msg})
}