Autocomplete and evaluate solutions on the solve page
Test and publish the site / test (push) Successful in 1m25s
Test and publish the site / publish (push) Successful in 1m51s

The editor's completion popup was on but empty for C++, since
@codemirror/lang-cpp has no completion source. web/src/completions.js
adds one: keywords, the STL, every name in the file (the template's
macros show their expansion, typedefs what they alias), members after
. and ->, and snippets for the loops and lambdas typed over and over.
Python gains the contest standard library and members after ., on top
of lang-python's builtins and local names. Nothing knows types, so
members are the common ones plus those already used in the file.

Evaluate (POST/GET /problems/<name>/evaluate) has Claude judge the
editor's code as a strong competitive programmer would before
submitting. It runs the saved tests on the runner first, as Submit
does, and gives Claude the verdicts and up to three failing cases. The
reply is a verdict, correctness, complexity against the constraints,
line-anchored issues and a traced counterexample (internal/evaluate).
The page shows it in an Evaluation tab of the results panel, marks the
issues in the editor beside the lint's for as long as their lines are
unchanged, and can load the counterexample as the custom input.

It is a background job the page polls, like explanations, but it
commits nothing: the code is a draft. explain.Jobs.StartWith keeps a
finished job's answer in memory until the next one or a restart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-20 12:46:54 +01:00
co-authored by Claude Opus 5.5
parent 34552f2d81
commit d4849859df
18 changed files with 1566 additions and 36 deletions
+117
View File
@@ -0,0 +1,117 @@
package handlers
import (
"context"
"errors"
"log"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/evaluate"
"adam-french.co.uk/usaco-site/internal/runner"
)
// The saved tests run first and Claude takes a minute or two after.
const evaluateTimeout = 10 * time.Minute
// startEvaluate starts judging the editor's source and answers at once; the
// page polls evaluateStatus, whose result is the evaluation. Nothing is
// committed: the source is a draft, and the answer is about this version of
// it only.
func (s *Server) startEvaluate(ctx *gin.Context) {
if s.Claude == nil {
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "Claude is not configured on this server (CLAUDE_API_KEY)"})
return
}
body, p, l, ok := s.readCode(ctx)
if !ok {
return
}
if strings.TrimSpace(body.Source) == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the source is empty"})
return
}
if len(body.Note) > maxNote {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "the note is too long"})
return
}
if strings.TrimSpace(p.Statement) == "" && p.URL == "" {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "add the problem statement or a link to it first"})
return
}
in := evaluate.Input{
Name: p.Name, Statement: p.Statement, Examples: examples(p),
Lang: body.Lang, Source: body.Source, LeetCode: l.leetcode, Note: body.Note,
}
link := p.URL
if !s.evalJobs.StartWith(p.Name, func() (any, error) { return s.evaluate(in, link, l) }) {
ctx.JSON(http.StatusConflict, gin.H{"error": "a solution is already being evaluated"})
return
}
ctx.JSON(http.StatusAccepted, s.evalJobs.Get(p.Name))
}
func (s *Server) evaluateStatus(ctx *gin.Context) {
if p, ok := s.lookup(ctx, true); ok {
ctx.JSON(http.StatusOK, s.evalJobs.Get(p.Name))
}
}
// evaluate is one job. Its error is shown to the admin, so every path
// returns a message meant for them and logs the detail.
func (s *Server) evaluate(in evaluate.Input, link string, l *layout) (*evaluate.Evaluation, error) {
ctx, cancel := context.WithTimeout(context.Background(), evaluateTimeout)
defer cancel()
name := in.Name
// A fetched statement is not saved: that would be the only commit an
// evaluation makes. Explain or Edit details keep one.
if _, err := s.ensureStatement(ctx, "evaluate", name, &in.Statement, link); err != nil {
return nil, err
}
in.Run, in.RunNote = s.evaluationRun(ctx, name, in.Lang, in.Source, l)
ev, err := evaluate.Generate(ctx, s.Claude, in, time.Now())
if err != nil {
var f *claude.Failure
if errors.As(err, &f) {
log.Printf("[evaluate] %s: %s: %v", name, f.Msg, f.Err)
return nil, f
}
log.Printf("[evaluate] %s: %v", name, err)
return nil, errors.New("the evaluation could not be written")
}
return ev, nil
}
// evaluationRun is Submit's run, for Claude to read. A run that cannot
// happen costs the evaluation its test verdicts, not the evaluation: the
// note says why, and goes to Claude in their place.
func (s *Server) evaluationRun(ctx context.Context, name, lang, source string, l *layout) (*runner.RunResponse, string) {
if s.Runner == nil {
return nil, "The tests were not run: the code runner is not configured."
}
tests, err := readRunTests(l)
if err != nil {
log.Printf("[evaluate] %s: reading the tests: %v", name, err)
return nil, "The tests were not run: they could not be read."
}
files, err := s.headers(l, lang)
if err != nil {
log.Printf("[evaluate] %s: reading the headers: %v", name, err)
return nil, "The tests were not run: the headers could not be read."
}
c, cancel := context.WithTimeout(ctx, runTimeout)
defer cancel()
res, err := s.Runner.Run(c, runner.RunRequest{Lang: lang, Source: source, Files: files, IO: l.io, Tests: tests})
if err != nil {
log.Printf("[evaluate] %s: running the tests: %v", name, err)
return nil, "The tests were not run: the code runner failed."
}
return &res, ""
}
+146
View File
@@ -0,0 +1,146 @@
package handlers
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/claude"
"adam-french.co.uk/usaco-site/internal/evaluate"
"adam-french.co.uk/usaco-site/internal/explain"
)
// fakeEvaluator flags line 1 of whatever it is shown, or fails.
type fakeEvaluator struct {
user string
fail bool
}
func (f *fakeEvaluator) Model() string { return "fake-model" }
func (f *fakeEvaluator) JSON(_ context.Context, req claude.Request, out any) error {
f.user = req.User
if f.fail {
return &claude.Failure{Msg: "Claude declined to answer"}
}
*out.(*evaluate.Result) = evaluate.Result{
Verdict: "edge_cases", Summary: "Prints zero.",
Issues: []evaluate.Issue{{Line: 1, Severity: "error", Title: "Never reads n"}},
}
return nil
}
type evalStatus struct {
State string `json:"state"`
Error string `json:"error"`
Result *evaluate.Evaluation `json:"result"`
}
func waitEvaluate(t *testing.T, r *gin.Engine, name string) evalStatus {
t.Helper()
for range 400 {
var s evalStatus
json.Unmarshal(do(r, "GET", "/usaco/api/problems/"+name+"/evaluate", "", true).Body.Bytes(), &s)
if s.State != explain.Running {
return s
}
time.Sleep(5 * time.Millisecond)
}
t.Fatal("evaluation still running")
return evalStatus{}
}
const evalBody = `{"lang":"cpp","source":"int main() {}\n","note":"is it fast enough?"}`
func TestEvaluateRefusals(t *testing.T) {
r, repo, _ := setupRun(t)
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 503 {
t.Fatalf("no Claude = %d, want 503", rec.Code)
}
repo.srv.Claude = &fakeEvaluator{}
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, false); rec.Code != 401 {
t.Fatalf("public evaluate = %d, want 401", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 400 {
t.Fatalf("no statement or link = %d, want 400: %s", rec.Code, rec.Body)
}
withStatement(t, r)
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", `{"lang":"cpp","source":" \n"}`, true); rec.Code != 400 {
t.Fatalf("empty source = %d, want 400", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", `{"lang":"rust","source":"fn main() {}"}`, true); rec.Code != 400 {
t.Fatalf("rust = %d, want 400", rec.Code)
}
if rec := do(r, "POST", "/usaco/api/problems/two-sum/evaluate", `{"lang":"python","source":"x"}`, true); rec.Code != 400 {
t.Fatalf("python on LeetCode = %d, want 400", rec.Code)
}
}
func TestEvaluateRunsTheTestsAndCommitsNothing(t *testing.T) {
r, repo, fr := setupRun(t)
fc := &fakeEvaluator{}
repo.srv.Claude = fc
withStatement(t, r)
commits := len(repo.msg)
if rec := do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true); rec.Code != 202 {
t.Fatalf("evaluate = %d %s", rec.Code, rec.Body)
}
s := waitEvaluate(t, r, "moocast")
if s.State != explain.Done || s.Result == nil {
t.Fatalf("job = %+v", s)
}
ev := s.Result
if ev.Verdict != "edge_cases" || ev.Lang != "cpp" || ev.Source != "int main() {}\n" || ev.Model != "fake-model" || ev.Tests != "1/1 passed" {
t.Errorf("evaluation = %+v", ev)
}
if len(ev.Issues) != 1 || ev.Issues[0].Line != 1 {
t.Errorf("issues = %+v", ev.Issues)
}
// Submit's run: the saved tests, with the headers.
if fr.run == nil || len(fr.run.Tests) != 3 || fr.run.IO != "moocast" || fr.run.Files["debugging.h"] == "" {
t.Errorf("run = %+v", fr.run)
}
for _, want := range []string{"walkie-talkies", "<code lang=\"cpp\">\n1| int main() {}\n</code>", "1/1 passed on the saved tests", "is it fast enough?"} {
if !strings.Contains(fc.user, want) {
t.Errorf("prompt is missing %q:\n%s", want, fc.user)
}
}
if len(repo.msg) != commits {
t.Errorf("an evaluation committed: %v", repo.msg[commits:])
}
}
func TestEvaluateWithoutARunner(t *testing.T) {
r, repo, fr := setupRun(t)
fc := &fakeEvaluator{}
repo.srv.Claude = fc
withStatement(t, r)
// A runner that fails costs the verdicts, not the evaluation.
fr.err = errors.New("runner down")
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
if s := waitEvaluate(t, r, "moocast"); s.State != explain.Done || s.Result.Tests != "The tests were not run: the code runner failed." {
t.Fatalf("with a failing runner = %+v", s)
}
repo.srv.Runner = nil
if c := getCodeReply(t, r, "moocast"); c.Runner {
t.Fatal("runner still reported")
}
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
s := waitEvaluate(t, r, "moocast")
if s.State != explain.Done || !strings.Contains(fc.user, "the code runner is not configured") {
t.Fatalf("with no runner = %+v\n%s", s, fc.user)
}
fc.fail = true
do(r, "POST", "/usaco/api/problems/moocast/evaluate", evalBody, true)
if s := waitEvaluate(t, r, "moocast"); s.State != explain.Failed || s.Error != "Claude declined to answer" || s.Result != nil {
t.Fatalf("a failed evaluation = %+v", s)
}
}
+7 -5
View File
@@ -1,8 +1,8 @@
// Package handlers is the site's REST API: the problem list and pages (public
// for solved problems, everything for the admin), the admin's edits, the
// Claude explanations (explain.go) and recording reviews (review.go), the
// solve page's code editing and runs (run.go), and the Gitea webhook that
// tells the server to pull.
// solve page's code editing and runs (run.go) and evaluations
// (evaluate.go), and the Gitea webhook that tells the server to pull.
package handlers
import (
@@ -67,9 +67,9 @@ type Server struct {
Runner Runner
idx atomic.Pointer[index.Index]
// Separate, so a review and an explanation of one problem can run at
// the same time.
jobs, reviewJobs explain.Jobs
// Separate, so a review, an explanation and an evaluation of one
// problem can run at the same time.
jobs, reviewJobs, evalJobs explain.Jobs
}
// SetIndex swaps in a freshly built index. repo.Repo calls it (through
@@ -111,6 +111,8 @@ func (s *Server) Routes(api *gin.RouterGroup) {
admin.PUT("/problems/:name/code", s.saveCode)
admin.POST("/problems/:name/run", s.run)
admin.POST("/problems/:name/lint", s.lint)
admin.POST("/problems/:name/evaluate", s.startEvaluate)
admin.GET("/problems/:name/evaluate", s.evaluateStatus)
admin.POST("/leetcode/daily", s.startDaily)
api.POST("/hooks/gitea", s.webhook)
}
+17 -13
View File
@@ -16,6 +16,7 @@ import (
"github.com/gin-gonic/gin"
"adam-french.co.uk/usaco-site/internal/index"
"adam-french.co.uk/usaco-site/internal/runner"
)
@@ -159,6 +160,7 @@ func (s *Server) getCode(ctx *gin.Context) {
"languages": l.languages(),
"default": def,
"runner": s.Runner != nil,
"claude": s.Claude != nil,
"code": code,
})
}
@@ -248,44 +250,46 @@ type codeBody struct {
// Mode and Input are for runs only.
Mode string `json:"mode"`
Input string `json:"input"`
// Note is for evaluations only.
Note string `json:"note"`
}
// readCode reads and checks a solve page request against the problem's
// layout. It has answered when ok is false.
func (s *Server) readCode(ctx *gin.Context) (body codeBody, l *layout, ok bool) {
p, ok := s.lookup(ctx, true)
func (s *Server) readCode(ctx *gin.Context) (body codeBody, p *index.Problem, l *layout, ok bool) {
p, ok = s.lookup(ctx, true)
if !ok {
return body, nil, false
return body, nil, nil, false
}
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxRunBody)
if err := ctx.ShouldBindJSON(&body); err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the request is over 512 KB"})
return body, nil, false
return body, nil, nil, false
}
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return body, nil, false
return body, nil, nil, false
}
if len(body.Source) > maxSource {
ctx.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "the source is over 256 KB"})
return body, nil, false
return body, nil, nil, false
}
if body.Lang != runner.Cpp && body.Lang != runner.Python {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "lang must be cpp or python"})
return body, nil, false
return body, nil, nil, false
}
l, err := s.readLayout(p.Status, p.Name)
if err != nil {
log.Printf("[code] %s: %v", p.Name, err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "the problem's files could not be read"})
return body, nil, false
return body, nil, nil, false
}
if !l.allows(body.Lang) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "a LeetCode problem runs through its C++ driver only"})
return body, nil, false
return body, nil, nil, false
}
return body, l, true
return body, p, l, true
}
// headers are the files written next to a C++ source; Python needs none.
@@ -333,7 +337,7 @@ func (s *Server) run(ctx *gin.Context) {
if !s.runnerConfigured(ctx) {
return
}
body, l, ok := s.readCode(ctx)
body, _, l, ok := s.readCode(ctx)
if !ok {
return
}
@@ -472,7 +476,7 @@ func (s *Server) lint(ctx *gin.Context) {
if !s.runnerConfigured(ctx) {
return
}
body, l, ok := s.readCode(ctx)
body, _, l, ok := s.readCode(ctx)
if !ok {
return
}
@@ -496,7 +500,7 @@ func (s *Server) lint(ctx *gin.Context) {
// saveCode commits the editor's source as the problem's solution. An
// unchanged source makes no commit: Mutate skips an empty diff.
func (s *Server) saveCode(ctx *gin.Context) {
body, _, ok := s.readCode(ctx)
body, _, _, ok := s.readCode(ctx)
if !ok {
return
}