Files
adamfandClaude Opus 5.5 c6b82588b1
Test and publish the site / test (push) Successful in 1m25s
Test and publish the site / publish (push) Successful in 5m18s
Precompile bits/stdc++.h in the runner, and move it to clang-tidy 22
The first publish failed its smoke test: on the production host
(2 slow cores) clang-tidy took over 30s on a two-line file and hit the
runner's 20s lint limit, and even a trivial build took 4s, nearly all
of it parsing <bits/stdc++.h>.

The runner image now precompiles that header for g++ (.gch) and clang
(.pch) with the flags the runner passes, and the runner uses them when
they are there. g++ lint gains -O2 so the build's header matches it.
Alpine 3.24's clang-tidy 22 walks far less of the system headers than
3.22's clang-tidy 20. Measured on the host: a build 3.9s to 0.6s, and
clang-tidy 32.5s to 4.3s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 11:43:04 +01:00

260 lines
8.3 KiB
Go

package runner
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
"time"
)
// language is how one Lang is built and run, in the work directory.
type language struct {
source string
// compile builds the program. For python it is only a syntax check, so
// a SyntaxError is a failed build as it would be in C++, not a crash on
// every test.
compile []string
run []string
}
var languages = map[string]language{
// The CLI's CXXFLAGS (lib/common.sh), with -I. for the repo root: the
// request's Files hold debugging.h and leetcode.h.
Cpp: {
source: "main.cpp",
compile: []string{"g++", "-O2", "-std=c++17", "-Wall", "-Wextra", "-DLOCAL", "-I.", "-o", "main", "main.cpp"},
run: []string{"./main"},
},
// -I keeps a submitted py_compile.py from standing in for the real one.
Python: {
source: "main.py",
compile: []string{"python3", "-I", "-m", "py_compile", "main.py"},
run: []string{"python3", "main.py"},
},
}
// reserved are names the runner itself writes, so Files may not use them.
var reserved = map[string]bool{"main.cpp": true, "main.py": true, "main": true}
// workspace is one request's temporary directory. The program runs in
// work/; what the runner captures lives beside it, out of the program's way.
type workspace struct {
root, work string
}
func newWorkspace(src, source string, files map[string]string) (*workspace, error) {
// os.MkdirTemp honours TMPDIR, /tmp by default: in the container that
// is the one writable (tmpfs) mount, and it must allow exec, since the
// compiled program runs from it.
root, err := os.MkdirTemp("", "usacorun-")
if err != nil {
return nil, err
}
ws := &workspace{root: root, work: filepath.Join(root, "work")}
if err := os.Mkdir(ws.work, 0o755); err != nil {
ws.remove()
return nil, err
}
for name, body := range files {
if err := os.WriteFile(filepath.Join(ws.work, name), []byte(body), 0o644); err != nil {
ws.remove()
return nil, err
}
}
if err := os.WriteFile(filepath.Join(ws.work, src), []byte(source), 0o644); err != nil {
ws.remove()
return nil, err
}
return ws, nil
}
func (ws *workspace) remove() { os.RemoveAll(ws.root) }
func (ws *workspace) capture(n string) string { return filepath.Join(ws.root, n) }
// run builds req.Source once and runs it on each test in order, in the
// same directory, as `usaco test` does. The error is only for the runner
// failing (no temp directory); anything wrong with the program is in the
// response.
func run(ctx context.Context, req RunRequest) (RunResponse, error) {
lang := languages[req.Lang]
ws, err := newWorkspace(lang.source, req.Source, req.Files)
if err != nil {
return RunResponse{}, err
}
defer ws.remove()
resp := RunResponse{Results: []Result{}}
resp.Compile = compile(ctx, ws, lang)
if !resp.Compile.OK {
return resp, nil
}
limit := time.Duration(req.TimeLimitMs) * time.Millisecond
if limit <= 0 {
limit = DefaultTimeLimitMs * time.Millisecond
}
for _, t := range req.Tests {
resp.Results = append(resp.Results, runTest(ctx, ws, lang, ioName(req.IO), limit, t))
}
return resp, nil
}
// ioName is the file-IO name a request means. A problem with no io name
// is a stdin/stdout one, which never opens the file, so any fixed name
// does; "input" reads sensibly in a program's error messages.
func ioName(io string) string {
if io == "" {
return "input"
}
return io
}
func compile(ctx context.Context, ws *workspace, lang language) Compile {
out := ws.capture("compile.txt")
args := lang.compile
if args[0] == "g++" {
args = withGCCPCH(args)
}
o := proc{
dir: ws.work,
args: args,
stdout: out,
stderr: out,
limits: limits{cpuSec: int(compileTimeout / time.Second), memoryKB: compileMemoryKB, fileBlocks: fileBlocks},
wall: compileTimeout,
}.run(ctx)
text, cut := readCapped(out, MaxOutput)
text, _ = capText(text, MaxOutput)
if cut {
text += "\n[output cut]"
}
c := Compile{Output: text, TimeMs: o.wall.Milliseconds()}
switch {
case o.err != nil:
c.Output = fmt.Sprintf("%s could not start on the runner: %v", lang.compile[0], o.err)
case o.stopped:
c.Output = strings.TrimSpace(text + "\n" + budgetMessage)
case o.timedOut:
c.Output = strings.TrimSpace(fmt.Sprintf("%s\ncompilation took longer than %s", text, compileTimeout))
default:
c.OK = o.state.Success()
}
return c
}
const budgetMessage = "stopped: the request's 60s budget ran out"
// runTest runs one test the way lib/common.sh's run_solution does: in the
// work directory with <io>.in on stdin, its output being <io>.out if it
// wrote one and stdout otherwise.
func runTest(ctx context.Context, ws *workspace, lang language, io string, limit time.Duration, t Test) Result {
res := Result{Name: t.Name, Expected: t.Output}
res.Input, res.Truncated = capText(t.Input, MaxOutput)
if ctx.Err() != nil {
res.Verdict, res.Message = TimeLimit, "not run: the request's 60s budget ran out"
return res
}
in := filepath.Join(ws.work, io+".in")
outFile := filepath.Join(ws.work, io+".out")
if err := os.WriteFile(in, []byte(t.Input), 0o644); err != nil {
res.Verdict, res.Message = RuntimeError, "could not write "+io+".in: "+err.Error()
return res
}
os.Remove(outFile)
stdout, stderr := ws.capture("stdout"), ws.capture("stderr")
o := proc{
dir: ws.work,
args: lang.run,
stdin: in,
stdout: stdout,
stderr: stderr,
limits: testLimits(limit),
wall: wallLimit(limit),
}.run(ctx)
res.TimeMs = o.wall.Milliseconds()
res.ExitCode = o.exitCode()
var cut bool
res.Stderr, cut = readCapped(stderr, MaxStderr)
res.Stderr, _ = capText(res.Stderr, MaxStderr)
res.Truncated = res.Truncated || cut
// Only a regular file counts as the program's <io>.out; anything else
// it left there (a directory, a symlink out of the sandbox) is ignored.
from := stdout
if fi, err := os.Lstat(outFile); err == nil && fi.Mode().IsRegular() {
from = outFile
}
output, tooLong := readCapped(from, compareCap)
res.Output, cut = capText(output, MaxOutput)
res.Truncated = res.Truncated || cut
sig, signaled := o.signal()
switch {
case o.err != nil:
res.Verdict, res.Message = RuntimeError, "could not start: "+o.err.Error()
case o.stopped:
res.Verdict, res.Message = TimeLimit, budgetMessage
case o.timedOut:
res.Verdict = TimeLimit
res.Message = fmt.Sprintf("ran past the %s wall-clock limit (%s of CPU time)", seconds(wallLimit(limit)), seconds(o.cpu))
// The rlimit is only a backstop a second above the limit: the verdict
// is the measured CPU time against the exact one, as a judge's is.
case signaled && sig == syscall.SIGXCPU, o.cpu > limit:
res.Verdict = TimeLimit
res.Message = fmt.Sprintf("used %s of CPU time; the limit is %s", seconds(o.cpu), seconds(limit))
case signaled:
res.Verdict = RuntimeError
res.Message = fmt.Sprintf("killed by signal %d (%s)", int(sig), sig) + memoryHint(res.Stderr)
case !o.state.Success():
res.Verdict = RuntimeError
res.Message = fmt.Sprintf("exit status %d", o.state.ExitCode()) + memoryHint(res.Stderr)
case t.Output == nil:
res.Verdict = Unchecked
case tooLong:
res.Verdict = WrongAnswer
res.Message = fmt.Sprintf("the output is over %d MB", compareCap>>20)
case normalize(output) == normalize(*t.Output):
res.Verdict = Accepted
default:
res.Verdict = WrongAnswer
}
return res
}
// memoryHint names the likely cause when the program ran out of address
// space: C++ aborts with bad_alloc, python raises MemoryError, and neither
// says there was a limit.
func memoryHint(stderr string) string {
if strings.Contains(stderr, "bad_alloc") || strings.Contains(stderr, "MemoryError") {
return fmt.Sprintf("; out of memory? The limit is %d MB", memoryKB>>10)
}
return ""
}
// normalize is test.sh's norm(): trailing whitespace off every line, then
// trailing blank lines dropped, so a missing final newline or a stray
// space never fails a test.
func normalize(s string) string {
lines := strings.Split(s, "\n")
for i, l := range lines {
lines[i] = strings.TrimRight(l, " \t\r\v\f")
}
for len(lines) > 0 && lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
return strings.Join(lines, "\n")
}
// seconds formats a duration the way the messages quote limits: "2s",
// "1.5s", "0.23s".
func seconds(d time.Duration) string {
s := fmt.Sprintf("%.2f", d.Seconds())
s = strings.TrimRight(strings.TrimRight(s, "0"), ".")
return s + "s"
}