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]>
323 lines
14 KiB
Go
323 lines
14 KiB
Go
// Package evaluate has Claude judge the code in the solve page's editor, as
|
|
// a strong competitive programmer would before submitting it: is it right,
|
|
// is it fast enough for the constraints, which lines are wrong, and is
|
|
// there a small input that breaks it.
|
|
//
|
|
// The code is a draft, so unlike an explanation or a review nothing is
|
|
// committed. The answer is kept in memory with the source it judged
|
|
// (explain.Jobs.StartWith), and the page anchors each issue to its line in
|
|
// the editor.
|
|
//
|
|
// Claude is given the saved tests' verdicts from the runner along with the
|
|
// code, because a test that fails is a fact it should not have to work out,
|
|
// and one that passes is evidence it can weigh.
|
|
package evaluate
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"adam-french.co.uk/usaco-site/internal/claude"
|
|
"adam-french.co.uk/usaco-site/internal/explain"
|
|
"adam-french.co.uk/usaco-site/internal/runner"
|
|
)
|
|
|
|
// Input is what Claude is told.
|
|
type Input struct {
|
|
Name string
|
|
Statement string
|
|
Examples []explain.Example
|
|
Lang string // runner.Cpp or runner.Python
|
|
Source string
|
|
LeetCode bool // the source is a class Solution run through driver.h
|
|
Note string // what the admin wants checked: "worried about overflow"
|
|
// Run is the saved tests' outcome, nil when they were not run; RunNote
|
|
// says why not.
|
|
Run *runner.RunResponse
|
|
RunNote string
|
|
}
|
|
|
|
// Issue is one problem in the code, anchored to a line of it.
|
|
type Issue struct {
|
|
Line int `json:"line"`
|
|
Severity string `json:"severity"`
|
|
Title string `json:"title"`
|
|
Detail string `json:"detail"`
|
|
}
|
|
|
|
// Counterexample is an input the code gets wrong; all blank when Claude has
|
|
// none it is sure of.
|
|
type Counterexample struct {
|
|
Input string `json:"input"`
|
|
Expected string `json:"expected"`
|
|
Why string `json:"why"`
|
|
}
|
|
|
|
// Result is the reply's shape; Schema is the same thing for the API.
|
|
type Result struct {
|
|
Verdict string `json:"verdict"`
|
|
Summary string `json:"summary"`
|
|
Correctness string `json:"correctness"`
|
|
Complexity string `json:"complexity"`
|
|
Issues []Issue `json:"issues"`
|
|
Counterexample Counterexample `json:"counterexample"`
|
|
Style string `json:"style"`
|
|
}
|
|
|
|
// Evaluation is what the job keeps and the page shows: the reply, and the
|
|
// source it is about, so the page can tell when the editor has moved on.
|
|
type Evaluation struct {
|
|
Result
|
|
Lang string `json:"lang"`
|
|
Source string `json:"source"`
|
|
Model string `json:"model"`
|
|
At time.Time `json:"at"`
|
|
// Tests is the run's one-line outcome ("3/4 passed"), or why there was
|
|
// none.
|
|
Tests string `json:"tests"`
|
|
}
|
|
|
|
// Verdicts, and how they read on the page.
|
|
var Verdicts = map[string]string{
|
|
"correct": "Looks correct",
|
|
"edge_cases": "Misses edge cases",
|
|
"wrong": "Wrong",
|
|
"too_slow": "Too slow",
|
|
"incomplete": "Unfinished",
|
|
}
|
|
|
|
func str(desc string) map[string]any { return map[string]any{"type": "string", "description": desc} }
|
|
|
|
// Schema constrains the reply to Result. Structured outputs need every
|
|
// object closed and every property required.
|
|
var Schema = map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"verdict": map[string]any{
|
|
"type": "string",
|
|
"enum": []string{"correct", "edge_cases", "wrong", "too_slow", "incomplete"},
|
|
"description": "correct: you expect it to be accepted. edge_cases: the idea is right but some inputs break it (overflow, empty input, an off-by-one at a boundary). " +
|
|
"wrong: the approach itself gives wrong answers. too_slow: right answers, but over the time or memory limit at the largest inputs. " +
|
|
"incomplete: it does not compile, or is not a full attempt yet. When several apply, pick the first of wrong, too_slow, edge_cases.",
|
|
},
|
|
"summary": str("Markdown, one or two sentences: what the code does, as an algorithm, so they can check it was read right."),
|
|
"correctness": str("Markdown. Why it is or is not correct. Account for every failing test. If it is wrong, say where the reasoning breaks; if it is right, give the argument briefly, especially for a greedy choice."),
|
|
"complexity": str("Markdown. Time and memory as written, against what the constraints allow, with a rough operation count at the largest input."),
|
|
"issues": map[string]any{
|
|
"type": "array",
|
|
"description": "Specific problems, most serious first: bugs, edge cases, overflow, undefined behaviour, needless slowness. Empty if there are none. Not style nitpicks.",
|
|
"items": map[string]any{
|
|
"type": "object",
|
|
"properties": map[string]any{
|
|
"line": map[string]any{"type": "integer", "description": "The source line it is on, as numbered in <code>. 0 if it is about the program as a whole."},
|
|
"severity": map[string]any{"type": "string", "enum": []string{"error", "warning", "info"}, "description": "error: gives a wrong answer, crashes or times out on some valid input. warning: risky or fragile, but may be fine on this problem's tests. info: worth knowing, harmless here."},
|
|
"title": str("Plain text, under ten words: shown inline in the editor."),
|
|
"detail": str("Markdown. What goes wrong and on what input, and how to fix it. A corrected line or two is fine; never a whole solution."),
|
|
},
|
|
"required": []string{"line", "severity", "title", "detail"},
|
|
"additionalProperties": false,
|
|
},
|
|
},
|
|
"counterexample": map[string]any{
|
|
"type": "object",
|
|
"description": "A small input this code gets wrong, in exactly the problem's input format. All three blank unless you have traced the code on it and are sure.",
|
|
"properties": map[string]any{
|
|
"input": str("The input, exactly as the program would read it. Blank for none."),
|
|
"expected": str("The correct output for that input, worked out carefully. Blank for none."),
|
|
"why": str("Markdown, one or two sentences: what this code outputs instead, and why. Blank for none."),
|
|
},
|
|
"required": []string{"input", "expected", "why"},
|
|
"additionalProperties": false,
|
|
},
|
|
"style": str("Markdown, two to four sentences: readability and contest habits worth changing, if any. Blank if there is nothing worth saying."),
|
|
},
|
|
"required": []string{"verdict", "summary", "correctness", "complexity", "issues", "counterexample", "style"},
|
|
"additionalProperties": false,
|
|
}
|
|
|
|
// The reply is short; the rest is room for adaptive thinking, which is
|
|
// where the tracing happens.
|
|
const maxTokens = 24000
|
|
|
|
// System is the same on every call, so it is cached.
|
|
const System = `You are a strong competitive programmer reviewing someone's solution before they submit it. You get the problem, their code, and usually the verdicts from running it on their saved tests. Tell them whether it will be accepted and, if not, exactly why.
|
|
|
|
How to judge:
|
|
- Decide correctness yourself. Trace the code on the examples and on small cases you construct, especially the boundaries: minimum sizes, all-equal values, the largest values, an empty answer.
|
|
- The test verdicts are facts. A failing test proves a bug; explain every one. Passing tests are evidence, not proof: samples are small and weak.
|
|
- Check the complexity against the constraints in the statement. Assume about 10^8 simple operations per second in C++ and 10^7 in CPython.
|
|
- Look hard for what usually breaks accepted-looking code: int overflow where long long is needed, off-by-ones, state not reset between test cases, uninitialised values, out-of-bounds access, wrong output format, recursion depth (in Python especially), comparing floating point exactly, and slow I/O on big input.
|
|
- Read the code as written, not as intended. Code that is unfinished or does not compile is incomplete.
|
|
|
|
Their setup:
|
|
- C++ is built with g++ -std=c++17 -O2 -DLOCAL. LOCAL is defined only on their machine, never on the judge, so the DBG and print macros are no-ops there. Their template defines macros and typedefs such as ll, vi, pii, F(i, L, R) for (int i = L; i < R; i++), FE (<=), FD and FDE (counting down), ALL(c), SZ(c), pb, fi and se, REMAX and REMIN, takeI(n) (declares int n and reads it), takeL, takeV(v, n), whileZ (reads T and loops T times), YESNO(b), and STDIO(name), which reads name.in and writes name.out when run locally or on USACO. Treat these as ordinary code.
|
|
- A LeetCode problem's code is the class Solution only; a driver reads the tests and calls it, so judge the method, not I/O.
|
|
- Python reads with a tokens() helper over sys.stdin.buffer, and a stdio(name) helper redirects to name.in and name.out when that file exists.
|
|
|
|
How to answer:
|
|
- The code is shown with line numbers. Every issue names the line it is on, as numbered there, so it can be marked in their editor.
|
|
- Point at fixes; do not write their solution. A corrected line or two is fine.
|
|
- Give a counterexample only if you have traced the code on it and are sure it fails, and you have worked out the right answer. Keep it small, and in exactly the input format. Otherwise leave it blank.
|
|
- Be direct. If the code is right, say so plainly and keep the rest short; do not invent problems.
|
|
- Write in plain prose, using markdown for emphasis, lists and inline code, and LaTeX between $...$ for math such as complexities ($O(n \log n)$); the page typesets it with KaTeX.`
|
|
|
|
// Prompt is the user message.
|
|
func Prompt(in Input) string {
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "<problem name=%q>\n%s\n</problem>\n", in.Name, strings.TrimSpace(in.Statement))
|
|
for i, ex := range in.Examples {
|
|
fmt.Fprintf(&b, "\n<example n=\"%d\">\n<input>\n%s\n</input>\n", i+1, strings.TrimRight(ex.In, "\n"))
|
|
if ex.Out != "" {
|
|
fmt.Fprintf(&b, "<output>\n%s\n</output>\n", strings.TrimRight(ex.Out, "\n"))
|
|
}
|
|
b.WriteString("</example>\n")
|
|
}
|
|
kind := ""
|
|
if in.LeetCode {
|
|
kind = " leetcode=\"true\""
|
|
}
|
|
fmt.Fprintf(&b, "\n<code lang=%q%s>\n%s</code>\n", in.Lang, kind, numbered(in.Source))
|
|
b.WriteString("\n<test_run>\n" + runText(in.Run, in.RunNote) + "</test_run>\n")
|
|
if note := strings.TrimSpace(in.Note); note != "" {
|
|
fmt.Fprintf(&b, "\n<context>\n%s\n</context>\n", note)
|
|
}
|
|
b.WriteString("\nEvaluate my solution.")
|
|
return b.String()
|
|
}
|
|
|
|
// numbered prefixes each line with its number, right-aligned, as an editor
|
|
// gutter would show it.
|
|
func numbered(src string) string {
|
|
lines := strings.Split(strings.TrimRight(src, "\n"), "\n")
|
|
w := len(fmt.Sprint(len(lines)))
|
|
var b strings.Builder
|
|
for i, line := range lines {
|
|
fmt.Fprintf(&b, "%*d| %s\n", w, i+1, line)
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
// Caps on what a run puts in the prompt. A failing test bigger than
|
|
// maxCase is a stress test: its verdict is worth stating, its text is not.
|
|
const (
|
|
maxCase = 2 << 10
|
|
maxShown = 3
|
|
maxCompiler = 4 << 10
|
|
)
|
|
|
|
func runText(r *runner.RunResponse, note string) string {
|
|
if r == nil {
|
|
return note + "\n"
|
|
}
|
|
var b strings.Builder
|
|
if !r.Compile.OK {
|
|
b.WriteString("It did not compile:\n" + capped(r.Compile.Output, maxCompiler) + "\n")
|
|
return b.String()
|
|
}
|
|
if len(r.Results) == 0 {
|
|
return "It compiled. There are no saved tests to run.\n"
|
|
}
|
|
fmt.Fprintf(&b, "%s on the saved tests:\n", Outcome(r))
|
|
for _, t := range r.Results {
|
|
fmt.Fprintf(&b, "- test %s: %s in %d ms", t.Name, t.Verdict, t.TimeMs)
|
|
if t.Message != "" {
|
|
b.WriteString(" (" + t.Message + ")")
|
|
}
|
|
b.WriteString("\n")
|
|
}
|
|
shown := 0
|
|
for _, t := range r.Results {
|
|
if shown == maxShown {
|
|
break
|
|
}
|
|
if t.Verdict == runner.Accepted || t.Verdict == runner.Unchecked {
|
|
continue
|
|
}
|
|
shown++
|
|
fmt.Fprintf(&b, "\n<failed_test name=%q verdict=%q>\n", t.Name, t.Verdict)
|
|
if len(t.Input) > maxCase || (t.Expected != nil && len(*t.Expected) > maxCase) {
|
|
b.WriteString("(too big to show)\n</failed_test>\n")
|
|
continue
|
|
}
|
|
fmt.Fprintf(&b, "<input>\n%s\n</input>\n", strings.TrimRight(t.Input, "\n"))
|
|
if t.Expected != nil {
|
|
fmt.Fprintf(&b, "<expected>\n%s\n</expected>\n", strings.TrimRight(*t.Expected, "\n"))
|
|
}
|
|
fmt.Fprintf(&b, "<got>\n%s\n</got>\n", capped(strings.TrimRight(t.Output, "\n"), maxCase))
|
|
if t.Stderr != "" {
|
|
fmt.Fprintf(&b, "<stderr>\n%s\n</stderr>\n", capped(strings.TrimRight(t.Stderr, "\n"), maxCase))
|
|
}
|
|
b.WriteString("</failed_test>\n")
|
|
}
|
|
return b.String()
|
|
}
|
|
|
|
// Outcome is a run's one-line result: "3/4 passed", or "2 ran" when no
|
|
// test had an expected output.
|
|
func Outcome(r *runner.RunResponse) string {
|
|
if !r.Compile.OK {
|
|
return "did not compile"
|
|
}
|
|
passed, checked := 0, 0
|
|
for _, t := range r.Results {
|
|
if t.Verdict != runner.Unchecked {
|
|
checked++
|
|
}
|
|
if t.Verdict == runner.Accepted {
|
|
passed++
|
|
}
|
|
}
|
|
if checked == 0 {
|
|
return fmt.Sprintf("%d ran, unchecked", len(r.Results))
|
|
}
|
|
return fmt.Sprintf("%d/%d passed", passed, checked)
|
|
}
|
|
|
|
func capped(s string, n int) string {
|
|
if len(s) <= n {
|
|
return s
|
|
}
|
|
return s[:n] + "\n(cut)"
|
|
}
|
|
|
|
// Generate asks Claude and returns the evaluation.
|
|
func Generate(ctx context.Context, a explain.Asker, in Input, now time.Time) (*Evaluation, error) {
|
|
var r Result
|
|
err := a.JSON(ctx, claude.Request{System: System, User: Prompt(in), Schema: Schema, MaxTokens: maxTokens}, &r)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
tests := in.RunNote
|
|
if in.Run != nil {
|
|
tests = Outcome(in.Run)
|
|
}
|
|
return &Evaluation{Result: clean(r, in.Source), Lang: in.Lang, Source: in.Source, Model: a.Model(), At: now, Tests: tests}, nil
|
|
}
|
|
|
|
// clean keeps the reply inside what the page can show: lines that exist,
|
|
// severities it knows, and a counterexample only when it is whole.
|
|
func clean(r Result, src string) Result {
|
|
lines := strings.Count(strings.TrimRight(src, "\n"), "\n") + 1
|
|
issues := []Issue{}
|
|
for _, is := range r.Issues {
|
|
if is.Line < 0 || is.Line > lines {
|
|
is.Line = 0
|
|
}
|
|
switch is.Severity {
|
|
case "error", "warning", "info":
|
|
default:
|
|
is.Severity = "info"
|
|
}
|
|
if strings.TrimSpace(is.Title) != "" || strings.TrimSpace(is.Detail) != "" {
|
|
issues = append(issues, is)
|
|
}
|
|
}
|
|
r.Issues = issues
|
|
if strings.TrimSpace(r.Counterexample.Input) == "" || strings.TrimSpace(r.Counterexample.Expected) == "" {
|
|
r.Counterexample = Counterexample{}
|
|
}
|
|
return r
|
|
}
|