AgPerry's picture
Add files using upload-large-folder tool
fb2916f verified
Raw History Blame Contribute Delete
10.2 kB
"""Deterministic offline verdict model.
The server never executes guest source code, in any language, under any
identity. A submission is graded by a fixed, ordered set of rules applied to
the submitted text, while the *expected* output of each test case is produced
by this repository's own reference implementations
(:mod:`leetcode_app.content`).
Rule order, applied to the comment-stripped source:
1. blank source -> Compile Error
2. required entry point missing -> Compile Error
3. source still equals the starter -> Wrong Answer, no output produced
4. no result-producing statement -> Wrong Answer, no output produced
5. no token of the question's method -> Wrong Answer at the first case
6. otherwise -> Accepted
Everything derived from the source (verdict, runtime, memory, the failing
case) is a pure function of ``(question, language, source, cases)``: the same
submission always produces the same result.
"""
from __future__ import annotations
import hashlib
import json
import re
from dataclasses import dataclass, field
from typing import Any
from . import content
from .content import Question
ACCEPTED = "Accepted"
WRONG_ANSWER = "Wrong Answer"
COMPILE_ERROR = "Compile Error"
RUNTIME_ERROR = "Runtime Error"
# A statement that produces the answer, per language.
RESULT_TOKENS: dict[str, tuple[str, ...]] = {
"python3": ("return",),
"pandas": ("return",),
"cpp": ("return",),
"java": ("return",),
"javascript": ("return",),
"mysql": ("select",),
"bash": ("sed", "awk", "head", "tail", "cat", "nl", "echo", "sort", "printf"),
}
# The declaration a compiler needs to find, per language.
ENTRY_MARKERS: dict[str, tuple[str, ...]] = {
"python3": ("class solution", "def "),
"pandas": ("def ",),
"cpp": ("class solution",),
"java": ("class solution",),
"javascript": ("var ", "function", "const ", "let "),
"mysql": ("select",),
"bash": (),
}
ENTRY_MESSAGES: dict[str, str] = {
"python3": "NameError: name 'Solution' is not defined",
"pandas": "NameError: the required function is not defined",
"cpp": "error: 'Solution' was not declared in this scope",
"java": "error: cannot find symbol: class Solution",
"javascript": "ReferenceError: the required function is not defined",
"mysql": "You have an error in your SQL syntax",
"bash": "command not found",
}
_LINE_COMMENTS: dict[str, tuple[str, ...]] = {
"python3": ("#",),
"pandas": ("#",),
"bash": ("#",),
"mysql": ("--", "#"),
"cpp": ("//",),
"java": ("//",),
"javascript": ("//",),
}
_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
_SQL_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
_WHITESPACE = re.compile(r"\s+")
class CaseInputError(ValueError):
"""A test case could not be read as input for this question."""
@dataclass
class CaseResult:
index: int
input: str
output: str | None
expected: str
passed: bool
executed: bool = True
def as_dict(self) -> dict[str, Any]:
return {
"index": self.index,
"input": self.input,
"output": self.output,
"expected": self.expected,
"passed": self.passed,
"executed": self.executed,
}
@dataclass
class Verdict:
status: str
message: str = ""
cases: list[CaseResult] = field(default_factory=list)
runtime_ms: int | None = None
memory_mb: float | None = None
runtime_percentile: float | None = None
memory_percentile: float | None = None
@property
def passed(self) -> int:
return sum(1 for case in self.cases if case.passed)
@property
def total(self) -> int:
return len(self.cases)
@property
def failing(self) -> CaseResult | None:
for case in self.cases:
if not case.passed:
return case
return None
def as_dict(self) -> dict[str, Any]:
failing = self.failing
return {
"status": self.status,
"message": self.message,
"passed": self.passed,
"total": self.total,
"runtime_ms": self.runtime_ms,
"memory_mb": self.memory_mb,
"runtime_percentile": self.runtime_percentile,
"memory_percentile": self.memory_percentile,
"cases": [case.as_dict() for case in self.cases],
"failing": failing.as_dict() if failing is not None else None,
}
def strip_comments(source: str, language: str) -> str:
text = source
if language in {"cpp", "java", "javascript"}:
text = _BLOCK_COMMENT.sub(" ", text)
if language == "mysql":
text = _SQL_BLOCK_COMMENT.sub(" ", text)
markers = _LINE_COMMENTS.get(language, ("#",))
lines: list[str] = []
for line in text.splitlines():
cut = len(line)
for marker in markers:
position = line.find(marker)
if position != -1:
cut = min(cut, position)
lines.append(line[:cut])
return "\n".join(lines)
def normalize(source: str) -> str:
return _WHITESPACE.sub(" ", source).strip()
def _digest(question: Question, language: str, source: str) -> bytes:
payload = f"{question.slug}\0{language}\0{normalize(source)}".encode("utf-8")
return hashlib.sha256(payload).digest()
def _performance(question: Question, language: str, source: str) -> dict[str, Any]:
"""Deterministic runtime/memory figures derived from the submission."""
digest = _digest(question, language, source)
runtime_ms = digest[0] % 90
memory_mb = 15.0 + (digest[1] % 60) / 10
runtime_percentile = round(20.0 + (digest[2] % 790) / 10, 2)
memory_percentile = round(20.0 + (digest[3] % 790) / 10, 2)
return {
"runtime_ms": runtime_ms,
"memory_mb": round(memory_mb, 2),
"runtime_percentile": runtime_percentile,
"memory_percentile": memory_percentile,
}
def expected_output(question: Question, raw_case: str) -> str:
"""Expected output for one case, from this repository's own reference."""
fixed = question.fixed_expected.get(raw_case.strip())
if fixed is not None:
return fixed
reference = content.REFERENCES.get(question.slug)
if reference is None:
raise CaseInputError(
"This question runs against its own fixed data set."
)
try:
arguments = content.parse_case(raw_case)
except (json.JSONDecodeError, ValueError) as error:
raise CaseInputError(f"The test case could not be read: {error}") from error
if not arguments:
raise CaseInputError("The test case is empty.")
try:
return content.format_expected(reference(*arguments))
except TypeError as error:
raise CaseInputError(
"The test case does not match this question's input format."
) from error
except (IndexError, KeyError, ValueError, ZeroDivisionError) as error:
raise CaseInputError(f"The test case could not be evaluated: {error}") from error
def _entry_markers(question: Question, language: str) -> tuple[str, ...]:
override = question.entry_markers.get(language)
if override is not None:
return override
return ENTRY_MARKERS.get(language, ())
def classify(question: Question, language: str, source: str) -> tuple[str, str]:
"""Return ``(status, message)`` for the submission's source alone."""
stripped = strip_comments(source, language)
if not stripped.strip():
return COMPILE_ERROR, "error: the submission is empty"
lowered = stripped.casefold()
for marker in _entry_markers(question, language):
if marker not in lowered:
return COMPILE_ERROR, ENTRY_MESSAGES.get(language, "error: compile failed")
starter = question.starter.get(language, "")
if normalize(strip_comments(starter, language)) == normalize(stripped):
return WRONG_ANSWER, "The starter code does not produce an answer yet."
result_tokens = RESULT_TOKENS.get(language, ("return",))
if not any(token in lowered for token in result_tokens):
return WRONG_ANSWER, "The submission never produces a result."
if not any(token in lowered for token in question.technique_tokens):
return WRONG_ANSWER, ""
return ACCEPTED, ""
def evaluate(
question: Question,
language: str,
source: str,
cases: list[str],
) -> Verdict:
"""Grade ``source`` against ``cases`` and return the verdict."""
status, message = classify(question, language, source)
results: list[CaseResult] = []
produce_output = status == ACCEPTED
failing_index = 0 if status == WRONG_ANSWER else -1
for index, raw_case in enumerate(cases):
try:
expected = expected_output(question, raw_case)
except CaseInputError as error:
return Verdict(status=RUNTIME_ERROR, message=str(error), cases=[])
output: str | None
if produce_output:
output, passed, executed = expected, True, True
elif status == COMPILE_ERROR:
output, passed, executed = None, False, False
elif index == failing_index:
output = None if message else question.wrong_output
passed, executed = False, True
else:
# Execution stops at the first case that does not match.
output, passed, executed = None, False, False
results.append(
CaseResult(
index=index,
input=raw_case,
output=output,
expected=expected,
passed=passed,
executed=executed,
)
)
verdict = Verdict(status=status, message=message, cases=results)
if status == ACCEPTED:
for key, value in _performance(question, language, source).items():
setattr(verdict, key, value)
elif status == WRONG_ANSWER:
performance = _performance(question, language, source)
verdict.runtime_ms = performance["runtime_ms"]
verdict.memory_mb = performance["memory_mb"]
return verdict