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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Test runner for the Idea First, Code Later CP Benchmark dataset.
|
| 3 |
+
|
| 4 |
+
This module provides tools to load competitive programming problems from the
|
| 5 |
+
Hugging Face dataset and run solutions against their test cases.
|
| 6 |
+
|
| 7 |
+
Features:
|
| 8 |
+
- Automatic dataset loading from Hugging Face
|
| 9 |
+
- Support for C++ and Python solutions
|
| 10 |
+
- Special judge support for problems with multiple valid outputs
|
| 11 |
+
- Kattis integration for CS3233 problems
|
| 12 |
+
- Memory and time limit enforcement
|
| 13 |
+
|
| 14 |
+
Example:
|
| 15 |
+
>>> from hf_test_runner import TestRunner
|
| 16 |
+
>>> runner = TestRunner()
|
| 17 |
+
>>> results = runner.run_solution(
|
| 18 |
+
... problem_id="icpc-jakarta-2019_card-collecting",
|
| 19 |
+
... solution_code=open("solution.cpp").read(),
|
| 20 |
+
... language="cpp"
|
| 21 |
+
... )
|
| 22 |
+
>>> print(results["status"]) # "PASSED" or error type
|
| 23 |
+
|
| 24 |
+
Classes:
|
| 25 |
+
TestRunner: Main class for running solutions against problems.
|
| 26 |
+
Problem: Dataclass representing a problem from the dataset.
|
| 27 |
+
|
| 28 |
+
Functions:
|
| 29 |
+
run_solution: Convenience function for quick one-off solution testing.
|
| 30 |
+
parse_time_limit: Parse time limit strings like "2 sec" to float.
|
| 31 |
+
parse_memory_limit_to_bytes: Parse memory limit strings to bytes.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
import os
|
| 35 |
+
import re
|
| 36 |
+
import subprocess
|
| 37 |
+
import tempfile
|
| 38 |
+
import time
|
| 39 |
+
import signal
|
| 40 |
+
import resource
|
| 41 |
+
import traceback
|
| 42 |
+
from dataclasses import dataclass
|
| 43 |
+
from typing import Optional
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
from datasets import load_dataset
|
| 47 |
+
except ImportError:
|
| 48 |
+
print("Please install datasets: pip install datasets")
|
| 49 |
+
raise
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# Constants
|
| 53 |
+
PREEXEC_ERROR_EXIT_CODE = 2
|
| 54 |
+
HF_DATASET_ID = "samahadhoud/idea-first-code-later-cp"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@dataclass
|
| 58 |
+
class Problem:
|
| 59 |
+
"""
|
| 60 |
+
Represents a competitive programming problem loaded from the HF dataset.
|
| 61 |
+
|
| 62 |
+
Attributes:
|
| 63 |
+
problem_id: Unique identifier in format "contest_slug" (e.g., "icpc-jakarta-2019_card-collecting")
|
| 64 |
+
problem_code: Problem letter in the contest (A, B, C, ...)
|
| 65 |
+
problem_slug: URL-friendly problem name
|
| 66 |
+
problem_title: Full human-readable problem title
|
| 67 |
+
|
| 68 |
+
contest_name: Contest identifier (e.g., "icpc-jakarta-2019")
|
| 69 |
+
contest_full_name: Full contest name (e.g., "ICPC Asia Jakarta Regional Contest 2019")
|
| 70 |
+
year: Competition year as string
|
| 71 |
+
source: Source URL or repository
|
| 72 |
+
|
| 73 |
+
time_limit: Time limit as string (e.g., "2 sec")
|
| 74 |
+
memory_limit: Memory limit as string (e.g., "256 MB")
|
| 75 |
+
|
| 76 |
+
statement: Problem statement in Markdown format
|
| 77 |
+
analysis: Editorial/solution analysis in Markdown
|
| 78 |
+
|
| 79 |
+
sample_test_cases_input: List of sample input strings (shown in problem statement)
|
| 80 |
+
sample_test_cases_output: List of corresponding sample outputs
|
| 81 |
+
hidden_test_cases_input: List of hidden input strings (for actual judging)
|
| 82 |
+
hidden_test_cases_output: List of corresponding hidden outputs
|
| 83 |
+
|
| 84 |
+
has_special_judge: True if problem accepts multiple valid outputs
|
| 85 |
+
special_judge_code: C++ scorer code using testlib for validation
|
| 86 |
+
special_judge_format: "standard" or "jakarta2017" (different CLI formats)
|
| 87 |
+
|
| 88 |
+
uses_kattis: True for CS3233 problems (must submit via Kattis)
|
| 89 |
+
kattis_problem_id: Kattis problem ID for submission
|
| 90 |
+
"""
|
| 91 |
+
problem_id: str
|
| 92 |
+
problem_code: str
|
| 93 |
+
problem_slug: str
|
| 94 |
+
problem_title: str
|
| 95 |
+
|
| 96 |
+
contest_name: str
|
| 97 |
+
contest_full_name: str
|
| 98 |
+
year: str
|
| 99 |
+
source: str
|
| 100 |
+
|
| 101 |
+
time_limit: str
|
| 102 |
+
memory_limit: str
|
| 103 |
+
|
| 104 |
+
statement: str
|
| 105 |
+
analysis: str
|
| 106 |
+
|
| 107 |
+
sample_test_cases_input: list
|
| 108 |
+
sample_test_cases_output: list
|
| 109 |
+
hidden_test_cases_input: list
|
| 110 |
+
hidden_test_cases_output: list
|
| 111 |
+
|
| 112 |
+
has_special_judge: bool
|
| 113 |
+
special_judge_code: str
|
| 114 |
+
special_judge_format: str
|
| 115 |
+
|
| 116 |
+
uses_kattis: bool
|
| 117 |
+
kattis_problem_id: str
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def parse_time_limit(time_str: str) -> float:
|
| 121 |
+
"""
|
| 122 |
+
Parse a time limit string to seconds.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
time_str: Time limit string (e.g., "2 sec", "1.5s", "3")
|
| 126 |
+
|
| 127 |
+
Returns:
|
| 128 |
+
Time limit in seconds as float. Returns 10.0 if parsing fails.
|
| 129 |
+
|
| 130 |
+
Examples:
|
| 131 |
+
>>> parse_time_limit("2 sec")
|
| 132 |
+
2.0
|
| 133 |
+
>>> parse_time_limit("1.5s")
|
| 134 |
+
1.5
|
| 135 |
+
>>> parse_time_limit("")
|
| 136 |
+
10.0
|
| 137 |
+
"""
|
| 138 |
+
if not time_str:
|
| 139 |
+
return 10.0 # default
|
| 140 |
+
match = re.search(r'([\d.]+)\s*(?:sec|s)?', time_str.lower())
|
| 141 |
+
if match:
|
| 142 |
+
return float(match.group(1))
|
| 143 |
+
return 10.0
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def parse_memory_limit_to_bytes(value) -> Optional[int]:
|
| 147 |
+
"""
|
| 148 |
+
Parse a memory limit value to bytes.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
value: Memory limit as int (MB), float (MB), or string (e.g., "256 MB", "1 GB")
|
| 152 |
+
|
| 153 |
+
Returns:
|
| 154 |
+
Memory limit in bytes, or None if unlimited/unspecified.
|
| 155 |
+
|
| 156 |
+
Raises:
|
| 157 |
+
ValueError: If the value cannot be parsed or is negative.
|
| 158 |
+
|
| 159 |
+
Examples:
|
| 160 |
+
>>> parse_memory_limit_to_bytes(256)
|
| 161 |
+
268435456
|
| 162 |
+
>>> parse_memory_limit_to_bytes("256 MB")
|
| 163 |
+
268435456
|
| 164 |
+
>>> parse_memory_limit_to_bytes("1 GB")
|
| 165 |
+
1073741824
|
| 166 |
+
>>> parse_memory_limit_to_bytes(None)
|
| 167 |
+
None
|
| 168 |
+
"""
|
| 169 |
+
if value is None:
|
| 170 |
+
return None
|
| 171 |
+
if isinstance(value, (int, float)):
|
| 172 |
+
if value < 0:
|
| 173 |
+
raise ValueError("memory limit must be non-negative")
|
| 174 |
+
return int(value * 1024 * 1024)
|
| 175 |
+
|
| 176 |
+
if isinstance(value, str):
|
| 177 |
+
s = value.strip().lower()
|
| 178 |
+
if s in ("none", "unlimited", "0", ""):
|
| 179 |
+
return None
|
| 180 |
+
m = re.match(r"^\s*([0-9]*\.?[0-9]+)\s*([kmgtp]?b?|)$", s)
|
| 181 |
+
if not m:
|
| 182 |
+
raise ValueError(f"cannot parse memory limit '{value}'")
|
| 183 |
+
num = float(m.group(1))
|
| 184 |
+
unit = m.group(2)
|
| 185 |
+
if unit in ("", "b"):
|
| 186 |
+
multiplier = 1024 * 1024
|
| 187 |
+
elif unit in ("k", "kb"):
|
| 188 |
+
multiplier = 1024
|
| 189 |
+
elif unit in ("m", "mb"):
|
| 190 |
+
multiplier = 1024 * 1024
|
| 191 |
+
elif unit in ("g", "gb"):
|
| 192 |
+
multiplier = 1024 * 1024 * 1024
|
| 193 |
+
else:
|
| 194 |
+
raise ValueError(f"unknown unit in memory limit '{value}'")
|
| 195 |
+
return int(num * multiplier)
|
| 196 |
+
|
| 197 |
+
raise ValueError("unsupported type for memory limit")
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _preexec_setrlimit_bytes(bytes_limit):
|
| 201 |
+
"""
|
| 202 |
+
Set memory limit in child process using setrlimit.
|
| 203 |
+
|
| 204 |
+
This function is designed to be used as a preexec_fn in subprocess.run().
|
| 205 |
+
It sets RLIMIT_AS (address space limit) to enforce memory limits on
|
| 206 |
+
the child process.
|
| 207 |
+
|
| 208 |
+
Args:
|
| 209 |
+
bytes_limit: Memory limit in bytes, or None for no limit.
|
| 210 |
+
|
| 211 |
+
Note:
|
| 212 |
+
If this function fails, it writes the traceback to stderr and
|
| 213 |
+
exits with PREEXEC_ERROR_EXIT_CODE (2) to signal the error.
|
| 214 |
+
On macOS, RLIMIT_AS may not be supported, so failures are silently ignored.
|
| 215 |
+
"""
|
| 216 |
+
try:
|
| 217 |
+
if bytes_limit is None:
|
| 218 |
+
return
|
| 219 |
+
if not isinstance(bytes_limit, int) or bytes_limit < 0:
|
| 220 |
+
raise ValueError("bytes_limit must be non-negative int")
|
| 221 |
+
# Try to set memory limit (may fail on macOS)
|
| 222 |
+
try:
|
| 223 |
+
resource.setrlimit(resource.RLIMIT_AS, (bytes_limit, bytes_limit))
|
| 224 |
+
except (ValueError, OSError):
|
| 225 |
+
# RLIMIT_AS not supported on macOS, silently ignore
|
| 226 |
+
pass
|
| 227 |
+
except Exception:
|
| 228 |
+
try:
|
| 229 |
+
tb = traceback.format_exc()
|
| 230 |
+
os.write(2, tb.encode("utf-8", errors="replace"))
|
| 231 |
+
except Exception:
|
| 232 |
+
pass
|
| 233 |
+
os._exit(PREEXEC_ERROR_EXIT_CODE)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
class TestRunner:
|
| 237 |
+
"""
|
| 238 |
+
Test runner for the Idea First, Code Later CP Benchmark dataset.
|
| 239 |
+
|
| 240 |
+
This class loads problems from Hugging Face and provides methods to run
|
| 241 |
+
solutions against test cases with proper judging, time/memory limits,
|
| 242 |
+
and special judge support.
|
| 243 |
+
|
| 244 |
+
Attributes:
|
| 245 |
+
dataset: The loaded HuggingFace dataset
|
| 246 |
+
problems: Dict mapping problem_id to problem data
|
| 247 |
+
|
| 248 |
+
Example:
|
| 249 |
+
>>> runner = TestRunner()
|
| 250 |
+
>>> results = runner.run_solution(
|
| 251 |
+
... problem_id="icpc-jakarta-2019_card-collecting",
|
| 252 |
+
... solution_code=code,
|
| 253 |
+
... language="cpp"
|
| 254 |
+
... )
|
| 255 |
+
>>> if results["status"] == "PASSED":
|
| 256 |
+
... print("All tests passed!")
|
| 257 |
+
"""
|
| 258 |
+
|
| 259 |
+
def __init__(self, dataset_id: str = HF_DATASET_ID, cache_dir: Optional[str] = None):
|
| 260 |
+
"""
|
| 261 |
+
Initialize the test runner and load the dataset from Hugging Face.
|
| 262 |
+
|
| 263 |
+
Args:
|
| 264 |
+
dataset_id: HuggingFace dataset ID (default: samahadhoud/idea-first-code-later-cp)
|
| 265 |
+
cache_dir: Optional local cache directory for the dataset
|
| 266 |
+
|
| 267 |
+
Raises:
|
| 268 |
+
ImportError: If the datasets library is not installed
|
| 269 |
+
"""
|
| 270 |
+
print(f"Loading dataset from {dataset_id}...")
|
| 271 |
+
self.dataset = load_dataset(dataset_id, cache_dir=cache_dir)["train"]
|
| 272 |
+
self.problems = {row["problem_id"]: row for row in self.dataset}
|
| 273 |
+
print(f"Loaded {len(self.problems)} problems")
|
| 274 |
+
|
| 275 |
+
def get_problem(self, problem_id: str) -> Problem:
|
| 276 |
+
"""
|
| 277 |
+
Retrieve a problem by its ID.
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
problem_id: Unique problem identifier (e.g., "icpc-jakarta-2019_card-collecting")
|
| 281 |
+
|
| 282 |
+
Returns:
|
| 283 |
+
Problem object with all problem data.
|
| 284 |
+
|
| 285 |
+
Raises:
|
| 286 |
+
ValueError: If the problem_id is not found in the dataset.
|
| 287 |
+
|
| 288 |
+
Example:
|
| 289 |
+
>>> problem = runner.get_problem("icpc-jakarta-2019_card-collecting")
|
| 290 |
+
>>> print(problem.problem_title)
|
| 291 |
+
'Card Collecting'
|
| 292 |
+
"""
|
| 293 |
+
if problem_id not in self.problems:
|
| 294 |
+
raise ValueError(f"Problem {problem_id} not found. Available: {list(self.problems.keys())[:5]}...")
|
| 295 |
+
|
| 296 |
+
row = self.problems[problem_id]
|
| 297 |
+
return Problem(
|
| 298 |
+
problem_id=row["problem_id"],
|
| 299 |
+
problem_code=row["problem_code"],
|
| 300 |
+
problem_slug=row["problem_slug"],
|
| 301 |
+
problem_title=row["problem_title"],
|
| 302 |
+
contest_name=row["contest_name"],
|
| 303 |
+
contest_full_name=row["contest_full_name"],
|
| 304 |
+
year=row["year"],
|
| 305 |
+
source=row["source"],
|
| 306 |
+
time_limit=row["time_limit"],
|
| 307 |
+
memory_limit=row["memory_limit"],
|
| 308 |
+
statement=row["statement"],
|
| 309 |
+
analysis=row["analysis"],
|
| 310 |
+
sample_test_cases_input=row["sample_test_cases_input"],
|
| 311 |
+
sample_test_cases_output=row["sample_test_cases_output"],
|
| 312 |
+
hidden_test_cases_input=row["hidden_test_cases_input"],
|
| 313 |
+
hidden_test_cases_output=row["hidden_test_cases_output"],
|
| 314 |
+
has_special_judge=row["has_special_judge"],
|
| 315 |
+
special_judge_code=row["special_judge_code"],
|
| 316 |
+
special_judge_format=row["special_judge_format"],
|
| 317 |
+
uses_kattis=row["uses_kattis"],
|
| 318 |
+
kattis_problem_id=row["kattis_problem_id"],
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
def list_problems(self, contest: Optional[str] = None) -> list:
|
| 322 |
+
"""
|
| 323 |
+
List all available problem IDs, optionally filtered by contest.
|
| 324 |
+
|
| 325 |
+
Args:
|
| 326 |
+
contest: Optional substring to filter by (e.g., "jakarta-2019")
|
| 327 |
+
|
| 328 |
+
Returns:
|
| 329 |
+
List of problem ID strings.
|
| 330 |
+
|
| 331 |
+
Example:
|
| 332 |
+
>>> runner.list_problems()[:3]
|
| 333 |
+
['cs3233-2023_a', 'cs3233-2023_b', 'cs3233-2023_c']
|
| 334 |
+
>>> runner.list_problems("jakarta-2017")
|
| 335 |
+
['icpc-jakarta-2017_...']
|
| 336 |
+
"""
|
| 337 |
+
if contest:
|
| 338 |
+
return [pid for pid in self.problems if contest in pid]
|
| 339 |
+
return list(self.problems.keys())
|
| 340 |
+
|
| 341 |
+
def run_solution(
|
| 342 |
+
self,
|
| 343 |
+
problem_id: str,
|
| 344 |
+
solution_code: str,
|
| 345 |
+
language: str = "cpp",
|
| 346 |
+
run_hidden: bool = True,
|
| 347 |
+
solution_file: Optional[str] = None,
|
| 348 |
+
) -> dict:
|
| 349 |
+
"""
|
| 350 |
+
Run a solution against a problem's test cases.
|
| 351 |
+
|
| 352 |
+
Executes the solution code against sample tests first, then hidden tests
|
| 353 |
+
if sample tests pass. Handles compilation, time/memory limits, and
|
| 354 |
+
special judges automatically.
|
| 355 |
+
|
| 356 |
+
Args:
|
| 357 |
+
problem_id: The problem ID from the dataset
|
| 358 |
+
solution_code: The solution source code as a string
|
| 359 |
+
language: Programming language - "cpp" (default) or "Python"
|
| 360 |
+
run_hidden: Whether to run hidden test cases after samples pass
|
| 361 |
+
solution_file: Optional path to solution file (used for Kattis submission)
|
| 362 |
+
|
| 363 |
+
Returns:
|
| 364 |
+
dict with keys:
|
| 365 |
+
- status: "PASSED", "Wrong Answer", "Time Limit Exceeded",
|
| 366 |
+
"Memory Limit Exceeded", "Runtime Error", or "Compile Error"
|
| 367 |
+
- problem_id: The problem ID
|
| 368 |
+
- problem_title: Human-readable problem title
|
| 369 |
+
- test_cases: List of individual test results
|
| 370 |
+
- sample_summary: Dict with pass/fail counts for sample tests
|
| 371 |
+
- hidden_summary: Dict with pass/fail counts for hidden tests
|
| 372 |
+
|
| 373 |
+
Example:
|
| 374 |
+
>>> results = runner.run_solution(
|
| 375 |
+
... "icpc-jakarta-2019_card-collecting",
|
| 376 |
+
... open("solution.cpp").read(),
|
| 377 |
+
... language="cpp"
|
| 378 |
+
... )
|
| 379 |
+
>>> print(results["status"])
|
| 380 |
+
'PASSED'
|
| 381 |
+
"""
|
| 382 |
+
problem = self.get_problem(problem_id)
|
| 383 |
+
|
| 384 |
+
# Handle Kattis problems
|
| 385 |
+
if problem.uses_kattis:
|
| 386 |
+
return self._run_kattis(problem, solution_code, solution_file, language)
|
| 387 |
+
|
| 388 |
+
# Compile special judge if needed
|
| 389 |
+
scorer_executable = None
|
| 390 |
+
if problem.has_special_judge and problem.special_judge_code:
|
| 391 |
+
scorer_executable = self._compile_scorer(problem)
|
| 392 |
+
|
| 393 |
+
results = {
|
| 394 |
+
"problem_id": problem_id,
|
| 395 |
+
"problem_title": problem.problem_title,
|
| 396 |
+
"status": "PASSED",
|
| 397 |
+
"test_cases": [],
|
| 398 |
+
"sample_summary": {},
|
| 399 |
+
"hidden_summary": {},
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
time_limit = parse_time_limit(problem.time_limit)
|
| 403 |
+
memory_limit = problem.memory_limit
|
| 404 |
+
|
| 405 |
+
# Run sample tests
|
| 406 |
+
sample_passed = self._run_tests(
|
| 407 |
+
problem, solution_code, language,
|
| 408 |
+
problem.sample_test_cases_input,
|
| 409 |
+
problem.sample_test_cases_output,
|
| 410 |
+
"sample", results, time_limit, memory_limit,
|
| 411 |
+
scorer_executable
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
if not sample_passed:
|
| 415 |
+
return results
|
| 416 |
+
|
| 417 |
+
# Run hidden tests
|
| 418 |
+
if run_hidden and problem.hidden_test_cases_input:
|
| 419 |
+
self._run_tests(
|
| 420 |
+
problem, solution_code, language,
|
| 421 |
+
problem.hidden_test_cases_input,
|
| 422 |
+
problem.hidden_test_cases_output,
|
| 423 |
+
"hidden", results, time_limit, memory_limit,
|
| 424 |
+
scorer_executable
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
return results
|
| 428 |
+
|
| 429 |
+
def _run_kattis(
|
| 430 |
+
self,
|
| 431 |
+
problem: Problem,
|
| 432 |
+
solution_code: str,
|
| 433 |
+
solution_file: Optional[str],
|
| 434 |
+
language: str
|
| 435 |
+
) -> dict:
|
| 436 |
+
"""
|
| 437 |
+
Submit a solution to Kattis for CS3233 problems.
|
| 438 |
+
|
| 439 |
+
CS3233 problems are judged on Kattis and don't have local hidden test cases.
|
| 440 |
+
This method submits the solution via the Kattis CLI and parses the result.
|
| 441 |
+
|
| 442 |
+
Args:
|
| 443 |
+
problem: The Problem object
|
| 444 |
+
solution_code: Solution source code
|
| 445 |
+
solution_file: Optional path to existing solution file
|
| 446 |
+
language: "cpp" or "Python"
|
| 447 |
+
|
| 448 |
+
Returns:
|
| 449 |
+
dict with status, kattis_output, and execution time
|
| 450 |
+
|
| 451 |
+
Note:
|
| 452 |
+
Requires kattis-cli to be installed and configured:
|
| 453 |
+
https://github.com/Kattis/kattis-cli
|
| 454 |
+
"""
|
| 455 |
+
if not solution_file:
|
| 456 |
+
# Create temp file
|
| 457 |
+
ext = ".py" if language == "Python" else ".cpp"
|
| 458 |
+
with tempfile.NamedTemporaryFile(mode="w", suffix=ext, delete=False) as f:
|
| 459 |
+
f.write(solution_code)
|
| 460 |
+
solution_file = f.name
|
| 461 |
+
|
| 462 |
+
print(f"Submitting to Kattis: {problem.kattis_problem_id}")
|
| 463 |
+
|
| 464 |
+
try:
|
| 465 |
+
proc = subprocess.run(
|
| 466 |
+
["kattis", solution_file, "-p", problem.kattis_problem_id, "-f"],
|
| 467 |
+
capture_output=True, text=True, timeout=300
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
stdout = proc.stdout
|
| 471 |
+
stderr = proc.stderr
|
| 472 |
+
|
| 473 |
+
print(f"📤 Kattis output:\n{stdout}")
|
| 474 |
+
|
| 475 |
+
# Extract verdict
|
| 476 |
+
verdict_match = re.search(
|
| 477 |
+
r'(Accepted|Wrong Answer|Time Limit Exceeded|Run Time Error|Compile Error|Memory Limit Exceeded)',
|
| 478 |
+
stdout
|
| 479 |
+
)
|
| 480 |
+
time_match = re.search(r'\(([\d.]+)s\)', stdout)
|
| 481 |
+
|
| 482 |
+
raw_verdict = verdict_match.group(1) if verdict_match else "Unknown"
|
| 483 |
+
|
| 484 |
+
verdict_map = {
|
| 485 |
+
"Accepted": "PASSED",
|
| 486 |
+
"Wrong Answer": "Wrong Answer",
|
| 487 |
+
"Time Limit Exceeded": "Time Limit Exceeded",
|
| 488 |
+
"Run Time Error": "Runtime Error",
|
| 489 |
+
"Compile Error": "Compile Error",
|
| 490 |
+
"Memory Limit Exceeded": "Memory Limit Exceeded",
|
| 491 |
+
"Unknown": "Runtime Error"
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
return {
|
| 495 |
+
"problem_id": problem.problem_id,
|
| 496 |
+
"problem_title": problem.problem_title,
|
| 497 |
+
"status": verdict_map.get(raw_verdict, "Runtime Error"),
|
| 498 |
+
"time": float(time_match.group(1)) if time_match else None,
|
| 499 |
+
"kattis_output": stdout,
|
| 500 |
+
"kattis_stderr": stderr,
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
except Exception as e:
|
| 504 |
+
return {
|
| 505 |
+
"problem_id": problem.problem_id,
|
| 506 |
+
"status": "Submission Failed",
|
| 507 |
+
"error": str(e)
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
def _compile_scorer(self, problem: Problem) -> Optional[str]:
|
| 511 |
+
"""
|
| 512 |
+
Compile the special judge scorer for problems with multiple valid outputs.
|
| 513 |
+
|
| 514 |
+
Some problems accept multiple correct answers (e.g., "print any valid permutation").
|
| 515 |
+
These use a custom scorer (written in C++ using testlib) to validate outputs.
|
| 516 |
+
|
| 517 |
+
Args:
|
| 518 |
+
problem: The Problem object containing special_judge_code
|
| 519 |
+
|
| 520 |
+
Returns:
|
| 521 |
+
Path to the compiled scorer executable, or None if compilation fails.
|
| 522 |
+
|
| 523 |
+
Note:
|
| 524 |
+
The scorer is compiled with g++ -std=c++17. The executable is stored
|
| 525 |
+
in a temporary directory that persists for the duration of testing.
|
| 526 |
+
On macOS, bits/stdc++.h is replaced with standard includes.
|
| 527 |
+
"""
|
| 528 |
+
# Create persistent temp directory for scorer (not auto-deleted)
|
| 529 |
+
tmp_dir = tempfile.mkdtemp(prefix="scorer_")
|
| 530 |
+
scorer_src = os.path.join(tmp_dir, "scorer.cpp")
|
| 531 |
+
scorer_exe = os.path.join(tmp_dir, "scorer")
|
| 532 |
+
|
| 533 |
+
scorer_code = problem.special_judge_code
|
| 534 |
+
|
| 535 |
+
# Handle bits/stdc++.h which doesn't exist on macOS
|
| 536 |
+
if "#include <bits/stdc++.h>" in scorer_code or '#include "bits/stdc++.h"' in scorer_code:
|
| 537 |
+
# Replace with common standard includes
|
| 538 |
+
replacement = """#include <iostream>
|
| 539 |
+
#include <vector>
|
| 540 |
+
#include <string>
|
| 541 |
+
#include <algorithm>
|
| 542 |
+
#include <cmath>
|
| 543 |
+
#include <set>
|
| 544 |
+
#include <map>
|
| 545 |
+
#include <cstdio>
|
| 546 |
+
#include <cstdlib>
|
| 547 |
+
#include <cstring>
|
| 548 |
+
#include <sstream>
|
| 549 |
+
#include <fstream>"""
|
| 550 |
+
scorer_code = scorer_code.replace('#include <bits/stdc++.h>', replacement)
|
| 551 |
+
scorer_code = scorer_code.replace('#include "bits/stdc++.h"', replacement)
|
| 552 |
+
|
| 553 |
+
with open(scorer_src, "w") as f:
|
| 554 |
+
f.write(scorer_code)
|
| 555 |
+
|
| 556 |
+
result = subprocess.run(
|
| 557 |
+
["g++", "-o", scorer_exe, scorer_src, "-std=c++17"],
|
| 558 |
+
capture_output=True, text=True
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
if result.returncode != 0:
|
| 562 |
+
print(f"⚠️ Scorer compilation failed: {result.stderr}")
|
| 563 |
+
return None
|
| 564 |
+
|
| 565 |
+
os.chmod(scorer_exe, 0o755)
|
| 566 |
+
return scorer_exe
|
| 567 |
+
|
| 568 |
+
def _run_tests(
|
| 569 |
+
self,
|
| 570 |
+
problem: Problem,
|
| 571 |
+
solution_code: str,
|
| 572 |
+
language: str,
|
| 573 |
+
inputs: list,
|
| 574 |
+
outputs: list,
|
| 575 |
+
test_type: str,
|
| 576 |
+
results: dict,
|
| 577 |
+
time_limit: float,
|
| 578 |
+
memory_limit: str,
|
| 579 |
+
scorer_executable: Optional[str],
|
| 580 |
+
) -> bool:
|
| 581 |
+
"""
|
| 582 |
+
Run a set of test cases against a solution.
|
| 583 |
+
|
| 584 |
+
Executes the solution for each input, compares output with expected,
|
| 585 |
+
and handles time/memory limits and special judging.
|
| 586 |
+
|
| 587 |
+
Args:
|
| 588 |
+
problem: The Problem object
|
| 589 |
+
solution_code: Source code to execute
|
| 590 |
+
language: "cpp" or "Python"
|
| 591 |
+
inputs: List of input strings
|
| 592 |
+
outputs: List of expected output strings
|
| 593 |
+
test_type: "sample" or "hidden" (for labeling results)
|
| 594 |
+
results: Dict to append test results to (modified in place)
|
| 595 |
+
time_limit: Time limit in seconds
|
| 596 |
+
memory_limit: Memory limit as string (e.g., "256 MB")
|
| 597 |
+
scorer_executable: Path to compiled scorer, or None for exact match
|
| 598 |
+
|
| 599 |
+
Returns:
|
| 600 |
+
True if all tests passed, False if any test failed.
|
| 601 |
+
|
| 602 |
+
Note:
|
| 603 |
+
Stops on first failure and updates results["status"] accordingly.
|
| 604 |
+
"""
|
| 605 |
+
tally = {"PASSED": 0, "TLE": 0, "MLE": 0, "Wrong Answer": 0, "RTE": 0, "CE": 0}
|
| 606 |
+
|
| 607 |
+
# Parse memory limit
|
| 608 |
+
try:
|
| 609 |
+
bytes_limit = parse_memory_limit_to_bytes(memory_limit)
|
| 610 |
+
except ValueError:
|
| 611 |
+
bytes_limit = None
|
| 612 |
+
|
| 613 |
+
# Compile C++ if needed
|
| 614 |
+
executable = None
|
| 615 |
+
if language == "cpp":
|
| 616 |
+
executable = self._compile_cpp(solution_code, problem.problem_slug)
|
| 617 |
+
if executable is None:
|
| 618 |
+
results["status"] = "Compile Error"
|
| 619 |
+
tally["CE"] += 1
|
| 620 |
+
results[f"{test_type}_summary"] = tally
|
| 621 |
+
return False
|
| 622 |
+
else: # Python - check syntax once before running tests
|
| 623 |
+
try:
|
| 624 |
+
compile(solution_code, "<solution>", "exec")
|
| 625 |
+
except SyntaxError as se:
|
| 626 |
+
results["status"] = "Compile Error"
|
| 627 |
+
results["test_cases"].append({
|
| 628 |
+
"test": f"{test_type}_1",
|
| 629 |
+
"result": "Compile Error",
|
| 630 |
+
"error": str(se)
|
| 631 |
+
})
|
| 632 |
+
tally["CE"] += 1
|
| 633 |
+
results[f"{test_type}_summary"] = tally
|
| 634 |
+
return False
|
| 635 |
+
|
| 636 |
+
# Calculate timeout (time_limit + 5s buffer, capped at 60s)
|
| 637 |
+
timeout = min(60, time_limit + 5)
|
| 638 |
+
|
| 639 |
+
for i, (input_data, expected_output) in enumerate(zip(inputs, outputs)):
|
| 640 |
+
test_name = f"{test_type}_{i+1}"
|
| 641 |
+
|
| 642 |
+
try:
|
| 643 |
+
# Run the solution
|
| 644 |
+
start_time = time.time()
|
| 645 |
+
|
| 646 |
+
if language == "cpp":
|
| 647 |
+
proc = subprocess.run(
|
| 648 |
+
[executable],
|
| 649 |
+
input=input_data, text=True, capture_output=True,
|
| 650 |
+
timeout=timeout,
|
| 651 |
+
preexec_fn=lambda bl=bytes_limit: _preexec_setrlimit_bytes(bl)
|
| 652 |
+
)
|
| 653 |
+
else: # Python
|
| 654 |
+
proc = subprocess.run(
|
| 655 |
+
["python3", "-c", solution_code],
|
| 656 |
+
input=input_data, text=True, capture_output=True,
|
| 657 |
+
timeout=timeout,
|
| 658 |
+
preexec_fn=lambda bl=bytes_limit: _preexec_setrlimit_bytes(bl)
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
execution_time = time.time() - start_time
|
| 662 |
+
generated_output = (proc.stdout or "").strip()
|
| 663 |
+
|
| 664 |
+
# Check for errors
|
| 665 |
+
if proc.returncode == PREEXEC_ERROR_EXIT_CODE:
|
| 666 |
+
raise RuntimeError("preexec_fn failed")
|
| 667 |
+
|
| 668 |
+
if proc.returncode is not None and proc.returncode < 0:
|
| 669 |
+
sig = -proc.returncode
|
| 670 |
+
if sig == signal.SIGKILL:
|
| 671 |
+
raise MemoryError("Killed by SIGKILL (likely OOM)")
|
| 672 |
+
|
| 673 |
+
if proc.returncode == 137:
|
| 674 |
+
raise MemoryError("Exit code 137 (OOM)")
|
| 675 |
+
|
| 676 |
+
if proc.returncode != 0:
|
| 677 |
+
raise RuntimeError(f"Non-zero exit: {proc.returncode}, stderr: {proc.stderr}")
|
| 678 |
+
|
| 679 |
+
# Judge output
|
| 680 |
+
is_correct = self._judge_output(
|
| 681 |
+
problem, input_data, expected_output, generated_output,
|
| 682 |
+
scorer_executable
|
| 683 |
+
)
|
| 684 |
+
|
| 685 |
+
if is_correct:
|
| 686 |
+
results["test_cases"].append({
|
| 687 |
+
"test": test_name,
|
| 688 |
+
"result": "PASSED",
|
| 689 |
+
"time": execution_time,
|
| 690 |
+
})
|
| 691 |
+
tally["PASSED"] += 1
|
| 692 |
+
print(f"✅ {test_name} Passed ({execution_time:.2f}s)")
|
| 693 |
+
else:
|
| 694 |
+
results["status"] = "Wrong Answer"
|
| 695 |
+
results["test_cases"].append({
|
| 696 |
+
"test": test_name,
|
| 697 |
+
"result": "Wrong Answer",
|
| 698 |
+
"time": execution_time,
|
| 699 |
+
"expected": expected_output[:200] + "..." if len(expected_output) > 200 else expected_output,
|
| 700 |
+
"generated": generated_output[:200] + "..." if len(generated_output) > 200 else generated_output,
|
| 701 |
+
})
|
| 702 |
+
tally["Wrong Answer"] += 1
|
| 703 |
+
print(f"❌ {test_name} Wrong Answer")
|
| 704 |
+
results[f"{test_type}_summary"] = tally
|
| 705 |
+
return False
|
| 706 |
+
|
| 707 |
+
except subprocess.TimeoutExpired:
|
| 708 |
+
results["status"] = "Time Limit Exceeded"
|
| 709 |
+
results["test_cases"].append({"test": test_name, "result": "TLE"})
|
| 710 |
+
tally["TLE"] += 1
|
| 711 |
+
print(f"⏳ {test_name} TLE")
|
| 712 |
+
results[f"{test_type}_summary"] = tally
|
| 713 |
+
return False
|
| 714 |
+
|
| 715 |
+
except MemoryError as e:
|
| 716 |
+
results["status"] = "Memory Limit Exceeded"
|
| 717 |
+
results["test_cases"].append({"test": test_name, "result": "MLE", "error": str(e)})
|
| 718 |
+
tally["MLE"] += 1
|
| 719 |
+
print(f"💾 {test_name} MLE")
|
| 720 |
+
results[f"{test_type}_summary"] = tally
|
| 721 |
+
return False
|
| 722 |
+
|
| 723 |
+
except Exception as e:
|
| 724 |
+
results["status"] = "Runtime Error"
|
| 725 |
+
results["test_cases"].append({"test": test_name, "result": "RTE", "error": str(e)})
|
| 726 |
+
tally["RTE"] += 1
|
| 727 |
+
print(f"❌ {test_name} Runtime Error: {e}")
|
| 728 |
+
results[f"{test_type}_summary"] = tally
|
| 729 |
+
return False
|
| 730 |
+
|
| 731 |
+
results[f"{test_type}_summary"] = tally
|
| 732 |
+
return True
|
| 733 |
+
|
| 734 |
+
def _compile_cpp(self, solution_code: str, name: str) -> Optional[str]:
|
| 735 |
+
"""
|
| 736 |
+
Compile a C++ solution to an executable.
|
| 737 |
+
|
| 738 |
+
Args:
|
| 739 |
+
solution_code: C++ source code as a string
|
| 740 |
+
name: Base name for the source file and executable
|
| 741 |
+
|
| 742 |
+
Returns:
|
| 743 |
+
Path to the compiled executable, or None if compilation fails.
|
| 744 |
+
|
| 745 |
+
Note:
|
| 746 |
+
Compiles with: g++ -o <exe> <src> -std=c++17 -O2
|
| 747 |
+
Compilation errors are printed to stdout.
|
| 748 |
+
"""
|
| 749 |
+
tmp_dir = tempfile.mkdtemp()
|
| 750 |
+
cpp_file = os.path.join(tmp_dir, f"{name}.cpp")
|
| 751 |
+
executable = os.path.join(tmp_dir, f"{name}.out")
|
| 752 |
+
|
| 753 |
+
with open(cpp_file, "w") as f:
|
| 754 |
+
f.write(solution_code)
|
| 755 |
+
|
| 756 |
+
result = subprocess.run(
|
| 757 |
+
["g++", "-o", executable, cpp_file, "-std=c++17", "-O2"],
|
| 758 |
+
capture_output=True, text=True
|
| 759 |
+
)
|
| 760 |
+
|
| 761 |
+
if result.returncode != 0:
|
| 762 |
+
print(f"❌ Compile Error:\n{result.stderr}")
|
| 763 |
+
return None
|
| 764 |
+
|
| 765 |
+
return executable
|
| 766 |
+
|
| 767 |
+
def _judge_output(
|
| 768 |
+
self,
|
| 769 |
+
problem: Problem,
|
| 770 |
+
input_data: str,
|
| 771 |
+
expected_output: str,
|
| 772 |
+
generated_output: str,
|
| 773 |
+
scorer_executable: Optional[str],
|
| 774 |
+
) -> bool:
|
| 775 |
+
"""
|
| 776 |
+
Judge whether the generated output is correct.
|
| 777 |
+
|
| 778 |
+
First attempts exact string match (after stripping whitespace).
|
| 779 |
+
If that fails and a special judge is available, uses the scorer.
|
| 780 |
+
|
| 781 |
+
Args:
|
| 782 |
+
problem: The Problem object
|
| 783 |
+
input_data: The input that was given to the solution
|
| 784 |
+
expected_output: The expected output from test case
|
| 785 |
+
generated_output: The output produced by the solution
|
| 786 |
+
scorer_executable: Path to compiled scorer, or None
|
| 787 |
+
|
| 788 |
+
Returns:
|
| 789 |
+
True if the output is correct, False otherwise.
|
| 790 |
+
|
| 791 |
+
Note:
|
| 792 |
+
Special judge formats:
|
| 793 |
+
- "standard": scorer <input> <judge_output> <contestant_output>
|
| 794 |
+
- "jakarta2017": scorer <input> <unused> <judge_output> < contestant_output
|
| 795 |
+
"""
|
| 796 |
+
expected_output = expected_output.strip()
|
| 797 |
+
generated_output = generated_output.strip()
|
| 798 |
+
|
| 799 |
+
# Exact match
|
| 800 |
+
if generated_output == expected_output:
|
| 801 |
+
return True
|
| 802 |
+
|
| 803 |
+
# Use special judge if available
|
| 804 |
+
if scorer_executable and problem.has_special_judge:
|
| 805 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 806 |
+
input_file = os.path.join(tmp_dir, "input.txt")
|
| 807 |
+
expected_file = os.path.join(tmp_dir, "expected.txt")
|
| 808 |
+
generated_file = os.path.join(tmp_dir, "generated.txt")
|
| 809 |
+
|
| 810 |
+
with open(input_file, "w") as f:
|
| 811 |
+
f.write(input_data)
|
| 812 |
+
with open(expected_file, "w") as f:
|
| 813 |
+
f.write(expected_output)
|
| 814 |
+
with open(generated_file, "w") as f:
|
| 815 |
+
f.write(generated_output)
|
| 816 |
+
|
| 817 |
+
if problem.special_judge_format == "jakarta2017":
|
| 818 |
+
# Format: scorer <input> <unused> <judge_output> < contestant_output
|
| 819 |
+
proc = subprocess.run(
|
| 820 |
+
[scorer_executable, input_file, "dummy", expected_file],
|
| 821 |
+
input=generated_output, text=True, capture_output=True
|
| 822 |
+
)
|
| 823 |
+
# Returns nothing for AC, "WA" for wrong
|
| 824 |
+
return "WA" not in proc.stdout and proc.returncode == 0
|
| 825 |
+
else:
|
| 826 |
+
# Standard format: scorer <input> <judge_output> <contestant_output>
|
| 827 |
+
proc = subprocess.run(
|
| 828 |
+
[scorer_executable, input_file, expected_file, generated_file],
|
| 829 |
+
capture_output=True, text=True
|
| 830 |
+
)
|
| 831 |
+
# Check for AC in output or successful return code with no WA
|
| 832 |
+
output = proc.stdout.strip().upper()
|
| 833 |
+
return "AC" in output or (proc.returncode == 0 and "WA" not in output)
|
| 834 |
+
|
| 835 |
+
return False
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
# Convenience function
|
| 839 |
+
def run_solution(problem_id: str, solution_code: str, language: str = "cpp") -> dict:
|
| 840 |
+
"""
|
| 841 |
+
Convenience function to quickly run a solution against a problem.
|
| 842 |
+
|
| 843 |
+
Creates a TestRunner instance, runs the solution, and returns results.
|
| 844 |
+
For running multiple solutions, create a TestRunner instance directly
|
| 845 |
+
to avoid reloading the dataset each time.
|
| 846 |
+
|
| 847 |
+
Args:
|
| 848 |
+
problem_id: The problem ID from the dataset
|
| 849 |
+
solution_code: Solution source code as a string
|
| 850 |
+
language: "cpp" (default) or "Python"
|
| 851 |
+
|
| 852 |
+
Returns:
|
| 853 |
+
dict with status and test results (see TestRunner.run_solution)
|
| 854 |
+
|
| 855 |
+
Example:
|
| 856 |
+
>>> from hf_test_runner import run_solution
|
| 857 |
+
>>> results = run_solution("icpc-jakarta-2019_card-collecting", code)
|
| 858 |
+
>>> print(results["status"])
|
| 859 |
+
"""
|
| 860 |
+
runner = TestRunner()
|
| 861 |
+
return runner.run_solution(problem_id, solution_code, language)
|
| 862 |
+
|
| 863 |
+
|
| 864 |
+
if __name__ == "__main__":
|
| 865 |
+
# Example usage
|
| 866 |
+
runner = TestRunner()
|
| 867 |
+
|
| 868 |
+
# List some problems
|
| 869 |
+
print("\nAvailable problems (first 10):")
|
| 870 |
+
for pid in runner.list_problems()[:10]:
|
| 871 |
+
p = runner.get_problem(pid)
|
| 872 |
+
print(f" {pid}: {p.problem_title}")
|
| 873 |
+
print(f" Sample tests: {len(p.sample_test_cases_input)}, Hidden: {len(p.hidden_test_cases_input)}")
|
| 874 |
+
print(f" Special judge: {p.has_special_judge}, Kattis: {p.uses_kattis}")
|