AdithyaSK HF Staff commited on
Commit
97283bc
·
verified ·
1 Parent(s): 4b1a005

369 validated tasks; grader keeps large builds within the 10 GB disk (part 11)

Browse files

Re-ran the oracle with the updated verifier. The verifier now empties Lake's per-module setup files and generated C once each module is built, and deletes the build before writing its verdict, so a build that fills the disk scores 0 instead of leaving the trial without a result. 14 more tasks validated; not-validated list updated.

Files changed (47) hide show
  1. tasks/infinite-matroid-corollaries/task.toml +1 -1
  2. tasks/infinite-matroid-corollaries/tests/grade.py +67 -5
  3. tasks/interpolated-factors/task.toml +1 -1
  4. tasks/interpolated-factors/tests/grade.py +67 -5
  5. tasks/invariant-ising/environment/Dockerfile +8 -0
  6. tasks/invariant-ising/environment/fetch_mathlib.sh +19 -0
  7. tasks/invariant-ising/environment/lake-manifest.json +116 -0
  8. tasks/invariant-ising/environment/lakefile.lean +12 -0
  9. tasks/invariant-ising/environment/lean_setup.sh +126 -0
  10. tasks/invariant-ising/environment/pack_submission.py +70 -0
  11. tasks/invariant-ising/instruction.md +546 -0
  12. tasks/invariant-ising/solution/closure.txt +0 -0
  13. tasks/invariant-ising/solution/reference.py +58 -0
  14. tasks/invariant-ising/solution/solve.sh +20 -0
  15. tasks/invariant-ising/task.toml +49 -0
  16. tasks/invariant-ising/tests/Challenge.lean +495 -0
  17. tasks/invariant-ising/tests/grade.py +418 -0
  18. tasks/invariant-ising/tests/task.json +25 -0
  19. tasks/invariant-ising/tests/test.sh +3 -0
  20. tasks/irrational-rotation/task.toml +1 -1
  21. tasks/irrational-rotation/tests/grade.py +67 -5
  22. tasks/irrational-triangle-billiard/task.toml +1 -1
  23. tasks/irrational-triangle-billiard/tests/grade.py +67 -5
  24. tasks/ising-finiteness/task.toml +1 -1
  25. tasks/ising-finiteness/tests/grade.py +67 -5
  26. tasks/isometric-immersion/task.toml +1 -1
  27. tasks/isometric-immersion/tests/grade.py +67 -5
  28. tasks/k-median-recovery/task.toml +1 -1
  29. tasks/k-median-recovery/tests/grade.py +67 -5
  30. tasks/k-median-refined-recovery/task.toml +1 -1
  31. tasks/k-median-refined-recovery/tests/grade.py +67 -5
  32. tasks/k-median-threshold/task.toml +1 -1
  33. tasks/k-median-threshold/tests/grade.py +67 -5
  34. tasks/k-server/task.toml +1 -1
  35. tasks/k-server/tests/grade.py +67 -5
  36. tasks/kadison-ringrose/task.toml +1 -1
  37. tasks/kadison-ringrose/tests/grade.py +67 -5
  38. tasks/kadison-similarity/task.toml +1 -1
  39. tasks/kadison-similarity/tests/grade.py +67 -5
  40. tasks/kahler-splitting/task.toml +1 -1
  41. tasks/kahler-splitting/tests/grade.py +67 -5
  42. tasks/kaplansky-direct-finiteness/task.toml +1 -1
  43. tasks/kaplansky-direct-finiteness/tests/grade.py +67 -5
  44. tasks/kaplansky-finitely-presented/task.toml +1 -1
  45. tasks/kaplansky-finitely-presented/tests/grade.py +67 -5
  46. tasks/kaplansky-quasitrace/task.toml +1 -1
  47. tasks/kaplansky-quasitrace/tests/grade.py +67 -5
tasks/infinite-matroid-corollaries/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 33
23
  reference_lean_bytes = 193312
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 637
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 193312
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 155
27
  difficulty = "research"
28
 
29
  [agent]
tasks/infinite-matroid-corollaries/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/interpolated-factors/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 77
23
  reference_lean_bytes = 1249281
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 1971
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 1249281
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 1361
27
  difficulty = "research"
28
 
29
  [agent]
tasks/interpolated-factors/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/invariant-ising/environment/Dockerfile ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Shared by every openai/math task (agent and separate verifier). See lean_setup.sh.
2
+ FROM ubuntu:24.04
3
+ ENV ELAN_HOME=/opt/elan \
4
+ PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
5
+ LANG=C.UTF-8
6
+ COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/
7
+ RUN bash /opt/build/lean_setup.sh
8
+ WORKDIR /workspace
tasks/invariant-ising/environment/fetch_mathlib.sh ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never
3
+ # reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every
4
+ # module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk.
5
+ set -euo pipefail
6
+ cd /opt/lean-env
7
+ trim() {
8
+ find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} +
9
+ rm -rf "${HOME:-/root}/.cache/mathlib"
10
+ }
11
+ for dir in .lake/packages/mathlib/Mathlib/*/; do
12
+ name=$(basename "$dir")
13
+ echo "== Mathlib/$name"
14
+ lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null
15
+ trim
16
+ df -h / | tail -1
17
+ done
18
+ lake exe cache get
19
+ trim
tasks/invariant-ising/environment/lake-manifest.json ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "1.2.0",
3
+ "packagesDir": ".lake/packages",
4
+ "packages": [
5
+ {
6
+ "url": "https://github.com/leanprover-community/mathlib4.git",
7
+ "type": "git",
8
+ "subDir": null,
9
+ "scope": "",
10
+ "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612",
11
+ "name": "mathlib",
12
+ "manifestFile": "lake-manifest.json",
13
+ "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612",
14
+ "inherited": false,
15
+ "configFile": "lakefile.lean"
16
+ },
17
+ {
18
+ "url": "https://github.com/leanprover-community/plausible",
19
+ "type": "git",
20
+ "subDir": null,
21
+ "scope": "leanprover-community",
22
+ "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c",
23
+ "name": "plausible",
24
+ "manifestFile": "lake-manifest.json",
25
+ "inputRev": "main",
26
+ "inherited": true,
27
+ "configFile": "lakefile.toml"
28
+ },
29
+ {
30
+ "url": "https://github.com/leanprover-community/LeanSearchClient",
31
+ "type": "git",
32
+ "subDir": null,
33
+ "scope": "leanprover-community",
34
+ "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707",
35
+ "name": "LeanSearchClient",
36
+ "manifestFile": "lake-manifest.json",
37
+ "inputRev": "main",
38
+ "inherited": true,
39
+ "configFile": "lakefile.toml"
40
+ },
41
+ {
42
+ "url": "https://github.com/leanprover-community/import-graph",
43
+ "type": "git",
44
+ "subDir": null,
45
+ "scope": "leanprover-community",
46
+ "rev": "e928b72544873815af278d38681b31c0293588e3",
47
+ "name": "importGraph",
48
+ "manifestFile": "lake-manifest.json",
49
+ "inputRev": "main",
50
+ "inherited": true,
51
+ "configFile": "lakefile.toml"
52
+ },
53
+ {
54
+ "url": "https://github.com/leanprover-community/ProofWidgets4",
55
+ "type": "git",
56
+ "subDir": null,
57
+ "scope": "leanprover-community",
58
+ "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5",
59
+ "name": "proofwidgets",
60
+ "manifestFile": "lake-manifest.json",
61
+ "inputRev": "main",
62
+ "inherited": true,
63
+ "configFile": "lakefile.lean"
64
+ },
65
+ {
66
+ "url": "https://github.com/leanprover-community/aesop",
67
+ "type": "git",
68
+ "subDir": null,
69
+ "scope": "leanprover-community",
70
+ "rev": "355695d523e41d0554926416cba2a2b3544fbbc9",
71
+ "name": "aesop",
72
+ "manifestFile": "lake-manifest.json",
73
+ "inputRev": "master",
74
+ "inherited": true,
75
+ "configFile": "lakefile.toml"
76
+ },
77
+ {
78
+ "url": "https://github.com/leanprover-community/quote4",
79
+ "type": "git",
80
+ "subDir": null,
81
+ "scope": "leanprover-community",
82
+ "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259",
83
+ "name": "Qq",
84
+ "manifestFile": "lake-manifest.json",
85
+ "inputRev": "master",
86
+ "inherited": true,
87
+ "configFile": "lakefile.toml"
88
+ },
89
+ {
90
+ "url": "https://github.com/leanprover-community/batteries",
91
+ "type": "git",
92
+ "subDir": null,
93
+ "scope": "leanprover-community",
94
+ "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2",
95
+ "name": "batteries",
96
+ "manifestFile": "lake-manifest.json",
97
+ "inputRev": "main",
98
+ "inherited": true,
99
+ "configFile": "lakefile.toml"
100
+ },
101
+ {
102
+ "url": "https://github.com/leanprover/lean4-cli",
103
+ "type": "git",
104
+ "subDir": null,
105
+ "scope": "leanprover",
106
+ "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204",
107
+ "name": "Cli",
108
+ "manifestFile": "lake-manifest.json",
109
+ "inputRev": "v4.34.0",
110
+ "inherited": true,
111
+ "configFile": "lakefile.toml"
112
+ }
113
+ ],
114
+ "name": "openai_math",
115
+ "lakeDir": ".lake"
116
+ }
tasks/invariant-ising/environment/lakefile.lean ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Lake
2
+ open Lake DSL
3
+
4
+ -- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`.
5
+ package openai_math where
6
+ leanOptions := #[⟨`autoImplicit, false⟩]
7
+
8
+ require mathlib from git
9
+ "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612"
10
+
11
+ -- `Submission` and every `Submission.*` module it imports.
12
+ lean_lib Submission
tasks/invariant-ising/environment/lean_setup.sh ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Builds the image shared by every openai/math task, for both the agent and the separate verifier:
3
+ # - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library)
4
+ # - Comparator, lean4export and landrun, used only by the verifier's grade.py
5
+ # - every challenge statement, at /opt/openai-math/challenges/<Name>.lean
6
+ # - /workspace, a Lake project where the agent writes Submission.lean
7
+ # All revisions are pinned. The openai/math library (the reference proofs) is never installed.
8
+ set -euxo pipefail
9
+ export DEBIAN_FRONTEND=noninteractive
10
+
11
+ LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1
12
+ OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a
13
+ COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1
14
+ LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4
15
+ GO_VERSION=1.24.7
16
+
17
+ apt-get update -qq
18
+ apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \
19
+ zstd python3 procps iproute2 iptables tmux >/dev/null
20
+ rm -rf /var/lib/apt/lists/*
21
+ git config --system --add safe.directory '*'
22
+
23
+ export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH
24
+ curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \
25
+ | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path
26
+
27
+ # --- Verifier tools, built before Mathlib so the build trees are gone before the big download ---
28
+ curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz
29
+ GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \
30
+ /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}"
31
+ rm -rf /tmp/go /tmp/gopath /tmp/gocache
32
+
33
+ git clone -q https://github.com/leanprover/comparator.git /tmp/comparator
34
+ (
35
+ cd /tmp/comparator
36
+ git checkout -q "$COMPARATOR_REV"
37
+ # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass
38
+ # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake
39
+ # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds
40
+ # parallelism only and does not affect what is checked.
41
+ sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean
42
+ test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2
43
+ echo "$LEAN_TOOLCHAIN" > lean-toolchain
44
+ lake build lean4export comparator
45
+ install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator
46
+ install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export
47
+ )
48
+ rm -rf /tmp/comparator
49
+
50
+ # --- Lean project with Mathlib ---
51
+ # Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches.
52
+ mkdir -p /opt/lean-env/.lake/packages
53
+ cd /opt/lean-env
54
+ echo "$LEAN_TOOLCHAIN" > lean-toolchain
55
+ cp /opt/build/lakefile.lean /opt/build/lake-manifest.json .
56
+ python3 - <<'PY'
57
+ import json, subprocess
58
+ for p in json.load(open("lake-manifest.json"))["packages"]:
59
+ d = f".lake/packages/{p['name']}"
60
+ subprocess.run(["git", "init", "-q", d], check=True)
61
+ subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True)
62
+ subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True)
63
+ subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True)
64
+ PY
65
+ # Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the
66
+ # static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping
67
+ # them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk.
68
+ lake exe cache --help >/dev/null 2>&1 || true
69
+ find /opt/elan/toolchains/*/lib -name '*.a' -delete
70
+ rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp*
71
+ apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \
72
+ 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true
73
+ apt-get autoremove -y -qq >/dev/null || true
74
+ bash /opt/build/fetch_mathlib.sh
75
+ rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache
76
+
77
+ # --- Challenge statements (public; the reference proofs are not fetched) ---
78
+ git init -q /tmp/oai && cd /tmp/oai
79
+ git remote add origin https://github.com/openai/math.git
80
+ git config core.sparseCheckout true
81
+ echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout
82
+ git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV"
83
+ git checkout -q FETCH_HEAD
84
+ mkdir -p /opt/openai-math/challenges
85
+ cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/
86
+ cd / && rm -rf /tmp/oai
87
+ install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py
88
+
89
+ # --- Agent workspace and the verifier's unprivileged user ---
90
+ mkdir -p /workspace/.lake
91
+ cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/
92
+ ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages
93
+ useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader
94
+ mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade
95
+
96
+ # Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in
97
+ # the image); a second build must compile nothing but Submission, or agents would pay for it.
98
+ cd /workspace
99
+ printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean
100
+ lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true
101
+ echo '-- second build' >> Submission.lean
102
+ lake build Submission 2>&1 | tee /tmp/smoke.log
103
+ if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then
104
+ echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1
105
+ fi
106
+ rm -rf Submission.lean .lake/build /tmp/smoke.log
107
+
108
+ # Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user,
109
+ # so everything must be world-readable (and stays root-owned, so not writable).
110
+ chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math
111
+ # Same smoke test as `grader`, in a scratch project like the one grade.py lays out.
112
+ smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX)
113
+ cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/"
114
+ mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages"
115
+ printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean"
116
+ chmod 0755 "$smoke" && chown grader "$smoke/.lake"
117
+ (cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \
118
+ lake build Submission) 2>&1 | tee /tmp/smoke.log
119
+ if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then
120
+ echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1
121
+ fi
122
+ rm -rf "$smoke" /tmp/smoke.log
123
+
124
+ rm -rf /opt/build /root/.cache
125
+ df -h / | tail -1
126
+ du -sh /opt/elan /opt/lean-env
tasks/invariant-ising/environment/pack_submission.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Pack the agent's proof into one file for the verifier.
3
+
4
+ Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes.
5
+ It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular
6
+ `Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never
7
+ followed, so only one plain file crosses to the verifier sandbox.
8
+
9
+ The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step
10
+ only keeps the transfer small and free of links.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import shutil
17
+ import stat
18
+ import tarfile
19
+ from pathlib import Path
20
+
21
+ WORKSPACE = Path("/workspace")
22
+ OUT_DIR = Path("/logs/artifacts")
23
+ MAX_TOTAL_BYTES = 768 << 20
24
+
25
+
26
+ def clear(directory: Path) -> None:
27
+ directory.mkdir(parents=True, exist_ok=True)
28
+ for entry in directory.iterdir():
29
+ if entry.is_dir() and not entry.is_symlink():
30
+ shutil.rmtree(entry)
31
+ else:
32
+ entry.unlink()
33
+
34
+
35
+ def regular(path: Path) -> bool:
36
+ try:
37
+ return stat.S_ISREG(path.lstat().st_mode)
38
+ except OSError:
39
+ return False
40
+
41
+
42
+ def main() -> None:
43
+ clear(OUT_DIR)
44
+ tmp = OUT_DIR / "submission.tar.part"
45
+ total = 0
46
+ with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar:
47
+ root = WORKSPACE / "Submission.lean"
48
+ if regular(root):
49
+ total += root.lstat().st_size
50
+ if total > MAX_TOTAL_BYTES:
51
+ raise SystemExit("submission exceeds the size limit")
52
+ tar.add(root, arcname="Submission.lean", recursive=False)
53
+ tree = WORKSPACE / "Submission"
54
+ if tree.is_dir() and not tree.is_symlink():
55
+ for dirpath, dirnames, filenames in os.walk(tree, followlinks=False):
56
+ dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()]
57
+ for name in sorted(filenames):
58
+ path = Path(dirpath) / name
59
+ if not name.endswith(".lean") or not regular(path):
60
+ continue
61
+ total += path.lstat().st_size
62
+ if total > MAX_TOTAL_BYTES:
63
+ raise SystemExit("submission exceeds the size limit")
64
+ tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False)
65
+ tmp.rename(OUT_DIR / "submission.tar")
66
+ print(f"packed {total} bytes")
67
+
68
+
69
+ if __name__ == "__main__":
70
+ main()
tasks/invariant-ising/instruction.md ADDED
@@ -0,0 +1,546 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # openai/math challenge `InvariantIsing` (family 234)
2
+
3
+ Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in
4
+ Lean 4, with a proof the Lean kernel accepts.
5
+
6
+ Context: this statement belongs to family 234 of the release, *All-temperature pressure for orthogonally invariant Ising spin glasses*
7
+ (Probability and statistical mechanics). The family as a whole: Gives an exact variational formula for the limiting pressure of orthogonally invariant Ising spin glasses at every fixed temperature, both almost surely and in expectation. The coupling matrix is a Haar-random rotation of a deterministic spectrum converging to a compactly supported law, with extreme eigenvalues converging to its support edges. The zero-field ground-state energy follows as temperature tends to zero.
8
+
9
+ The challenge is `InvariantIsing`, also at `/opt/openai-math/challenges/InvariantIsing.lean`:
10
+
11
+ ```lean
12
+ import Mathlib
13
+
14
+ namespace OAI
15
+
16
+ /-! All-temperature invariant Ising pressure and its magnetic, random-spectral,
17
+ ground-state, and Gaussian-pattern extensions. -/
18
+
19
+ noncomputable section
20
+ open MeasureTheory ProbabilityTheory Filter Set
21
+ open scoped BigOperators Topology Matrix Classical ENNReal
22
+ universe u
23
+ namespace InvariantIsing
24
+
25
+ abbrev Spin (N : ℕ) := Fin N → Bool
26
+
27
+ def spinValue (b : Bool) : ℝ := if b then 1 else -1
28
+
29
+ def logPartition {X : Type*} [Fintype X] (H : X → ℝ) : ℝ :=
30
+ Real.log ((Fintype.card X : ℝ)⁻¹ * ∑ x, Real.exp (H x))
31
+
32
+ def fieldEnergy {N : ℕ} (c : Fin N → ℝ) (σ : Spin N) : ℝ :=
33
+ ∑ i, c i * spinValue (σ i)
34
+
35
+ abbrev Rotation (N : ℕ) :=
36
+ EuclideanSpace ℝ (Fin N) ≃ₗᵢ[ℝ] EuclideanSpace ℝ (Fin N)
37
+
38
+ abbrev Orthogonal (N : ℕ) := Matrix.orthogonalGroup (Fin N) ℝ
39
+
40
+ def spinVector {N : ℕ} (σ : Spin N) : EuclideanSpace ℝ (Fin N) :=
41
+ WithLp.toLp 2 (fun i => spinValue (σ i))
42
+
43
+ def rotatedEnergy {N : ℕ} (eig : Fin N → ℝ) (U : Rotation N) (σ : Spin N) : ℝ :=
44
+ (1 / 2 : ℝ) * ∑ i, eig i * (U (spinVector σ) i) ^ 2
45
+
46
+ def rotatedPressure {N : ℕ} (eig : Fin N → ℝ) (U : Rotation N)
47
+ (c : Fin N → ℝ) : ℝ :=
48
+ (N : ℝ)⁻¹ * logPartition (fun σ => rotatedEnergy eig U σ + fieldEnergy c σ)
49
+
50
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
51
+
52
+ lemma orthogonal_mulVec_norm_sq {N : ℕ} (U : Orthogonal N)
53
+ (v : EuclideanSpace ℝ (Fin N)) :
54
+ ‖WithLp.toLp 2 ((U : Matrix (Fin N) (Fin N) ℝ) *ᵥ v.ofLp)‖ ^ 2 = ‖v‖ ^ 2 := by
55
+ have hU : (U : Matrix (Fin N) (Fin N) ℝ)ᵀ *
56
+ (U : Matrix (Fin N) (Fin N) ℝ) = 1 :=
57
+ (Matrix.mem_orthogonalGroup_iff' (Fin N) ℝ).mp U.property
58
+ rw [EuclideanSpace.real_norm_sq_eq, EuclideanSpace.real_norm_sq_eq]
59
+ simp only [pow_two]
60
+ change ((U : Matrix (Fin N) (Fin N) ℝ) *ᵥ v.ofLp) ⬝ᵥ
61
+ ((U : Matrix (Fin N) (Fin N) ℝ) *ᵥ v.ofLp) = v.ofLp ⬝ᵥ v.ofLp
62
+ rw [← Matrix.dotProduct_transpose_mulVec, Matrix.mulVec_mulVec, hU,
63
+ Matrix.one_mulVec]
64
+
65
+ def matrixRotation {N : ℕ} (U : Orthogonal N) : Rotation N :=
66
+ { ((WithLp.linearEquiv 2 ℝ (Fin N → ℝ)).trans
67
+ (Matrix.UnitaryGroup.toLinearEquiv U)).trans
68
+ (WithLp.linearEquiv 2 ℝ (Fin N → ℝ)).symm with
69
+ norm_map' := fun v => (sq_eq_sq₀ (norm_nonneg _) (norm_nonneg _)).mp
70
+ (orthogonal_mulVec_norm_sq U v) }
71
+
72
+ structure OverlapPath where
73
+ val : ℝ → ℝ
74
+ monotone : Monotone val
75
+ nonneg : ∀ s, 0 ≤ val s
76
+ le_one : ∀ s, val s ≤ 1
77
+
78
+ instance : CoeFun OverlapPath (fun _ => ℝ → ℝ) := ⟨OverlapPath.val⟩
79
+
80
+ def pathMeasure : Measure ℝ := volume.restrict (Ioo (0 : ℝ) 1)
81
+
82
+ def deficit (p : OverlapPath) (r : ℝ) : ℝ :=
83
+ 1 - r - ∫ s, max (p s - r) 0 ∂pathMeasure
84
+
85
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
86
+
87
+ def gaussianOperator (a v : ℝ) (f : ℝ → ℝ) (z : ℝ) : ℝ :=
88
+ if a = 0 then ∫ g, f (z + Real.sqrt v * g) ∂gaussianReal 0 1
89
+ else a⁻¹ * Real.log (∫ g, Real.exp (a * f (z + Real.sqrt v * g)) ∂gaussianReal 0 1)
90
+
91
+ structure FieldStep where
92
+ depth : ℕ
93
+ cut : Fin (depth + 2) → ℝ
94
+ ordered_cut : StrictMono cut
95
+ first : cut 0 = 0
96
+ last : cut (Fin.last (depth + 1)) = 1
97
+ height : Fin (depth + 1) → ℝ
98
+ nonneg : ∀ i, 0 ≤ height i
99
+ ordered_height : Monotone height
100
+
101
+ def fieldFunction (h : FieldStep) (s : ℝ) : ℝ :=
102
+ ∑ i : Fin (h.depth + 1),
103
+ if h.cut i.castSucc < s ∧ s < h.cut i.succ then h.height i else 0
104
+
105
+ def fieldIncrement (h : FieldStep) (i : Fin (h.depth + 1)) : ℝ × ℝ :=
106
+ (h.cut i.castSucc, h.height i -
107
+ if hi : i.val = 0 then 0 else h.height ⟨i.val - 1, by omega⟩)
108
+
109
+ def fieldValue (h : FieldStep) (b : ℝ) : ℝ :=
110
+ ((List.ofFn (fieldIncrement h)).foldr
111
+ (fun av f => gaussianOperator av.1 av.2 f) (fun z => Real.log (Real.cosh z))) b -
112
+ h.height (Fin.last h.depth) / 2
113
+
114
+ def fieldPairing (p : OverlapPath) (h : FieldStep) : ℝ :=
115
+ ∫ s, p s * fieldFunction h s ∂pathMeasure
116
+
117
+ def entropyFunctional (p : OverlapPath) : EReal :=
118
+ ⨆ h : FieldStep, ((fieldValue h 0 + fieldPairing p h / 2 : ℝ) : EReal)
119
+
120
+ def spectralFunctional (R : ℝ → ℝ) (p : OverlapPath) : ℝ :=
121
+ (1 / 2 : ℝ) * ∫ r, R (deficit p r) ∂pathMeasure
122
+
123
+ def variationalFunctional (R : ℝ → ℝ) : EReal :=
124
+ ⨅ p : OverlapPath, entropyFunctional p + (spectralFunctional R p : EReal)
125
+
126
+ def measureResolvent (μ : Measure ℝ) (b : ℝ) : ℝ := ∫ y, 1 / (b - y) ∂μ
127
+
128
+ def measureInverse (μ : Measure ℝ) (e x : ℝ) : ℝ :=
129
+ if h : ∃ b, e < b ∧ measureResolvent μ b = x then h.choose else e
130
+
131
+ def measureR (μ : Measure ℝ) (e x : ℝ) : ℝ :=
132
+ if 0 < x then measureInverse μ e x - 1 / x else ∫ y, y ∂μ
133
+
134
+ def finiteSpectralMeasure {ι : Type*} (ρ eig : ι → ℝ) : Measure ℝ :=
135
+ Measure.sum fun a => ENNReal.ofReal (ρ a) • Measure.dirac (eig a)
136
+
137
+ theorem finiteSpectralMeasure_probability {ι : Type*} [Fintype ι] (ρ eig : ι → ℝ)
138
+ (hρ : ∀ a, 0 ≤ ρ a) (hsum : ∑ a, ρ a = 1) :
139
+ IsProbabilityMeasure (finiteSpectralMeasure ρ eig) := by
140
+ apply HasSum.isProbabilityMeasure_sum_dirac hρ
141
+ simpa only [hsum] using hasSum_fintype ρ
142
+
143
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
144
+
145
+ lemma empiricalSpectralWeight_sum {N : ℕ} (hN : 0 < N) :
146
+ ∑ _i : Fin N, (1 : ℝ)/N=1 := by
147
+ simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul]
148
+ field_simp
149
+
150
+ def empiricalSpectralLaw {N : ℕ} (hN : 0 < N) (eig : Fin N → ℝ) : ProbabilityMeasure ℝ :=
151
+ ⟨finiteSpectralMeasure (fun _ => (1 : ℝ)/N) eig,
152
+ finiteSpectralMeasure_probability _ _ (fun _ => by positivity) (empiricalSpectralWeight_sum hN)⟩
153
+
154
+ def spectralMinimum {n : ℕ} (eig : Fin (n+1) → ℝ) : ℝ :=
155
+ (Finset.univ.image eig).min' (Finset.image_nonempty.mpr Finset.univ_nonempty)
156
+
157
+ def spectralMaximum {n : ℕ} (eig : Fin (n+1) → ℝ) : ℝ :=
158
+ (Finset.univ.image eig).max' (Finset.image_nonempty.mpr Finset.univ_nonempty)
159
+
160
+ def magneticBiasObjective (h : FieldStep) (s b : ℝ) : ℝ := fieldValue h b - b * s
161
+
162
+ def constrainedFieldValue (h : FieldStep) (s : ℝ) : ℝ :=
163
+ sInf (range (magneticBiasObjective h s))
164
+
165
+ def magneticGroupValue {A : Type*} [Fintype A] (γ m : A → ℝ) (h : FieldStep) : ℝ :=
166
+ ∑ a, γ a * constrainedFieldValue h (m a)
167
+
168
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
169
+
170
+ def magneticEntropyFunctional {A : Type*} [Fintype A] (γ m : A → ℝ)
171
+ (p : OverlapPath) : EReal :=
172
+ ⨆ h : FieldStep, ((magneticGroupValue γ m h + fieldPairing p h / 2 : ℝ) : EReal)
173
+
174
+ def magneticVariationalFunctional {A : Type*} [Fintype A] (R : ℝ → ℝ) (γ m : A → ℝ) : EReal :=
175
+ ⨅ p : OverlapPath, magneticEntropyFunctional γ m p + (spectralFunctional R p : EReal)
176
+
177
+ def RationalMagnetization (A : Type*) := {m : A → ℚ // ∀ a, |(m a : ℝ)| < 1}
178
+
179
+ def finiteMagneticFunctional {A : Type*} [Fintype A] (R : ℝ → ℝ) (γ c : A → ℝ) : EReal :=
180
+ ⨆ m : RationalMagnetization A,
181
+ ((∑ a, γ a * c a * (m.val a : ℝ) : ℝ) : EReal) +
182
+ magneticVariationalFunctional R γ (fun a => (m.val a : ℝ))
183
+
184
+ def finiteIndexWeight {Ω A : Type*} [MeasurableSpace Ω]
185
+ (P : Measure Ω) (g : Ω → A) (a : A) : ℝ := P.real (g ⁻¹' {a})
186
+
187
+ def simpleFieldIndex {Ω : Type*} [MeasurableSpace Ω] (s : SimpleFunc Ω ℝ) (x : Ω) : s.range :=
188
+ ⟨s x,s.mem_range_self x⟩
189
+
190
+ def simpleFieldWeight {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) (s : SimpleFunc Ω ℝ) :=
191
+ finiteIndexWeight P (simpleFieldIndex s)
192
+
193
+ abbrev SimpleFieldPositive {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) (s : SimpleFunc Ω ℝ) :=
194
+ {i : s.range // 0 < simpleFieldWeight P s i}
195
+
196
+ def simpleFieldValue {Ω : Type*} [MeasurableSpace Ω]
197
+ (P : Measure Ω) [IsProbabilityMeasure P] (s : SimpleFunc Ω ℝ) (R : ℝ → ℝ) : ℝ :=
198
+ (finiteMagneticFunctional R (fun i : SimpleFieldPositive P s => simpleFieldWeight P s i)
199
+ (fun i => i.val.val)).toReal
200
+
201
+ def fieldSimpleApproximation (n : ℕ) : SimpleFunc ℝ ℝ :=
202
+ SimpleFunc.approxOn id measurable_id (range (id : ℝ → ℝ) ∪ {0}) 0 (by simp) n
203
+
204
+ def magneticFieldFunctional (spectral : Measure ℝ) (edge : ℝ) (field : ProbabilityMeasure ℝ) : ℝ :=
205
+ limUnder atTop (fun n => simpleFieldValue (field : Measure ℝ) (fieldSimpleApproximation n)
206
+ (measureR spectral edge))
207
+
208
+ structure FieldLawCoupling (μ ν : ProbabilityMeasure ℝ) where
209
+ law : ProbabilityMeasure (ℝ × ℝ)
210
+ fst : (law : Measure (ℝ × ℝ)).map Prod.fst = (μ : Measure ℝ)
211
+ snd : (law : Measure (ℝ × ℝ)).map Prod.snd = (ν : Measure ℝ)
212
+
213
+ def FieldLawCoupling.cost {μ ν : ProbabilityMeasure ℝ} (p : FieldLawCoupling μ ν) : ℝ≥0∞ :=
214
+ ∫⁻ xy, ENNReal.ofReal |xy.1-xy.2| ∂(p.law : Measure (ℝ × ℝ))
215
+
216
+ def fieldWassersteinOne (μ ν : ProbabilityMeasure ℝ) : ℝ≥0∞ :=
217
+ ⨅ p : FieldLawCoupling μ ν, p.cost
218
+
219
+ def scaledSpectralLaw (ν : ProbabilityMeasure ℝ) (β : ℝ) : ProbabilityMeasure ℝ :=
220
+ ν.map (fun x => β*x)
221
+
222
+ def groundStateEnergy {N : ℕ} (eig : Fin N → ℝ) (U : Rotation N) : ℝ :=
223
+ (N : ℝ)⁻¹ * Finset.univ.sup' Finset.univ_nonempty (rotatedEnergy eig U)
224
+
225
+ def thermalVariationalValue (ν : ProbabilityMeasure ℝ) (b β : ℝ) : ℝ :=
226
+ (variationalFunctional (measureR (scaledSpectralLaw ν β : Measure ℝ) (β*b))).toReal/β
227
+
228
+ abbrev FieldSpectralData (N : ℕ) := (Fin N → ℝ) × (Fin N → ℝ)
229
+
230
+ def dataPhysicalPressure {N : ℕ} (d : FieldSpectralData N) (U : Orthogonal N) : ℝ :=
231
+ rotatedPressure d.1 (matrixRotation U⁻¹) d.2
232
+
233
+ def ConditionalFieldOrbitLaw {Ω : Type*} [MeasurableSpace Ω] {N : ℕ}
234
+ (P : Measure Ω) (d : Ω → FieldSpectralData N) (pressure : Ω → ℝ)
235
+ (H : Measure (Orthogonal N)) : Prop :=
236
+ P.map (fun ω => (d ω,pressure ω)) =
237
+ ((P.map d).prod H).map (fun z => (z.1,dataPhysicalPressure z.1 z.2))
238
+
239
+ def spectralExcess {N : ℕ} (eig : Fin N → ℝ) (a b : ℝ) : ℝ :=
240
+ (insert 0 (Finset.univ.image (fun i => max (a-eig i) (eig i-b)))).max'
241
+ (Finset.insert_nonempty 0 _)
242
+
243
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
244
+
245
+ @[irreducible] def gaussianPatternCount (α : ℝ) (N : ℕ) : ℕ := ⌊α*N⌋₊
246
+
247
+ def marchenkoPasturA (α : ℝ) : ℝ := (1-Real.sqrt α)^2
248
+
249
+ def marchenkoPasturB (α : ℝ) : ℝ := (1+Real.sqrt α)^2
250
+
251
+ def marchenkoPasturLower (α : ℝ) : ℝ := if α ≤ 1 then 0 else marchenkoPasturA α
252
+
253
+ def marchenkoPasturMeasure (α : ℝ) : Measure ℝ :=
254
+ ENNReal.ofReal (max (1-α) 0) • Measure.dirac 0 +
255
+ volume.withDensity ((Icc (marchenkoPasturA α) (marchenkoPasturB α)).indicator
256
+ (fun x => ENNReal.ofReal
257
+ (Real.sqrt ((marchenkoPasturB α-x)*(x-marchenkoPasturA α))/(2*Real.pi*x))))
258
+
259
+ def gaussianPatternLimit (α c : ℝ) : ℝ :=
260
+ (variationalFunctional (measureR ((marchenkoPasturMeasure α).map (fun x => c*x))
261
+ (max (c*marchenkoPasturLower α) (c*marchenkoPasturB α)))).toReal
262
+
263
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
264
+
265
+ def gaussianPatternArray {N m : ℕ} (z : EuclideanSpace ℝ (Fin N × Fin m)) :
266
+ Matrix (Fin N) (Fin m) ℝ := fun i j => z (i,j)
267
+
268
+ def gaussianPatternSum {N m : ℕ} (z : EuclideanSpace ℝ (Fin N × Fin m)) (σ : Spin N) :
269
+ EuclideanSpace ℝ (Fin m) :=
270
+ WithLp.toLp 2 ((gaussianPatternArray z)ᵀ *ᵥ (fun i => spinValue (σ i)))
271
+
272
+ def gaussianPatternPressure {N m : ℕ} (c : ℝ)
273
+ (z : EuclideanSpace ℝ (Fin N × Fin m)) : ℝ :=
274
+ (N : ℝ)⁻¹*logPartition (fun σ : Spin N => c/(2*N)*‖gaussianPatternSum z σ‖^2)
275
+
276
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
277
+
278
+ def gaussianPatternGroundEnergy {N m : ℕ} (ε : ℝ)
279
+ (z : EuclideanSpace ℝ (Fin N × Fin m)) : ℝ :=
280
+ (N : ℝ)⁻¹*Finset.univ.sup' Finset.univ_nonempty
281
+ (fun σ : Spin N => ε/(2*N)*‖gaussianPatternSum z σ‖^2)
282
+
283
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
284
+
285
+ def gaussianPatternColumn {N m : ℕ} (z : EuclideanSpace ℝ (Fin N × Fin m))
286
+ (i : Fin N) : EuclideanSpace ℝ (Fin m) := WithLp.toLp 2 (fun j => z (i,j))
287
+
288
+ def gaussianPatternOperator {N m : ℕ} (z : EuclideanSpace ℝ (Fin N × Fin m)) :
289
+ (Fin N → ℝ) →L[ℝ] EuclideanSpace ℝ (Fin m) :=
290
+ (PiLp.continuousLinearEquiv 2 ℝ (fun _ : Fin m => ℝ)).symm.toContinuousLinearMap.comp
291
+ ((gaussianPatternArray z)ᵀ.mulVecLin.toContinuousLinearMap)
292
+
293
+ theorem limiting_pressure_of_extreme_limits_unconditional :
294
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
295
+ (U : (N : ℕ) → Ω → Orthogonal N) (_hU : ∀ N, Measurable (U N))
296
+ (_hHaar : ∀ N, (P.map (U N)).IsMulRightInvariant)
297
+ (eig : (N : ℕ) → Fin N → ℝ) (ν : ProbabilityMeasure ℝ) (a b : ℝ)
298
+ (_hcompact : IsCompact (ν : Measure ℝ).support)
299
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
300
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
301
+ (_hmin : Tendsto (fun k => spectralMinimum (eig (k+1))) atTop (𝓝 a))
302
+ (_hmax : Tendsto (fun k => spectralMaximum (eig (k+1))) atTop (𝓝 b))
303
+ (_hweak : Tendsto (fun k => empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1)))
304
+ atTop (𝓝 ν)),
305
+ Tendsto (fun N => ∫ ω, rotatedPressure (eig N) (matrixRotation (U N ω)⁻¹) (fun _ => 0) ∂P)
306
+ atTop (𝓝 (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) ∧
307
+ ∀ᵐ ω ∂P, Tendsto (fun N => rotatedPressure (eig N) (matrixRotation (U N ω)⁻¹) (fun _ => 0))
308
+ atTop (𝓝 (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) := by
309
+ sorry
310
+
311
+ theorem limiting_wasserstein_field_pressure_of_extreme_limits_unconditional :
312
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
313
+ (U : (N : ℕ) → Ω → Orthogonal N) (_hU : ∀ N, Measurable (U N))
314
+ (_hHaar : ∀ N, (P.map (U N)).IsMulRightInvariant)
315
+ (eig : (N : ℕ) → Fin N → ℝ) (ν : ProbabilityMeasure ℝ) (a b : ℝ)
316
+ (_hcompact : IsCompact (ν : Measure ℝ).support)
317
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
318
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
319
+ (_hmin : Tendsto (fun k => spectralMinimum (eig (k+1))) atTop (𝓝 a))
320
+ (_hmax : Tendsto (fun k => spectralMaximum (eig (k+1))) atTop (𝓝 b))
321
+ (_hweak : Tendsto (fun k => empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1)))
322
+ atTop (𝓝 ν))
323
+ (field : (N : ℕ) → Fin N → ℝ) (ξ : ProbabilityMeasure ℝ)
324
+ (_hξ : Integrable (fun x : ℝ => x) (ξ : Measure ℝ))
325
+ (_hw : Tendsto (fun k => fieldWassersteinOne (empiricalSpectralLaw (Nat.succ_pos k) (field (k+1))) ξ)
326
+ atTop (𝓝 0)),
327
+ Tendsto (fun N => ∫ ω, rotatedPressure (eig N) (matrixRotation (U N ω)⁻¹) (field N) ∂P)
328
+ atTop (𝓝 (magneticFieldFunctional (ν : Measure ℝ) b ξ)) ∧
329
+ ∀ᵐ ω ∂P, Tendsto (fun N => rotatedPressure (eig N) (matrixRotation (U N ω)⁻¹) (field N))
330
+ atTop (𝓝 (magneticFieldFunctional (ν : Measure ℝ) b ξ)) := by
331
+ sorry
332
+
333
+ theorem positive_temperature_pressure_unconditional :
334
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
335
+ (U : (N : ℕ) → Ω → Orthogonal N) (_hU : ∀ N, Measurable (U N))
336
+ (_hHaar : ∀ N, (P.map (U N)).IsMulRightInvariant)
337
+ (eig : (N : ℕ) → Fin N → ℝ) (ν : ProbabilityMeasure ℝ) (a b : ℝ)
338
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
339
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
340
+ (_hno : ∀ ε : ℝ, 0 < ε → ∀ᶠ N in atTop, ∀ i, a-ε ≤ eig N i ∧ eig N i ≤ b+ε)
341
+ (β : ℝ) (_hβ : 0 < β)
342
+ (_hweak : Tendsto (fun k => empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1)))
343
+ atTop (𝓝 ν)),
344
+ Tendsto (fun N => ∫ ω, rotatedPressure (fun i => β*eig N i) (matrixRotation (U N ω)⁻¹) (fun _ => 0) ∂P)
345
+ atTop (𝓝 (variationalFunctional (measureR (scaledSpectralLaw ν β : Measure ℝ) (β*b))).toReal) ∧
346
+ ∀ᵐ ω ∂P, Tendsto (fun N => rotatedPressure (fun i => β*eig N i) (matrixRotation (U N ω)⁻¹) (fun _ => 0))
347
+ atTop (𝓝 (variationalFunctional (measureR (scaledSpectralLaw ν β : Measure ℝ) (β*b))).toReal) := by
348
+ sorry
349
+
350
+ theorem ground_state_limit_unconditional :
351
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
352
+ (U : (N : ℕ) → Ω → Orthogonal N) (_hU : ∀ N, Measurable (U N))
353
+ (_hHaar : ∀ N, (P.map (U N)).IsMulRightInvariant)
354
+ (eig : (N : ℕ) → Fin N → ℝ) (ν : ProbabilityMeasure ℝ) (a b : ℝ)
355
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
356
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
357
+ (_hno : ∀ ε : ℝ, 0 < ε → ∀ᶠ N in atTop, ∀ i, a-ε ≤ eig N i ∧ eig N i ≤ b+ε)
358
+ (_hweak : Tendsto (fun k => empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1)))
359
+ atTop (𝓝 ν)),
360
+ ∃ M : ℝ,
361
+ Tendsto (fun N => ∫ ω, groundStateEnergy (eig N) (matrixRotation (U N ω)⁻¹) ∂P)
362
+ atTop (𝓝 M) ∧
363
+ (∀ᵐ ω ∂P, Tendsto (fun N => groundStateEnergy (eig N) (matrixRotation (U N ω)⁻¹))
364
+ atTop (𝓝 M)) ∧
365
+ Tendsto (thermalVariationalValue ν b) atTop (𝓝 M) := by
366
+ sorry
367
+
368
+ theorem random_pressure_tendsto_in_measure_unconditional
369
+ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
370
+ (eig : (N : ℕ) → Ω → Fin N → ℝ) (Y : ℕ → Ω → ℝ)
371
+ (heig : ∀ N, Measurable (eig N)) (hY : ∀ N, Measurable (Y N))
372
+ (H : (N : ℕ) → Measure (Orthogonal N)) [∀ N, IsProbabilityMeasure (H N)]
373
+ [∀ N, (H N).IsMulRightInvariant]
374
+ (hlaw : ∀ N, ConditionalFieldOrbitLaw P (fun ω => (eig N ω,fun _ => 0)) (Y N) (H N))
375
+ (ν : ProbabilityMeasure ℝ) (a b : ℝ)
376
+ (hcompact : IsCompact (ν : Measure ℝ).support)
377
+ (hbound : (ν : Measure ℝ).support ⊆ Icc a b)
378
+ (ha : a∈(ν : Measure ℝ).support) (hb : b∈(ν : Measure ℝ).support)
379
+ (hweak : TendstoInMeasure P (fun k ω => LevyProkhorov.ofMeasure
380
+ (empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1) ω))) atTop
381
+ (fun _ => LevyProkhorov.ofMeasure ν))
382
+ (hexcess : TendstoInMeasure P (fun k ω => spectralExcess (eig (k+1) ω) a b)
383
+ atTop (fun _ => 0)) :
384
+ TendstoInMeasure P (fun k => Y (k+1)) atTop
385
+ (fun _ => (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) := by
386
+ sorry
387
+
388
+ theorem random_pressure_limit_unconditional :
389
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
390
+ (eig : (N : ℕ) → Ω → Fin N → ℝ) (Y : ℕ → Ω → ℝ)
391
+ (_heig : ∀ N, Measurable (eig N)) (_hY : ∀ N, Measurable (Y N))
392
+ (H : (N : ℕ) → Measure (Orthogonal N)) [∀ N, IsProbabilityMeasure (H N)]
393
+ [∀ N, (H N).IsMulRightInvariant]
394
+ (_hlaw : ∀ N, ConditionalFieldOrbitLaw P (fun ω => (eig N ω,fun _ => 0)) (Y N) (H N))
395
+ (ν : ProbabilityMeasure ℝ) (a b : ℝ)
396
+ (_hcompact : IsCompact (ν : Measure ℝ).support)
397
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
398
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
399
+ (_hweak : TendstoInMeasure P (fun k ω => LevyProkhorov.ofMeasure
400
+ (empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1) ω))) atTop
401
+ (fun _ => LevyProkhorov.ofMeasure ν))
402
+ (_hexcess : TendstoInMeasure P (fun k ω => spectralExcess (eig (k+1) ω) a b)
403
+ atTop (fun _ => 0))
404
+ (_hUI : UniformIntegrable (fun k => Y (k+1)) 1 P),
405
+ TendstoInMeasure P (fun k => Y (k+1)) atTop
406
+ (fun _ => (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) ∧
407
+ Tendsto (fun k => eLpNorm (fun ω => Y (k+1) ω-
408
+ (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) 1 P) atTop (𝓝 0) ∧
409
+ Tendsto (fun k => ∫ ω, Y (k+1) ω ∂P) atTop
410
+ (𝓝 (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) := by
411
+ sorry
412
+
413
+ theorem random_pressure_tendsto_ae_unconditional :
414
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
415
+ (eig : (N : ℕ) → Ω → Fin N → ℝ) (Y : ℕ → Ω → ℝ)
416
+ (_heig : ∀ N, Measurable (eig N)) (_hY : ∀ N, Measurable (Y N))
417
+ (H : (N : ℕ) → Measure (Orthogonal N)) [∀ N, IsProbabilityMeasure (H N)]
418
+ [∀ N, (H N).IsMulRightInvariant]
419
+ (_hlaw : ∀ N, ConditionalFieldOrbitLaw P (fun ω => (eig N ω,fun _ => 0)) (Y N) (H N))
420
+ (ν : ProbabilityMeasure ℝ) (a b : ℝ)
421
+ (_hcompact : IsCompact (ν : Measure ℝ).support)
422
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
423
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
424
+ (_hno : ∀ᵐ ω ∂P, ∀ ε : ℝ, 0 < ε → ∀ᶠ N in atTop,
425
+ ∀ i, a-ε ≤ eig N ω i ∧ eig N ω i ≤ b+ε)
426
+ (_hweak : ∀ᵐ ω ∂P, Tendsto (fun k =>
427
+ empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1) ω)) atTop (𝓝 ν)),
428
+ ∀ᵐ ω ∂P, Tendsto (fun N => Y N ω) atTop
429
+ (𝓝 (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) := by
430
+ sorry
431
+
432
+ theorem random_field_pressure_tendsto_ae_unconditional :
433
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
434
+ (d : (N : ℕ) → Ω → FieldSpectralData N) (Y : ℕ → Ω → ℝ)
435
+ (_hd : ∀ N, Measurable (d N)) (_hY : ∀ N, Measurable (Y N))
436
+ (H : (N : ℕ) → Measure (Orthogonal N)) [∀ N, IsProbabilityMeasure (H N)]
437
+ [∀ N, (H N).IsMulRightInvariant]
438
+ (_hlaw : ∀ N, ConditionalFieldOrbitLaw P (d N) (Y N) (H N))
439
+ (ν : ProbabilityMeasure ℝ) (a b : ℝ)
440
+ (_hcompact : IsCompact (ν : Measure ℝ).support)
441
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
442
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
443
+ (_hno : ∀ᵐ ω ∂P, ∀ ε : ℝ, 0 < ε → ∀ᶠ N in atTop,
444
+ ∀ i, a-ε ≤ (d N ω).1 i ∧ (d N ω).1 i ≤ b+ε)
445
+ (_hweak : ∀ᵐ ω ∂P, Tendsto (fun k =>
446
+ empiricalSpectralLaw (Nat.succ_pos k) (d (k+1) ω).1) atTop (𝓝 ν))
447
+ (ξ : ProbabilityMeasure ℝ) (_hξ : Integrable (fun x : ℝ => x) (ξ : Measure ℝ))
448
+ (_hw : ∀ᵐ ω ∂P, Tendsto (fun k => fieldWassersteinOne
449
+ (empiricalSpectralLaw (Nat.succ_pos k) (d (k+1) ω).2) ξ) atTop (𝓝 0)),
450
+ ∀ᵐ ω ∂P, Tendsto (fun N => Y N ω) atTop
451
+ (𝓝 (magneticFieldFunctional (ν : Measure ℝ) b ξ)) := by
452
+ sorry
453
+
454
+ theorem gaussianPattern_pressure_limit_unconditional :
455
+ ∀ (α : ℝ) (_hα : 0 < α)
456
+ {Ω : Type u} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
457
+ (Z : (N : ℕ) → Ω → EuclideanSpace ℝ (Fin N × Fin (gaussianPatternCount α N)))
458
+ (_hZ : ∀ N, Measurable (Z N)) (_hlaw : ∀ N, HasLaw (Z N) (stdGaussian _) P)
459
+ (c : ℝ),
460
+ TendstoInMeasure P (fun k ω => gaussianPatternPressure (N := k+1) (m := gaussianPatternCount α (k+1)) c (Z (k+1) ω)) atTop
461
+ (fun _ => gaussianPatternLimit α c) ∧
462
+ Tendsto (fun k => eLpNorm (fun ω => gaussianPatternPressure (N := k+1) (m := gaussianPatternCount α (k+1)) c (Z (k+1) ω)-
463
+ gaussianPatternLimit α c) 1 P) atTop (𝓝 0) ∧
464
+ Tendsto (fun k => ∫ ω, gaussianPatternPressure (N := k+1) (m := gaussianPatternCount α (k+1)) c (Z (k+1) ω) ∂P) atTop
465
+ (𝓝 (gaussianPatternLimit α c)) := by
466
+ sorry
467
+
468
+ theorem gaussianPattern_ground_limit_unconditional :
469
+ ∀ (α : ℝ) (_hα : 0 < α)
470
+ {Ω : Type u} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
471
+ (Z : (N : ℕ) → Ω → EuclideanSpace ℝ (Fin N × Fin (gaussianPatternCount α N)))
472
+ (_hZ : ∀ N, Measurable (Z N)) (_hlaw : ∀ N, HasLaw (Z N) (stdGaussian _) P)
473
+ (ε : ℝ),
474
+ ∃ e : ℝ,
475
+ TendstoInMeasure P (fun k ω => gaussianPatternGroundEnergy ε (Z (k+1) ω)) atTop (fun _ => e) ∧
476
+ Tendsto (fun k => eLpNorm (fun ω => gaussianPatternGroundEnergy ε (Z (k+1) ω)-e) 1 P)
477
+ atTop (𝓝 0) ∧
478
+ Tendsto (fun k => ∫ ω, gaussianPatternGroundEnergy ε (Z (k+1) ω) ∂P) atTop (𝓝 e) ∧
479
+ Tendsto (fun β => gaussianPatternLimit α (ε*β)/β) atTop (𝓝 e) := by
480
+ sorry
481
+
482
+ theorem gaussianPattern_norm_limits_unconditional :
483
+ ∀ (α : ���) (_hα : 0 < α)
484
+ {Ω : Type u} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
485
+ (Z : (N : ℕ) → Ω → EuclideanSpace ℝ (Fin N × Fin (gaussianPatternCount α N)))
486
+ (_hZ : ∀ N, Measurable (Z N)) (_hlaw : ∀ N, HasLaw (Z N) (stdGaussian _) P),
487
+ ∃ eplus eminus : ℝ, 0 ≤ eplus ∧ eminus ≤ 0 ∧
488
+ Tendsto (fun β => gaussianPatternLimit α β/β) atTop (𝓝 eplus) ∧
489
+ Tendsto (fun β => gaussianPatternLimit α (-β)/β) atTop (𝓝 eminus) ∧
490
+ (TendstoInMeasure P (fun k ω => ‖gaussianPatternOperator (Z (k+1) ω)‖/(k+1)) atTop
491
+ (fun _ => Real.sqrt (2*eplus)) ∧
492
+ Tendsto (fun k => eLpNorm (fun ω => ‖gaussianPatternOperator (Z (k+1) ω)‖/(k+1)-
493
+ Real.sqrt (2*eplus)) 1 P) atTop (𝓝 0)) ∧
494
+ (TendstoInMeasure P (fun k ω =>
495
+ (Finset.univ.inf' Finset.univ_nonempty (fun σ : Spin (k+1) => ‖gaussianPatternSum (Z (k+1) ω) σ‖))/(k+1))
496
+ atTop (fun _ => Real.sqrt (-2*eminus)) ∧
497
+ Tendsto (fun k => eLpNorm (fun ω =>
498
+ (Finset.univ.inf' Finset.univ_nonempty (fun σ : Spin (k+1) => ‖gaussianPatternSum (Z (k+1) ω) σ‖))/(k+1)-
499
+ Real.sqrt (-2*eminus)) 1 P) atTop (𝓝 0)) := by
500
+ sorry
501
+
502
+ end InvariantIsing
503
+
504
+ end
505
+
506
+ end OAI
507
+ ```
508
+
509
+ ## What to submit
510
+
511
+ Write `/workspace/Submission.lean`. Start from a copy of the challenge:
512
+
513
+ ```bash
514
+ cp /opt/openai-math/challenges/InvariantIsing.lean /workspace/Submission.lean
515
+ ```
516
+
517
+ then replace every `sorry` with a proof. The file is graded on three things:
518
+
519
+ - **Same statements.** The theorems `OAI.InvariantIsing.limiting_pressure_of_extreme_limits_unconditional`, `OAI.InvariantIsing.limiting_wasserstein_field_pressure_of_extreme_limits_unconditional`, `OAI.InvariantIsing.positive_temperature_pressure_unconditional`, `OAI.InvariantIsing.ground_state_limit_unconditional`, `OAI.InvariantIsing.random_pressure_tendsto_in_measure_unconditional`, `OAI.InvariantIsing.random_pressure_limit_unconditional`, `OAI.InvariantIsing.random_pressure_tendsto_ae_unconditional`, `OAI.InvariantIsing.random_field_pressure_tendsto_ae_unconditional`, `OAI.InvariantIsing.gaussianPattern_pressure_limit_unconditional`, `OAI.InvariantIsing.gaussianPattern_ground_limit_unconditional`, `OAI.InvariantIsing.gaussianPattern_norm_limits_unconditional` must keep exactly the statement shown above: same names,
520
+ namespaces, binders and types. Every definition the statements use must stay exactly as written.
521
+ Change nothing except the proofs.
522
+ - **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`.
523
+ `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected.
524
+ - **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the
525
+ definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added
526
+ before them can change how they elaborate, and then they no longer match the challenge.
527
+ - **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator.
528
+
529
+ Long proofs can be split into modules under `/workspace/Submission/` (module names
530
+ `Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at
531
+ those two paths are graded.
532
+
533
+ ## Environment
534
+
535
+ - Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a
536
+ Lake project.
537
+ - The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three
538
+ parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms <name>` to see
539
+ which axioms a proof uses.
540
+ - There is no internet access. OpenAI's own proofs are not installed.
541
+
542
+ ## Grading
543
+
544
+ When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and
545
+ checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker.
546
+ The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0.
tasks/invariant-ising/solution/closure.txt ADDED
The diff for this file is too large to render. See raw diff
 
tasks/invariant-ising/solution/reference.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Place openai/math's reference proof as a submission (used by the oracle's solve.sh).
3
+
4
+ Standalone: the adapter copies this file into every task's solution/ directory.
5
+
6
+ reference.py <openai-math lean dir> <closure.txt> <solution module> <workspace>
7
+
8
+ Each module in closure.txt (``OAI.A.B``) is copied from ``<lean>/OAI/A/B.lean`` to
9
+ ``<workspace>/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to
10
+ ``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names
11
+ are namespaces, not module paths, so the theorems keep the names the challenge expects.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ _IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))")
21
+ _HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)")
22
+
23
+
24
+ def rename_imports(text: str) -> str:
25
+ """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only."""
26
+ out, in_header, in_comment = [], True, False
27
+ for line in text.splitlines(keepends=True):
28
+ if in_header:
29
+ stripped = line.strip()
30
+ if in_comment:
31
+ in_comment = "-/" not in stripped
32
+ elif stripped.startswith("/-"):
33
+ in_comment = "-/" not in stripped[2:]
34
+ elif _IMPORT.match(line):
35
+ line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1)
36
+ elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line):
37
+ in_header = False
38
+ out.append(line)
39
+ return "".join(out)
40
+
41
+
42
+ def module_path(root: Path, module: str) -> Path:
43
+ return root.joinpath(*module.split(".")).with_suffix(".lean")
44
+
45
+
46
+ def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None:
47
+ for module in modules:
48
+ dst = module_path(workspace / "Submission", module)
49
+ dst.parent.mkdir(parents=True, exist_ok=True)
50
+ dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8")
51
+ (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8")
52
+
53
+
54
+ if __name__ == "__main__":
55
+ lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5]
56
+ modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()]
57
+ place(Path(lean_dir), modules, solution_module, Path(workspace))
58
+ print(f"placed {len(modules)} reference modules for {solution_module}")
tasks/invariant-ising/solution/solve.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Oracle: submit openai/math's own proof of InvariantIsing, i.e. module OAI.Probability.InvariantIsing.Unconditional and the
3
+ # 2123 OAI modules it imports, placed under Submission/ (see reference.py).
4
+ set -euo pipefail
5
+ if [ -f /solution/reference.tar.gz ]; then
6
+ tar -xzf /solution/reference.tar.gz -C /workspace
7
+ else
8
+ # Fetch only those files at the pinned commit. The task blocks the network while the agent runs,
9
+ # so run the oracle with `harbor run ... --allow-agent-host github.com`.
10
+ tmp=$(mktemp -d)
11
+ git -C "$tmp" init -q
12
+ git -C "$tmp" remote add origin https://github.com/openai/math.git
13
+ git -C "$tmp" config core.sparseCheckout true
14
+ sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout"
15
+ git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a
16
+ git -C "$tmp" checkout -q FETCH_HEAD
17
+ python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.InvariantIsing.Unconditional /workspace
18
+ rm -rf "$tmp"
19
+ fi
20
+ echo "placed the reference proof of InvariantIsing"
tasks/invariant-ising/task.toml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.4"
2
+
3
+ [task]
4
+ name = "openai-math/invariant-ising"
5
+ version = "1.0.0"
6
+ description = "Prove InvariantIsing (openai/math family 234: All-temperature pressure for orthogonally invariant Ising spin glasses) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox."
7
+ keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"]
8
+
9
+ [metadata]
10
+ source = "https://github.com/openai/math"
11
+ source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a"
12
+ source_license = "Apache-2.0"
13
+ source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/InvariantIsing.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root"
14
+ challenge = "InvariantIsing"
15
+ family = "234"
16
+ family_title = "All-temperature pressure for orthogonally invariant Ising spin glasses"
17
+ subject = "Probability and statistical mechanics"
18
+ theorems = ["OAI.InvariantIsing.limiting_pressure_of_extreme_limits_unconditional", "OAI.InvariantIsing.limiting_wasserstein_field_pressure_of_extreme_limits_unconditional", "OAI.InvariantIsing.positive_temperature_pressure_unconditional", "OAI.InvariantIsing.ground_state_limit_unconditional", "OAI.InvariantIsing.random_pressure_tendsto_in_measure_unconditional", "OAI.InvariantIsing.random_pressure_limit_unconditional", "OAI.InvariantIsing.random_pressure_tendsto_ae_unconditional", "OAI.InvariantIsing.random_field_pressure_tendsto_ae_unconditional", "OAI.InvariantIsing.gaussianPattern_pressure_limit_unconditional", "OAI.InvariantIsing.gaussianPattern_ground_limit_unconditional", "OAI.InvariantIsing.gaussianPattern_norm_limits_unconditional"]
19
+ definition_holes = []
20
+ fixed_definitions = []
21
+ reference_module = "OAI.Probability.InvariantIsing.Unconditional"
22
+ reference_modules = 2123
23
+ reference_lean_bytes = 10537287
24
+ reference_requires_packages = []
25
+ oracle_result = "accepted"
26
+ oracle_grade_seconds = 5030
27
+ difficulty = "research"
28
+
29
+ [agent]
30
+ timeout_sec = 14400
31
+ network_mode = "no-network"
32
+
33
+ [environment]
34
+ build_timeout_sec = 5400
35
+ cpus = 4
36
+ memory_mb = 8192
37
+ storage_mb = 10240
38
+ workdir = "/workspace"
39
+ # Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs.
40
+ env = { LEAN_NUM_THREADS = "3" }
41
+
42
+ [verifier]
43
+ timeout_sec = 21183
44
+ environment_mode = "separate"
45
+ network_mode = "no-network"
46
+
47
+ [[verifier.collect]]
48
+ command = "python3 /opt/openai-math/pack_submission.py"
49
+ timeout_sec = 300
tasks/invariant-ising/tests/Challenge.lean ADDED
@@ -0,0 +1,495 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+
3
+ namespace OAI
4
+
5
+ /-! All-temperature invariant Ising pressure and its magnetic, random-spectral,
6
+ ground-state, and Gaussian-pattern extensions. -/
7
+
8
+ noncomputable section
9
+ open MeasureTheory ProbabilityTheory Filter Set
10
+ open scoped BigOperators Topology Matrix Classical ENNReal
11
+ universe u
12
+ namespace InvariantIsing
13
+
14
+ abbrev Spin (N : ℕ) := Fin N → Bool
15
+
16
+ def spinValue (b : Bool) : ℝ := if b then 1 else -1
17
+
18
+ def logPartition {X : Type*} [Fintype X] (H : X → ℝ) : ℝ :=
19
+ Real.log ((Fintype.card X : ℝ)⁻¹ * ∑ x, Real.exp (H x))
20
+
21
+ def fieldEnergy {N : ℕ} (c : Fin N → ℝ) (σ : Spin N) : ℝ :=
22
+ ∑ i, c i * spinValue (σ i)
23
+
24
+ abbrev Rotation (N : ℕ) :=
25
+ EuclideanSpace ℝ (Fin N) ≃ₗᵢ[ℝ] EuclideanSpace ℝ (Fin N)
26
+
27
+ abbrev Orthogonal (N : ℕ) := Matrix.orthogonalGroup (Fin N) ℝ
28
+
29
+ def spinVector {N : ℕ} (σ : Spin N) : EuclideanSpace ℝ (Fin N) :=
30
+ WithLp.toLp 2 (fun i => spinValue (σ i))
31
+
32
+ def rotatedEnergy {N : ℕ} (eig : Fin N → ℝ) (U : Rotation N) (σ : Spin N) : ℝ :=
33
+ (1 / 2 : ℝ) * ∑ i, eig i * (U (spinVector σ) i) ^ 2
34
+
35
+ def rotatedPressure {N : ℕ} (eig : Fin N → ℝ) (U : Rotation N)
36
+ (c : Fin N → ℝ) : ℝ :=
37
+ (N : ℝ)⁻¹ * logPartition (fun σ => rotatedEnergy eig U σ + fieldEnergy c σ)
38
+
39
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
40
+
41
+ lemma orthogonal_mulVec_norm_sq {N : ℕ} (U : Orthogonal N)
42
+ (v : EuclideanSpace ℝ (Fin N)) :
43
+ ‖WithLp.toLp 2 ((U : Matrix (Fin N) (Fin N) ℝ) *ᵥ v.ofLp)‖ ^ 2 = ‖v‖ ^ 2 := by
44
+ have hU : (U : Matrix (Fin N) (Fin N) ℝ)ᵀ *
45
+ (U : Matrix (Fin N) (Fin N) ℝ) = 1 :=
46
+ (Matrix.mem_orthogonalGroup_iff' (Fin N) ℝ).mp U.property
47
+ rw [EuclideanSpace.real_norm_sq_eq, EuclideanSpace.real_norm_sq_eq]
48
+ simp only [pow_two]
49
+ change ((U : Matrix (Fin N) (Fin N) ℝ) *ᵥ v.ofLp) ⬝ᵥ
50
+ ((U : Matrix (Fin N) (Fin N) ℝ) *ᵥ v.ofLp) = v.ofLp ⬝ᵥ v.ofLp
51
+ rw [← Matrix.dotProduct_transpose_mulVec, Matrix.mulVec_mulVec, hU,
52
+ Matrix.one_mulVec]
53
+
54
+ def matrixRotation {N : ℕ} (U : Orthogonal N) : Rotation N :=
55
+ { ((WithLp.linearEquiv 2 ℝ (Fin N → ℝ)).trans
56
+ (Matrix.UnitaryGroup.toLinearEquiv U)).trans
57
+ (WithLp.linearEquiv 2 ℝ (Fin N → ℝ)).symm with
58
+ norm_map' := fun v => (sq_eq_sq₀ (norm_nonneg _) (norm_nonneg _)).mp
59
+ (orthogonal_mulVec_norm_sq U v) }
60
+
61
+ structure OverlapPath where
62
+ val : ℝ → ℝ
63
+ monotone : Monotone val
64
+ nonneg : ∀ s, 0 ≤ val s
65
+ le_one : ∀ s, val s ≤ 1
66
+
67
+ instance : CoeFun OverlapPath (fun _ => ℝ → ℝ) := ⟨OverlapPath.val⟩
68
+
69
+ def pathMeasure : Measure ℝ := volume.restrict (Ioo (0 : ℝ) 1)
70
+
71
+ def deficit (p : OverlapPath) (r : ℝ) : ℝ :=
72
+ 1 - r - ∫ s, max (p s - r) 0 ∂pathMeasure
73
+
74
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
75
+
76
+ def gaussianOperator (a v : ℝ) (f : ℝ → ℝ) (z : ℝ) : ℝ :=
77
+ if a = 0 then ∫ g, f (z + Real.sqrt v * g) ∂gaussianReal 0 1
78
+ else a⁻¹ * Real.log (∫ g, Real.exp (a * f (z + Real.sqrt v * g)) ∂gaussianReal 0 1)
79
+
80
+ structure FieldStep where
81
+ depth : ℕ
82
+ cut : Fin (depth + 2) → ℝ
83
+ ordered_cut : StrictMono cut
84
+ first : cut 0 = 0
85
+ last : cut (Fin.last (depth + 1)) = 1
86
+ height : Fin (depth + 1) → ℝ
87
+ nonneg : ∀ i, 0 ≤ height i
88
+ ordered_height : Monotone height
89
+
90
+ def fieldFunction (h : FieldStep) (s : ℝ) : ℝ :=
91
+ ∑ i : Fin (h.depth + 1),
92
+ if h.cut i.castSucc < s ∧ s < h.cut i.succ then h.height i else 0
93
+
94
+ def fieldIncrement (h : FieldStep) (i : Fin (h.depth + 1)) : ℝ × ℝ :=
95
+ (h.cut i.castSucc, h.height i -
96
+ if hi : i.val = 0 then 0 else h.height ⟨i.val - 1, by omega⟩)
97
+
98
+ def fieldValue (h : FieldStep) (b : ℝ) : ℝ :=
99
+ ((List.ofFn (fieldIncrement h)).foldr
100
+ (fun av f => gaussianOperator av.1 av.2 f) (fun z => Real.log (Real.cosh z))) b -
101
+ h.height (Fin.last h.depth) / 2
102
+
103
+ def fieldPairing (p : OverlapPath) (h : FieldStep) : ℝ :=
104
+ ∫ s, p s * fieldFunction h s ∂pathMeasure
105
+
106
+ def entropyFunctional (p : OverlapPath) : EReal :=
107
+ ⨆ h : FieldStep, ((fieldValue h 0 + fieldPairing p h / 2 : ℝ) : EReal)
108
+
109
+ def spectralFunctional (R : ℝ → ℝ) (p : OverlapPath) : ℝ :=
110
+ (1 / 2 : ℝ) * ∫ r, R (deficit p r) ∂pathMeasure
111
+
112
+ def variationalFunctional (R : ℝ → ℝ) : EReal :=
113
+ ⨅ p : OverlapPath, entropyFunctional p + (spectralFunctional R p : EReal)
114
+
115
+ def measureResolvent (μ : Measure ℝ) (b : ℝ) : ℝ := ∫ y, 1 / (b - y) ∂μ
116
+
117
+ def measureInverse (μ : Measure ℝ) (e x : ℝ) : ℝ :=
118
+ if h : ∃ b, e < b ∧ measureResolvent μ b = x then h.choose else e
119
+
120
+ def measureR (μ : Measure ℝ) (e x : ℝ) : ℝ :=
121
+ if 0 < x then measureInverse μ e x - 1 / x else ∫ y, y ∂μ
122
+
123
+ def finiteSpectralMeasure {ι : Type*} (ρ eig : ι → ℝ) : Measure ℝ :=
124
+ Measure.sum fun a => ENNReal.ofReal (ρ a) • Measure.dirac (eig a)
125
+
126
+ theorem finiteSpectralMeasure_probability {ι : Type*} [Fintype ι] (ρ eig : ι → ℝ)
127
+ (hρ : ∀ a, 0 ≤ ρ a) (hsum : ∑ a, ρ a = 1) :
128
+ IsProbabilityMeasure (finiteSpectralMeasure ρ eig) := by
129
+ apply HasSum.isProbabilityMeasure_sum_dirac hρ
130
+ simpa only [hsum] using hasSum_fintype ρ
131
+
132
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
133
+
134
+ lemma empiricalSpectralWeight_sum {N : ℕ} (hN : 0 < N) :
135
+ ∑ _i : Fin N, (1 : ℝ)/N=1 := by
136
+ simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul]
137
+ field_simp
138
+
139
+ def empiricalSpectralLaw {N : ℕ} (hN : 0 < N) (eig : Fin N → ℝ) : ProbabilityMeasure ℝ :=
140
+ ⟨finiteSpectralMeasure (fun _ => (1 : ℝ)/N) eig,
141
+ finiteSpectralMeasure_probability _ _ (fun _ => by positivity) (empiricalSpectralWeight_sum hN)⟩
142
+
143
+ def spectralMinimum {n : ℕ} (eig : Fin (n+1) → ℝ) : ℝ :=
144
+ (Finset.univ.image eig).min' (Finset.image_nonempty.mpr Finset.univ_nonempty)
145
+
146
+ def spectralMaximum {n : ℕ} (eig : Fin (n+1) → ℝ) : ℝ :=
147
+ (Finset.univ.image eig).max' (Finset.image_nonempty.mpr Finset.univ_nonempty)
148
+
149
+ def magneticBiasObjective (h : FieldStep) (s b : ℝ) : ℝ := fieldValue h b - b * s
150
+
151
+ def constrainedFieldValue (h : FieldStep) (s : ℝ) : ℝ :=
152
+ sInf (range (magneticBiasObjective h s))
153
+
154
+ def magneticGroupValue {A : Type*} [Fintype A] (γ m : A → ℝ) (h : FieldStep) : ℝ :=
155
+ ∑ a, γ a * constrainedFieldValue h (m a)
156
+
157
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
158
+
159
+ def magneticEntropyFunctional {A : Type*} [Fintype A] (γ m : A → ℝ)
160
+ (p : OverlapPath) : EReal :=
161
+ ⨆ h : FieldStep, ((magneticGroupValue γ m h + fieldPairing p h / 2 : ℝ) : EReal)
162
+
163
+ def magneticVariationalFunctional {A : Type*} [Fintype A] (R : ℝ → ℝ) (γ m : A → ℝ) : EReal :=
164
+ ⨅ p : OverlapPath, magneticEntropyFunctional γ m p + (spectralFunctional R p : EReal)
165
+
166
+ def RationalMagnetization (A : Type*) := {m : A → ℚ // ∀ a, |(m a : ℝ)| < 1}
167
+
168
+ def finiteMagneticFunctional {A : Type*} [Fintype A] (R : ℝ → ℝ) (γ c : A → ℝ) : EReal :=
169
+ ⨆ m : RationalMagnetization A,
170
+ ((∑ a, γ a * c a * (m.val a : ℝ) : ℝ) : EReal) +
171
+ magneticVariationalFunctional R γ (fun a => (m.val a : ℝ))
172
+
173
+ def finiteIndexWeight {Ω A : Type*} [MeasurableSpace Ω]
174
+ (P : Measure Ω) (g : Ω → A) (a : A) : ℝ := P.real (g ⁻¹' {a})
175
+
176
+ def simpleFieldIndex {Ω : Type*} [MeasurableSpace Ω] (s : SimpleFunc Ω ℝ) (x : Ω) : s.range :=
177
+ ⟨s x,s.mem_range_self x⟩
178
+
179
+ def simpleFieldWeight {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) (s : SimpleFunc Ω ℝ) :=
180
+ finiteIndexWeight P (simpleFieldIndex s)
181
+
182
+ abbrev SimpleFieldPositive {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) (s : SimpleFunc Ω ℝ) :=
183
+ {i : s.range // 0 < simpleFieldWeight P s i}
184
+
185
+ def simpleFieldValue {Ω : Type*} [MeasurableSpace Ω]
186
+ (P : Measure Ω) [IsProbabilityMeasure P] (s : SimpleFunc Ω ℝ) (R : ℝ → ℝ) : ℝ :=
187
+ (finiteMagneticFunctional R (fun i : SimpleFieldPositive P s => simpleFieldWeight P s i)
188
+ (fun i => i.val.val)).toReal
189
+
190
+ def fieldSimpleApproximation (n : ℕ) : SimpleFunc ℝ ℝ :=
191
+ SimpleFunc.approxOn id measurable_id (range (id : ℝ → ℝ) ∪ {0}) 0 (by simp) n
192
+
193
+ def magneticFieldFunctional (spectral : Measure ℝ) (edge : ℝ) (field : ProbabilityMeasure ℝ) : ℝ :=
194
+ limUnder atTop (fun n => simpleFieldValue (field : Measure ℝ) (fieldSimpleApproximation n)
195
+ (measureR spectral edge))
196
+
197
+ structure FieldLawCoupling (μ ν : ProbabilityMeasure ℝ) where
198
+ law : ProbabilityMeasure (ℝ × ℝ)
199
+ fst : (law : Measure (ℝ × ℝ)).map Prod.fst = (μ : Measure ℝ)
200
+ snd : (law : Measure (ℝ × ℝ)).map Prod.snd = (ν : Measure ℝ)
201
+
202
+ def FieldLawCoupling.cost {μ ν : ProbabilityMeasure ℝ} (p : FieldLawCoupling μ ν) : ℝ≥0∞ :=
203
+ ∫⁻ xy, ENNReal.ofReal |xy.1-xy.2| ∂(p.law : Measure (ℝ × ℝ))
204
+
205
+ def fieldWassersteinOne (μ ν : ProbabilityMeasure ℝ) : ℝ≥0∞ :=
206
+ ⨅ p : FieldLawCoupling μ ν, p.cost
207
+
208
+ def scaledSpectralLaw (ν : ProbabilityMeasure ℝ) (β : ℝ) : ProbabilityMeasure ℝ :=
209
+ ν.map (fun x => β*x)
210
+
211
+ def groundStateEnergy {N : ℕ} (eig : Fin N → ℝ) (U : Rotation N) : ℝ :=
212
+ (N : ℝ)⁻¹ * Finset.univ.sup' Finset.univ_nonempty (rotatedEnergy eig U)
213
+
214
+ def thermalVariationalValue (ν : ProbabilityMeasure ℝ) (b β : ℝ) : ℝ :=
215
+ (variationalFunctional (measureR (scaledSpectralLaw ν β : Measure ℝ) (β*b))).toReal/β
216
+
217
+ abbrev FieldSpectralData (N : ℕ) := (Fin N → ℝ) × (Fin N → ℝ)
218
+
219
+ def dataPhysicalPressure {N : ℕ} (d : FieldSpectralData N) (U : Orthogonal N) : ℝ :=
220
+ rotatedPressure d.1 (matrixRotation U⁻¹) d.2
221
+
222
+ def ConditionalFieldOrbitLaw {Ω : Type*} [MeasurableSpace Ω] {N : ℕ}
223
+ (P : Measure Ω) (d : Ω → FieldSpectralData N) (pressure : Ω → ℝ)
224
+ (H : Measure (Orthogonal N)) : Prop :=
225
+ P.map (fun ω => (d ω,pressure ω)) =
226
+ ((P.map d).prod H).map (fun z => (z.1,dataPhysicalPressure z.1 z.2))
227
+
228
+ def spectralExcess {N : ℕ} (eig : Fin N → ℝ) (a b : ℝ) : ℝ :=
229
+ (insert 0 (Finset.univ.image (fun i => max (a-eig i) (eig i-b)))).max'
230
+ (Finset.insert_nonempty 0 _)
231
+
232
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
233
+
234
+ @[irreducible] def gaussianPatternCount (α : ℝ) (N : ℕ) : ℕ := ⌊α*N⌋₊
235
+
236
+ def marchenkoPasturA (α : ℝ) : ℝ := (1-Real.sqrt α)^2
237
+
238
+ def marchenkoPasturB (α : ℝ) : ℝ := (1+Real.sqrt α)^2
239
+
240
+ def marchenkoPasturLower (α : ℝ) : ℝ := if α ≤ 1 then 0 else marchenkoPasturA α
241
+
242
+ def marchenkoPasturMeasure (α : ℝ) : Measure ℝ :=
243
+ ENNReal.ofReal (max (1-α) 0) • Measure.dirac 0 +
244
+ volume.withDensity ((Icc (marchenkoPasturA α) (marchenkoPasturB α)).indicator
245
+ (fun x => ENNReal.ofReal
246
+ (Real.sqrt ((marchenkoPasturB α-x)*(x-marchenkoPasturA α))/(2*Real.pi*x))))
247
+
248
+ def gaussianPatternLimit (α c : ℝ) : ℝ :=
249
+ (variationalFunctional (measureR ((marchenkoPasturMeasure α).map (fun x => c*x))
250
+ (max (c*marchenkoPasturLower α) (c*marchenkoPasturB α)))).toReal
251
+
252
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
253
+
254
+ def gaussianPatternArray {N m : ℕ} (z : EuclideanSpace ℝ (Fin N × Fin m)) :
255
+ Matrix (Fin N) (Fin m) ℝ := fun i j => z (i,j)
256
+
257
+ def gaussianPatternSum {N m : ℕ} (z : EuclideanSpace ℝ (Fin N × Fin m)) (σ : Spin N) :
258
+ EuclideanSpace ℝ (Fin m) :=
259
+ WithLp.toLp 2 ((gaussianPatternArray z)ᵀ *ᵥ (fun i => spinValue (σ i)))
260
+
261
+ def gaussianPatternPressure {N m : ℕ} (c : ℝ)
262
+ (z : EuclideanSpace ℝ (Fin N × Fin m)) : ℝ :=
263
+ (N : ℝ)⁻¹*logPartition (fun σ : Spin N => c/(2*N)*‖gaussianPatternSum z σ‖^2)
264
+
265
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
266
+
267
+ def gaussianPatternGroundEnergy {N m : ℕ} (ε : ℝ)
268
+ (z : EuclideanSpace ℝ (Fin N × Fin m)) : ℝ :=
269
+ (N : ℝ)⁻¹*Finset.univ.sup' Finset.univ_nonempty
270
+ (fun σ : Spin N => ε/(2*N)*‖gaussianPatternSum z σ‖^2)
271
+
272
+ run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {}
273
+
274
+ def gaussianPatternColumn {N m : ℕ} (z : EuclideanSpace ℝ (Fin N × Fin m))
275
+ (i : Fin N) : EuclideanSpace ℝ (Fin m) := WithLp.toLp 2 (fun j => z (i,j))
276
+
277
+ def gaussianPatternOperator {N m : ℕ} (z : EuclideanSpace ℝ (Fin N × Fin m)) :
278
+ (Fin N → ℝ) →L[ℝ] EuclideanSpace ℝ (Fin m) :=
279
+ (PiLp.continuousLinearEquiv 2 ℝ (fun _ : Fin m => ℝ)).symm.toContinuousLinearMap.comp
280
+ ((gaussianPatternArray z)ᵀ.mulVecLin.toContinuousLinearMap)
281
+
282
+ theorem limiting_pressure_of_extreme_limits_unconditional :
283
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
284
+ (U : (N : ℕ) → Ω → Orthogonal N) (_hU : ∀ N, Measurable (U N))
285
+ (_hHaar : ∀ N, (P.map (U N)).IsMulRightInvariant)
286
+ (eig : (N : ℕ) → Fin N → ℝ) (ν : ProbabilityMeasure ℝ) (a b : ℝ)
287
+ (_hcompact : IsCompact (ν : Measure ℝ).support)
288
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
289
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
290
+ (_hmin : Tendsto (fun k => spectralMinimum (eig (k+1))) atTop (𝓝 a))
291
+ (_hmax : Tendsto (fun k => spectralMaximum (eig (k+1))) atTop (𝓝 b))
292
+ (_hweak : Tendsto (fun k => empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1)))
293
+ atTop (𝓝 ν)),
294
+ Tendsto (fun N => ∫ ω, rotatedPressure (eig N) (matrixRotation (U N ω)⁻¹) (fun _ => 0) ∂P)
295
+ atTop (𝓝 (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) ∧
296
+ ∀ᵐ ω ∂P, Tendsto (fun N => rotatedPressure (eig N) (matrixRotation (U N ω)⁻¹) (fun _ => 0))
297
+ atTop (𝓝 (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) := by
298
+ sorry
299
+
300
+ theorem limiting_wasserstein_field_pressure_of_extreme_limits_unconditional :
301
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
302
+ (U : (N : ℕ) → Ω → Orthogonal N) (_hU : ∀ N, Measurable (U N))
303
+ (_hHaar : ∀ N, (P.map (U N)).IsMulRightInvariant)
304
+ (eig : (N : ℕ) → Fin N → ℝ) (ν : ProbabilityMeasure ℝ) (a b : ℝ)
305
+ (_hcompact : IsCompact (ν : Measure ℝ).support)
306
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
307
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
308
+ (_hmin : Tendsto (fun k => spectralMinimum (eig (k+1))) atTop (𝓝 a))
309
+ (_hmax : Tendsto (fun k => spectralMaximum (eig (k+1))) atTop (𝓝 b))
310
+ (_hweak : Tendsto (fun k => empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1)))
311
+ atTop (𝓝 ν))
312
+ (field : (N : ℕ) → Fin N → ℝ) (ξ : ProbabilityMeasure ℝ)
313
+ (_hξ : Integrable (fun x : ℝ => x) (ξ : Measure ℝ))
314
+ (_hw : Tendsto (fun k => fieldWassersteinOne (empiricalSpectralLaw (Nat.succ_pos k) (field (k+1))) ξ)
315
+ atTop (𝓝 0)),
316
+ Tendsto (fun N => ∫ ω, rotatedPressure (eig N) (matrixRotation (U N ω)⁻¹) (field N) ∂P)
317
+ atTop (𝓝 (magneticFieldFunctional (ν : Measure ℝ) b ξ)) ∧
318
+ ∀ᵐ ω ∂P, Tendsto (fun N => rotatedPressure (eig N) (matrixRotation (U N ω)⁻¹) (field N))
319
+ atTop (𝓝 (magneticFieldFunctional (ν : Measure ℝ) b ξ)) := by
320
+ sorry
321
+
322
+ theorem positive_temperature_pressure_unconditional :
323
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
324
+ (U : (N : ℕ) → Ω → Orthogonal N) (_hU : ∀ N, Measurable (U N))
325
+ (_hHaar : ∀ N, (P.map (U N)).IsMulRightInvariant)
326
+ (eig : (N : ℕ) → Fin N → ℝ) (ν : ProbabilityMeasure ℝ) (a b : ℝ)
327
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
328
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
329
+ (_hno : ∀ ε : ℝ, 0 < ε → ∀ᶠ N in atTop, ∀ i, a-ε ≤ eig N i ∧ eig N i ≤ b+ε)
330
+ (β : ℝ) (_hβ : 0 < β)
331
+ (_hweak : Tendsto (fun k => empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1)))
332
+ atTop (𝓝 ν)),
333
+ Tendsto (fun N => ∫ ω, rotatedPressure (fun i => β*eig N i) (matrixRotation (U N ω)⁻¹) (fun _ => 0) ∂P)
334
+ atTop (𝓝 (variationalFunctional (measureR (scaledSpectralLaw ν β : Measure ℝ) (β*b))).toReal) ∧
335
+ ∀ᵐ ω ∂P, Tendsto (fun N => rotatedPressure (fun i => β*eig N i) (matrixRotation (U N ω)⁻¹) (fun _ => 0))
336
+ atTop (𝓝 (variationalFunctional (measureR (scaledSpectralLaw ν β : Measure ℝ) (β*b))).toReal) := by
337
+ sorry
338
+
339
+ theorem ground_state_limit_unconditional :
340
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
341
+ (U : (N : ℕ) → Ω → Orthogonal N) (_hU : ∀ N, Measurable (U N))
342
+ (_hHaar : ∀ N, (P.map (U N)).IsMulRightInvariant)
343
+ (eig : (N : ℕ) → Fin N → ℝ) (ν : ProbabilityMeasure ℝ) (a b : ℝ)
344
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
345
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
346
+ (_hno : ∀ ε : ℝ, 0 < ε → ∀ᶠ N in atTop, ∀ i, a-ε ≤ eig N i ∧ eig N i ≤ b+ε)
347
+ (_hweak : Tendsto (fun k => empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1)))
348
+ atTop (𝓝 ν)),
349
+ ∃ M : ℝ,
350
+ Tendsto (fun N => ∫ ω, groundStateEnergy (eig N) (matrixRotation (U N ω)⁻¹) ∂P)
351
+ atTop (𝓝 M) ∧
352
+ (∀ᵐ ω ∂P, Tendsto (fun N => groundStateEnergy (eig N) (matrixRotation (U N ω)⁻¹))
353
+ atTop (𝓝 M)) ∧
354
+ Tendsto (thermalVariationalValue ν b) atTop (𝓝 M) := by
355
+ sorry
356
+
357
+ theorem random_pressure_tendsto_in_measure_unconditional
358
+ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
359
+ (eig : (N : ℕ) → Ω → Fin N → ℝ) (Y : ℕ → Ω → ℝ)
360
+ (heig : ∀ N, Measurable (eig N)) (hY : ∀ N, Measurable (Y N))
361
+ (H : (N : ℕ) → Measure (Orthogonal N)) [∀ N, IsProbabilityMeasure (H N)]
362
+ [∀ N, (H N).IsMulRightInvariant]
363
+ (hlaw : ∀ N, ConditionalFieldOrbitLaw P (fun ω => (eig N ω,fun _ => 0)) (Y N) (H N))
364
+ (ν : ProbabilityMeasure ℝ) (a b : ℝ)
365
+ (hcompact : IsCompact (ν : Measure ℝ).support)
366
+ (hbound : (ν : Measure ℝ).support ⊆ Icc a b)
367
+ (ha : a∈(ν : Measure ℝ).support) (hb : b∈(ν : Measure ℝ).support)
368
+ (hweak : TendstoInMeasure P (fun k ω => LevyProkhorov.ofMeasure
369
+ (empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1) ω))) atTop
370
+ (fun _ => LevyProkhorov.ofMeasure ν))
371
+ (hexcess : TendstoInMeasure P (fun k ω => spectralExcess (eig (k+1) ω) a b)
372
+ atTop (fun _ => 0)) :
373
+ TendstoInMeasure P (fun k => Y (k+1)) atTop
374
+ (fun _ => (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) := by
375
+ sorry
376
+
377
+ theorem random_pressure_limit_unconditional :
378
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
379
+ (eig : (N : ℕ) → Ω → Fin N → ℝ) (Y : ℕ → Ω → ℝ)
380
+ (_heig : ∀ N, Measurable (eig N)) (_hY : ∀ N, Measurable (Y N))
381
+ (H : (N : ℕ) → Measure (Orthogonal N)) [∀ N, IsProbabilityMeasure (H N)]
382
+ [∀ N, (H N).IsMulRightInvariant]
383
+ (_hlaw : ∀ N, ConditionalFieldOrbitLaw P (fun ω => (eig N ω,fun _ => 0)) (Y N) (H N))
384
+ (ν : ProbabilityMeasure ℝ) (a b : ℝ)
385
+ (_hcompact : IsCompact (ν : Measure ℝ).support)
386
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
387
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
388
+ (_hweak : TendstoInMeasure P (fun k ω => LevyProkhorov.ofMeasure
389
+ (empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1) ω))) atTop
390
+ (fun _ => LevyProkhorov.ofMeasure ν))
391
+ (_hexcess : TendstoInMeasure P (fun k ω => spectralExcess (eig (k+1) ω) a b)
392
+ atTop (fun _ => 0))
393
+ (_hUI : UniformIntegrable (fun k => Y (k+1)) 1 P),
394
+ TendstoInMeasure P (fun k => Y (k+1)) atTop
395
+ (fun _ => (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) ∧
396
+ Tendsto (fun k => eLpNorm (fun ω => Y (k+1) ω-
397
+ (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) 1 P) atTop (𝓝 0) ∧
398
+ Tendsto (fun k => ∫ ω, Y (k+1) ω ∂P) atTop
399
+ (𝓝 (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) := by
400
+ sorry
401
+
402
+ theorem random_pressure_tendsto_ae_unconditional :
403
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
404
+ (eig : (N : ℕ) → Ω → Fin N → ℝ) (Y : ℕ → Ω → ℝ)
405
+ (_heig : ∀ N, Measurable (eig N)) (_hY : ∀ N, Measurable (Y N))
406
+ (H : (N : ℕ) → Measure (Orthogonal N)) [∀ N, IsProbabilityMeasure (H N)]
407
+ [∀ N, (H N).IsMulRightInvariant]
408
+ (_hlaw : ∀ N, ConditionalFieldOrbitLaw P (fun ω => (eig N ω,fun _ => 0)) (Y N) (H N))
409
+ (ν : ProbabilityMeasure ℝ) (a b : ℝ)
410
+ (_hcompact : IsCompact (ν : Measure ℝ).support)
411
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
412
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
413
+ (_hno : ∀ᵐ ω ∂P, ∀ ε : ℝ, 0 < ε → ∀ᶠ N in atTop,
414
+ ∀ i, a-ε ≤ eig N ω i ∧ eig N ω i ≤ b+ε)
415
+ (_hweak : ∀ᵐ ω ∂P, Tendsto (fun k =>
416
+ empiricalSpectralLaw (Nat.succ_pos k) (eig (k+1) ω)) atTop (𝓝 ν)),
417
+ ∀ᵐ ω ∂P, Tendsto (fun N => Y N ω) atTop
418
+ (𝓝 (variationalFunctional (measureR (ν : Measure ℝ) b)).toReal) := by
419
+ sorry
420
+
421
+ theorem random_field_pressure_tendsto_ae_unconditional :
422
+ ∀ {Ω : Type*} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
423
+ (d : (N : ℕ) → Ω → FieldSpectralData N) (Y : ℕ → Ω → ℝ)
424
+ (_hd : ∀ N, Measurable (d N)) (_hY : ∀ N, Measurable (Y N))
425
+ (H : (N : ℕ) → Measure (Orthogonal N)) [∀ N, IsProbabilityMeasure (H N)]
426
+ [∀ N, (H N).IsMulRightInvariant]
427
+ (_hlaw : ∀ N, ConditionalFieldOrbitLaw P (d N) (Y N) (H N))
428
+ (ν : ProbabilityMeasure ℝ) (a b : ℝ)
429
+ (_hcompact : IsCompact (ν : Measure ℝ).support)
430
+ (_hbound : (ν : Measure ℝ).support ⊆ Icc a b)
431
+ (_ha : a∈(ν : Measure ℝ).support) (_hb : b∈(ν : Measure ℝ).support)
432
+ (_hno : ∀ᵐ ω ∂P, ∀ ε : ℝ, 0 < ε → ∀ᶠ N in atTop,
433
+ ∀ i, a-ε ≤ (d N ω).1 i ∧ (d N ω).1 i ≤ b+ε)
434
+ (_hweak : ∀ᵐ ω ∂P, Tendsto (fun k =>
435
+ empiricalSpectralLaw (Nat.succ_pos k) (d (k+1) ω).1) atTop (𝓝 ν))
436
+ (ξ : ProbabilityMeasure ℝ) (_hξ : Integrable (fun x : ℝ => x) (ξ : Measure ℝ))
437
+ (_hw : ∀ᵐ ω ∂P, Tendsto (fun k => fieldWassersteinOne
438
+ (empiricalSpectralLaw (Nat.succ_pos k) (d (k+1) ω).2) ξ) atTop (𝓝 0)),
439
+ ∀ᵐ ω ∂P, Tendsto (fun N => Y N ω) atTop
440
+ (𝓝 (magneticFieldFunctional (ν : Measure ℝ) b ξ)) := by
441
+ sorry
442
+
443
+ theorem gaussianPattern_pressure_limit_unconditional :
444
+ ∀ (α : ℝ) (_hα : 0 < α)
445
+ {Ω : Type u} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
446
+ (Z : (N : ℕ) → Ω → EuclideanSpace ℝ (Fin N × Fin (gaussianPatternCount α N)))
447
+ (_hZ : ∀ N, Measurable (Z N)) (_hlaw : ∀ N, HasLaw (Z N) (stdGaussian _) P)
448
+ (c : ℝ),
449
+ TendstoInMeasure P (fun k ω => gaussianPatternPressure (N := k+1) (m := gaussianPatternCount α (k+1)) c (Z (k+1) ω)) atTop
450
+ (fun _ => gaussianPatternLimit α c) ∧
451
+ Tendsto (fun k => eLpNorm (fun ω => gaussianPatternPressure (N := k+1) (m := gaussianPatternCount α (k+1)) c (Z (k+1) ω)-
452
+ gaussianPatternLimit α c) 1 P) atTop (𝓝 0) ∧
453
+ Tendsto (fun k => ∫ ω, gaussianPatternPressure (N := k+1) (m := gaussianPatternCount α (k+1)) c (Z (k+1) ω) ∂P) atTop
454
+ (𝓝 (gaussianPatternLimit α c)) := by
455
+ sorry
456
+
457
+ theorem gaussianPattern_ground_limit_unconditional :
458
+ ∀ (α : ℝ) (_hα : 0 < α)
459
+ {Ω : Type u} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
460
+ (Z : (N : ℕ) → Ω → EuclideanSpace ℝ (Fin N × Fin (gaussianPatternCount α N)))
461
+ (_hZ : ∀ N, Measurable (Z N)) (_hlaw : ∀ N, HasLaw (Z N) (stdGaussian _) P)
462
+ (ε : ℝ),
463
+ ∃ e : ℝ,
464
+ TendstoInMeasure P (fun k ω => gaussianPatternGroundEnergy ε (Z (k+1) ω)) atTop (fun _ => e) ∧
465
+ Tendsto (fun k => eLpNorm (fun ω => gaussianPatternGroundEnergy ε (Z (k+1) ω)-e) 1 P)
466
+ atTop (𝓝 0) ∧
467
+ Tendsto (fun k => ∫ ω, gaussianPatternGroundEnergy ε (Z (k+1) ω) ∂P) atTop (𝓝 e) ∧
468
+ Tendsto (fun β => gaussianPatternLimit α (ε*β)/β) atTop (𝓝 e) := by
469
+ sorry
470
+
471
+ theorem gaussianPattern_norm_limits_unconditional :
472
+ ∀ (α : ℝ) (_hα : 0 < α)
473
+ {Ω : Type u} [MeasurableSpace Ω] (P : Measure Ω) [IsProbabilityMeasure P]
474
+ (Z : (N : ℕ) → Ω → EuclideanSpace ℝ (Fin N × Fin (gaussianPatternCount α N)))
475
+ (_hZ : ∀ N, Measurable (Z N)) (_hlaw : ∀ N, HasLaw (Z N) (stdGaussian _) P),
476
+ ∃ eplus eminus : ℝ, 0 ≤ eplus ∧ eminus ≤ 0 ∧
477
+ Tendsto (fun β => gaussianPatternLimit α β/β) atTop (𝓝 eplus) ∧
478
+ Tendsto (fun β => gaussianPatternLimit α (-β)/β) atTop (𝓝 eminus) ∧
479
+ (TendstoInMeasure P (fun k ω => ‖gaussianPatternOperator (Z (k+1) ω)‖/(k+1)) atTop
480
+ (fun _ => Real.sqrt (2*eplus)) ∧
481
+ Tendsto (fun k => eLpNorm (fun ω => ‖gaussianPatternOperator (Z (k+1) ω)‖/(k+1)-
482
+ Real.sqrt (2*eplus)) 1 P) atTop (𝓝 0)) ∧
483
+ (TendstoInMeasure P (fun k ω =>
484
+ (Finset.univ.inf' Finset.univ_nonempty (fun σ : Spin (k+1) => ‖gaussianPatternSum (Z (k+1) ω) σ‖))/(k+1))
485
+ atTop (fun _ => Real.sqrt (-2*eminus)) ∧
486
+ Tendsto (fun k => eLpNorm (fun ω =>
487
+ (Finset.univ.inf' Finset.univ_nonempty (fun σ : Spin (k+1) => ‖gaussianPatternSum (Z (k+1) ω) σ‖))/(k+1)-
488
+ Real.sqrt (-2*eminus)) 1 P) atTop (𝓝 0)) := by
489
+ sorry
490
+
491
+ end InvariantIsing
492
+
493
+ end
494
+
495
+ end OAI
tasks/invariant-ising/tests/grade.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Grade one openai/math challenge with Comparator.
3
+
4
+ This runs as root in a separate verifier sandbox that never executed agent code. The only input the
5
+ agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's
6
+ trusted challenge and Comparator config) and from the image.
7
+
8
+ Steps:
9
+ 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files.
10
+ 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission,
11
+ and the image's prebuilt Mathlib (root-owned, read-only to the grader).
12
+ 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network.
13
+ Comparator builds Challenge and Submission inside landrun, checks that every listed theorem
14
+ has exactly the challenge's statement, that only the permitted axioms are used, and replays
15
+ the proof through the Lean kernel.
16
+ 4. Kill everything the grader started, then write the verdict.
17
+
18
+ reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or
19
+ non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build,
20
+ the network block cannot be installed) writes no reward, so Harbor reports an error instead of a
21
+ score.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import os
28
+ import pwd
29
+ import re
30
+ import shutil
31
+ import signal
32
+ import socket
33
+ import stat
34
+ import subprocess
35
+ import sys
36
+ import tarfile
37
+ import tempfile
38
+ import threading
39
+ import time
40
+ from pathlib import Path
41
+
42
+ TESTS = Path("/tests")
43
+ VERIFIER_DIR = Path("/logs/verifier")
44
+ SUBMISSION_TAR = Path("/logs/artifacts/submission.tar")
45
+ LEAN_ENV = Path("/opt/lean-env")
46
+ RUN_ROOT = Path("/var/lib/oai-grade")
47
+ GRADER = "grader"
48
+ SUCCESS_LINE = "Your solution is okay!"
49
+ GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
+ # Lake and Comparator wording when a build process is killed for running out of memory.
52
+ OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
+
54
+ MAX_FILES = 20_000
55
+ MAX_FILE_BYTES = 64 << 20
56
+ MAX_TOTAL_BYTES = 768 << 20
57
+ # Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with
58
+ # a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`.
59
+ # Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`).
60
+ _COMPONENT = r"[^\W\d][\w'!?]*"
61
+ MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$")
62
+ MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$")
63
+
64
+ LAKEFILE = """import Lake
65
+ open Lake DSL
66
+
67
+ package openai_math where
68
+ leanOptions := #[⟨`autoImplicit, false⟩]
69
+
70
+ require mathlib from git
71
+ "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612"
72
+
73
+ lean_lib Challenge
74
+
75
+ -- `Submission` and every `Submission.*` module it imports.
76
+ lean_lib Submission
77
+ """
78
+
79
+
80
+ class Rejected(Exception):
81
+ """The submission is invalid: reward 0."""
82
+
83
+
84
+ class GradingError(Exception):
85
+ """The grading setup is broken: no reward, so the trial shows as errored."""
86
+
87
+
88
+ def toolchain_bin() -> Path:
89
+ bins = sorted(Path("/opt/elan/toolchains").glob("*/bin"))
90
+ if len(bins) != 1:
91
+ raise GradingError(f"expected one Lean toolchain, found {bins}")
92
+ return bins[0]
93
+
94
+
95
+ def unpack_submission(dest: Path) -> dict:
96
+ """Copy the submission's .lean files into ``dest``; reject anything else."""
97
+ try:
98
+ st = SUBMISSION_TAR.lstat()
99
+ except FileNotFoundError:
100
+ raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished")
101
+ if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20):
102
+ raise Rejected("submission archive is not a regular file of acceptable size")
103
+
104
+ files, total = [], 0
105
+ try:
106
+ with tarfile.open(SUBMISSION_TAR, "r:") as tar:
107
+ for count, member in enumerate(tar):
108
+ if count > MAX_FILES * 2:
109
+ raise Rejected(f"submission has more than {MAX_FILES} entries")
110
+ name = member.name.removeprefix("./")
111
+ if member.isdir():
112
+ if not MEMBER_DIR.match(name):
113
+ raise Rejected(f"unexpected directory in submission: {name!r}")
114
+ continue
115
+ if not member.isreg():
116
+ raise Rejected(f"only regular .lean files are accepted, got {name!r}")
117
+ if not MEMBER.match(name):
118
+ raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)")
119
+ if member.size > MAX_FILE_BYTES:
120
+ raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB")
121
+ total += member.size
122
+ if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES:
123
+ raise Rejected("submission is too large")
124
+ data = tar.extractfile(member).read(MAX_FILE_BYTES + 1)
125
+ try:
126
+ data.decode("utf-8")
127
+ except UnicodeDecodeError:
128
+ raise Rejected(f"{name} is not valid UTF-8")
129
+ target = dest / name
130
+ if target.exists():
131
+ raise Rejected(f"duplicate entry {name!r}")
132
+ target.parent.mkdir(parents=True, exist_ok=True)
133
+ target.write_bytes(data)
134
+ target.chmod(0o644)
135
+ files.append(name)
136
+ except tarfile.TarError as exc:
137
+ raise Rejected(f"submission archive is unreadable: {exc}")
138
+ if "Submission.lean" not in files:
139
+ raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished")
140
+ for d in (dest / "Submission",):
141
+ if d.exists():
142
+ for p in [d, *d.rglob("*")]:
143
+ if p.is_dir():
144
+ p.chmod(0o755)
145
+ return {"files": len(files), "bytes": total}
146
+
147
+
148
+ def write_project(run: Path, config: dict) -> None:
149
+ (run / "lakefile.lean").write_text(LAKEFILE)
150
+ shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json")
151
+ shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain")
152
+ shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean")
153
+ comparator_config = {
154
+ "challenge_module": "Challenge",
155
+ "solution_module": "Submission",
156
+ "theorem_names": config["theorem_names"],
157
+ "definition_names": config["definition_names"],
158
+ "permitted_axioms": config["permitted_axioms"],
159
+ "enable_nanoda": False,
160
+ }
161
+ (run / "config.json").write_text(json.dumps(comparator_config, indent=2))
162
+ lake = run / ".lake"
163
+ lake.mkdir()
164
+ (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages")
165
+ for p in run.iterdir():
166
+ if p.name != ".lake":
167
+ os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False)
168
+ uid = pwd.getpwnam(GRADER).pw_uid
169
+ os.chown(lake, uid, uid)
170
+ os.chmod(run, 0o755)
171
+
172
+
173
+ def fresh_run(task: dict) -> Path:
174
+ """A new, empty Lake project for one grading attempt."""
175
+ run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT))
176
+ write_project(run, task["comparator"])
177
+ return run
178
+
179
+
180
+ def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int:
181
+ """Make the prebuilt toolchain and packages readable by the grader (never writable).
182
+
183
+ The image already does this; this only repairs an image built without it. It must touch
184
+ nothing that is already right: these files live in the image's lower overlay layer, and a
185
+ `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took
186
+ 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat).
187
+ Returns the number of entries changed.
188
+ """
189
+ changed = 0
190
+ for root in roots:
191
+ for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
192
+ for name in [*dirnames, *filenames]:
193
+ path = os.path.join(dirpath, name)
194
+ st = os.lstat(path)
195
+ if stat.S_ISDIR(st.st_mode):
196
+ want = (st.st_mode | 0o555) & ~0o022
197
+ elif stat.S_ISREG(st.st_mode):
198
+ want = (st.st_mode | 0o444) & ~0o022
199
+ else:
200
+ continue
201
+ if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want):
202
+ os.chmod(path, stat.S_IMODE(want))
203
+ changed += 1
204
+ return changed
205
+
206
+
207
+ def block_grader_network() -> None:
208
+ """Reject every socket the grader user opens, loopback included.
209
+
210
+ landrun already denies TCP to the sandboxed build. This rule also covers the grader's own
211
+ processes outside landrun and services listening inside the sandbox.
212
+ """
213
+ uid = str(pwd.getpwnam(GRADER).pw_uid)
214
+ for tool in ("iptables", "ip6tables"):
215
+ rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"]
216
+ if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0:
217
+ continue
218
+ res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True)
219
+ if res.returncode != 0:
220
+ raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}")
221
+ probe = subprocess.run(
222
+ ["runuser", "-u", GRADER, "--", sys.executable, "-c",
223
+ "import socket,sys\n"
224
+ "s=socket.socket(); s.settimeout(3)\n"
225
+ "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"],
226
+ capture_output=True,
227
+ )
228
+ if probe.returncode == 0:
229
+ raise GradingError("the grader user can still open loopback connections")
230
+
231
+
232
+ def kill_grader() -> None:
233
+ for _ in range(20):
234
+ subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True)
235
+ if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0:
236
+ return
237
+ time.sleep(0.5)
238
+ raise GradingError("could not stop the grader's processes")
239
+
240
+
241
+ def out_of_memory(out: str) -> bool:
242
+ return any(m in out for m in OOM_MARKERS)
243
+
244
+
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
+ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
+ env = {
290
+ "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
291
+ "HOME": str(run),
292
+ "LANG": "C.UTF-8",
293
+ "LEAN_ABORT_ON_PANIC": "1",
294
+ # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large
295
+ # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun.
296
+ "LEAN_NUM_THREADS": threads,
297
+ }
298
+ cmd = [
299
+ "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
+ "lake", "env", "comparator", "config.json",
301
+ ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
+ return code, stdout + "\n--- stderr ---\n" + stderr
314
+
315
+
316
+ def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]:
317
+ """Run ``cmd``; on timeout kill its whole process tree and return code None.
318
+
319
+ `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun
320
+ kept the output pipe open and the grader waited past Harbor's own limit. Here the command
321
+ gets its own session; on timeout its process group is killed, and ``kill_extra`` (every
322
+ process of the grader user) catches anything that left the group.
323
+ """
324
+ proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
325
+ text=True, errors="replace", start_new_session=True)
326
+ try:
327
+ stdout, stderr = proc.communicate(timeout=timeout_sec)
328
+ return proc.returncode, stdout, stderr
329
+ except subprocess.TimeoutExpired:
330
+ try:
331
+ os.killpg(proc.pid, signal.SIGKILL)
332
+ except ProcessLookupError:
333
+ pass
334
+ if kill_extra:
335
+ kill_extra()
336
+ stdout, stderr = proc.communicate()
337
+ return None, stdout, stderr
338
+
339
+
340
+ def classify(code: int | None, out: str) -> tuple[int | None, str]:
341
+ """Map Comparator's result to (reward, reason). reward None means a grading error."""
342
+ if code == 0 and SUCCESS_LINE in out:
343
+ return 1, "accepted: statements match, only permitted axioms, kernel replay passed"
344
+ if "Building Submission" not in out:
345
+ # Comparator stopped before it touched the submission: the trusted challenge or the
346
+ # toolchain is broken (or too slow), which says nothing about the agent's proof.
347
+ return None, ("timed out before the submission was built" if code is None
348
+ else "the trusted Challenge failed to build or export")
349
+ if code is None:
350
+ return 0, "timed out while building or checking the submission"
351
+ tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
+ if out_of_memory(out):
355
+ return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
+ return 0, "rejected: " + " | ".join(tail)[-4000:]
357
+
358
+
359
+ def main() -> int:
360
+ VERIFIER_DIR.mkdir(parents=True, exist_ok=True)
361
+ os.chmod(VERIFIER_DIR, 0o755)
362
+ for name in ("reward.txt", "reward.json"):
363
+ (VERIFIER_DIR / name).unlink(missing_ok=True)
364
+
365
+ task = json.loads((TESTS / "task.json").read_text())
366
+ details: dict = {"task": task["challenge"], "started_at": time.time()}
367
+ reward: int | None = None
368
+ log = ""
369
+ try:
370
+ RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
+ deadline = time.time() + int(task["grade_timeout_sec"])
372
+ run = fresh_run(task)
373
+ details["permission_fixes"] = ensure_readable()
374
+ block_grader_network()
375
+ details["submission"] = unpack_submission(run)
376
+ code, out = run_comparator(run, int(deadline - time.time()))
377
+ log = out
378
+ kill_grader()
379
+ if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60:
380
+ # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
+ # in a fresh directory: the first attempt's .lake was written by the submission's own
382
+ # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
+ run = fresh_run(task)
385
+ unpack_submission(run)
386
+ code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
+ log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
+ kill_grader()
389
+ details["retried_single_thread"] = True
390
+ reward, details["reason"] = classify(code, out)
391
+ details["comparator_exit"] = code
392
+ except Rejected as exc:
393
+ reward, details["reason"] = 0, f"rejected: {exc}"
394
+ except GradingError as exc:
395
+ reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
+ finally:
399
+ try:
400
+ kill_grader()
401
+ except GradingError as exc:
402
+ reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
+ details["reward"] = reward
408
+ details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
+ (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
+ print(json.dumps(details, indent=2))
412
+ if reward is not None:
413
+ (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n")
414
+ return 0
415
+
416
+
417
+ if __name__ == "__main__":
418
+ sys.exit(main())
tasks/invariant-ising/tests/task.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "challenge": "InvariantIsing",
3
+ "comparator": {
4
+ "theorem_names": [
5
+ "OAI.InvariantIsing.limiting_pressure_of_extreme_limits_unconditional",
6
+ "OAI.InvariantIsing.limiting_wasserstein_field_pressure_of_extreme_limits_unconditional",
7
+ "OAI.InvariantIsing.positive_temperature_pressure_unconditional",
8
+ "OAI.InvariantIsing.ground_state_limit_unconditional",
9
+ "OAI.InvariantIsing.random_pressure_tendsto_in_measure_unconditional",
10
+ "OAI.InvariantIsing.random_pressure_limit_unconditional",
11
+ "OAI.InvariantIsing.random_pressure_tendsto_ae_unconditional",
12
+ "OAI.InvariantIsing.random_field_pressure_tendsto_ae_unconditional",
13
+ "OAI.InvariantIsing.gaussianPattern_pressure_limit_unconditional",
14
+ "OAI.InvariantIsing.gaussianPattern_ground_limit_unconditional",
15
+ "OAI.InvariantIsing.gaussianPattern_norm_limits_unconditional"
16
+ ],
17
+ "definition_names": [],
18
+ "permitted_axioms": [
19
+ "propext",
20
+ "Quot.sound",
21
+ "Classical.choice"
22
+ ]
23
+ },
24
+ "grade_timeout_sec": 20283
25
+ }
tasks/invariant-ising/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Runs in the separate verifier sandbox, which never ran agent code. See grade.py.
3
+ exec python3 /tests/grade.py
tasks/irrational-rotation/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 735
23
  reference_lean_bytes = 3645017
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 1441
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 3645017
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 2128
27
  difficulty = "research"
28
 
29
  [agent]
tasks/irrational-rotation/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/irrational-triangle-billiard/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 39
23
  reference_lean_bytes = 594085
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 820
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 594085
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 347
27
  difficulty = "research"
28
 
29
  [agent]
tasks/irrational-triangle-billiard/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/ising-finiteness/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 45
23
  reference_lean_bytes = 1494396
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 958
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 1494396
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 327
27
  difficulty = "research"
28
 
29
  [agent]
tasks/ising-finiteness/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/isometric-immersion/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 446
23
  reference_lean_bytes = 2824652
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 1242
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 2824652
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 698
27
  difficulty = "research"
28
 
29
  [agent]
tasks/isometric-immersion/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/k-median-recovery/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 506
23
  reference_lean_bytes = 3720803
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 1362
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 3720803
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 1418
27
  difficulty = "research"
28
 
29
  [agent]
tasks/k-median-recovery/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/k-median-refined-recovery/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 586
23
  reference_lean_bytes = 2580016
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 1849
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 2580016
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 1462
27
  difficulty = "research"
28
 
29
  [agent]
tasks/k-median-refined-recovery/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/k-median-threshold/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 765
23
  reference_lean_bytes = 3236997
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 2259
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 3236997
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 2180
27
  difficulty = "research"
28
 
29
  [agent]
tasks/k-median-threshold/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/k-server/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 37
23
  reference_lean_bytes = 1783312
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 587
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 1783312
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 322
27
  difficulty = "research"
28
 
29
  [agent]
tasks/k-server/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/kadison-ringrose/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 372
23
  reference_lean_bytes = 2793925
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 1352
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 2793925
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 1426
27
  difficulty = "research"
28
 
29
  [agent]
tasks/kadison-ringrose/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/kadison-similarity/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 816
23
  reference_lean_bytes = 5791602
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 3415
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 5791602
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 4111
27
  difficulty = "research"
28
 
29
  [agent]
tasks/kadison-similarity/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/kahler-splitting/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 46
23
  reference_lean_bytes = 726796
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 1239
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 726796
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 468
27
  difficulty = "research"
28
 
29
  [agent]
tasks/kahler-splitting/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/kaplansky-direct-finiteness/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 121
23
  reference_lean_bytes = 544294
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 1170
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 544294
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 704
27
  difficulty = "research"
28
 
29
  [agent]
tasks/kaplansky-direct-finiteness/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/kaplansky-finitely-presented/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 126
23
  reference_lean_bytes = 556097
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 1470
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 556097
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 723
27
  difficulty = "research"
28
 
29
  [agent]
tasks/kaplansky-finitely-presented/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None:
tasks/kaplansky-quasitrace/task.toml CHANGED
@@ -23,7 +23,7 @@ reference_modules = 123
23
  reference_lean_bytes = 1501004
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
- oracle_grade_seconds = 993
27
  difficulty = "research"
28
 
29
  [agent]
 
23
  reference_lean_bytes = 1501004
24
  reference_requires_packages = []
25
  oracle_result = "accepted"
26
+ oracle_grade_seconds = 492
27
  difficulty = "research"
28
 
29
  [agent]
tasks/kaplansky-quasitrace/tests/grade.py CHANGED
@@ -35,6 +35,7 @@ import subprocess
35
  import sys
36
  import tarfile
37
  import tempfile
 
38
  import time
39
  from pathlib import Path
40
 
@@ -46,6 +47,7 @@ RUN_ROOT = Path("/var/lib/oai-grade")
46
  GRADER = "grader"
47
  SUCCESS_LINE = "Your solution is okay!"
48
  GRADE_THREADS = "2"
 
49
  # Lake and Comparator wording when a build process is killed for running out of memory.
50
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
51
 
@@ -240,6 +242,49 @@ def out_of_memory(out: str) -> bool:
240
  return any(m in out for m in OOM_MARKERS)
241
 
242
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
244
  env = {
245
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
@@ -254,10 +299,17 @@ def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) ->
254
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
255
  "lake", "env", "comparator", "config.json",
256
  ]
257
- code, stdout, stderr = run_with_timeout(
258
- cmd, cwd=run, timeout_sec=timeout_sec,
259
- kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
260
- )
 
 
 
 
 
 
 
261
  return code, stdout + "\n--- stderr ---\n" + stderr
262
 
263
 
@@ -297,6 +349,8 @@ def classify(code: int | None, out: str) -> tuple[int | None, str]:
297
  if code is None:
298
  return 0, "timed out while building or checking the submission"
299
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
 
 
300
  if out_of_memory(out):
301
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
302
  return 0, "rejected: " + " | ".join(tail)[-4000:]
@@ -311,6 +365,7 @@ def main() -> int:
311
  task = json.loads((TESTS / "task.json").read_text())
312
  details: dict = {"task": task["challenge"], "started_at": time.time()}
313
  reward: int | None = None
 
314
  try:
315
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
316
  deadline = time.time() + int(task["grade_timeout_sec"])
@@ -325,26 +380,33 @@ def main() -> int:
325
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
326
  # in a fresh directory: the first attempt's .lake was written by the submission's own
327
  # build and must not be trusted for the challenge.
 
328
  run = fresh_run(task)
329
  unpack_submission(run)
330
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
331
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
332
  kill_grader()
333
  details["retried_single_thread"] = True
334
- (VERIFIER_DIR / "comparator.log").write_text(log)
335
  reward, details["reason"] = classify(code, out)
336
  details["comparator_exit"] = code
337
  except Rejected as exc:
338
  reward, details["reason"] = 0, f"rejected: {exc}"
339
  except GradingError as exc:
340
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
341
  finally:
342
  try:
343
  kill_grader()
344
  except GradingError as exc:
345
  reward, details["reason"] = None, f"grading error: {exc}"
 
 
 
 
346
  details["reward"] = reward
347
  details["finished_at"] = time.time()
 
348
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
349
  print(json.dumps(details, indent=2))
350
  if reward is not None:
 
35
  import sys
36
  import tarfile
37
  import tempfile
38
+ import threading
39
  import time
40
  from pathlib import Path
41
 
 
47
  GRADER = "grader"
48
  SUCCESS_LINE = "Your solution is okay!"
49
  GRADE_THREADS = "2"
50
+ SCRATCH_SWEEP_SEC = 15
51
  # Lake and Comparator wording when a build process is killed for running out of memory.
52
  OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137")
53
 
 
242
  return any(m in out for m in OOM_MARKERS)
243
 
244
 
245
+ def out_of_disk(out: str) -> bool:
246
+ return "no space left on device" in out.lower()
247
+
248
+
249
+ # Run as the grader user by `empty_build_scratch`. argv: the .lake/build/ir directory.
250
+ EMPTY_SCRATCH = r"""
251
+ import os, sys
252
+ for dirpath, _, files in os.walk(sys.argv[1]):
253
+ for name in files:
254
+ if not name.endswith(".setup.json"):
255
+ continue
256
+ base = os.path.join(dirpath, name[:-len(".setup.json")])
257
+ try:
258
+ # Lake writes X.c.hash once Lean, and leanir if the module needs it, are done with X;
259
+ # both read X.setup.json, so it may only be emptied after that.
260
+ if os.stat(base + ".c.hash").st_mtime < os.stat(base + ".setup.json").st_mtime:
261
+ continue
262
+ for path in (base + ".setup.json", base + ".c"):
263
+ if os.path.getsize(path):
264
+ os.truncate(path, 0)
265
+ except OSError:
266
+ pass
267
+ """
268
+
269
+
270
+ def empty_build_scratch(run: Path, stop: threading.Event) -> None:
271
+ """Until ``stop`` is set, empty files Lake leaves in .lake/build/ir that grading never reads.
272
+
273
+ For every module Lake writes a `.setup.json` (its imports with the path of every .olean they
274
+ pull in, about 5.5 MB with Mathlib) and the module compiled to C. Neither is used once the
275
+ module is built, and for proofs of 1,000-2,000 modules they filled the 10 GB disk before the
276
+ build finished. Lake keeps the recorded hashes, so emptied files do not trigger a rebuild.
277
+ This runs as the grader user, so it can touch nothing the build could not.
278
+ """
279
+ ir = str(run / ".lake" / "build" / "ir")
280
+ while not stop.wait(SCRATCH_SWEEP_SEC):
281
+ try:
282
+ subprocess.run(["runuser", "-u", GRADER, "--", sys.executable, "-c", EMPTY_SCRATCH, ir],
283
+ capture_output=True, timeout=600)
284
+ except subprocess.TimeoutExpired:
285
+ pass
286
+
287
+
288
  def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]:
289
  env = {
290
  "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin",
 
299
  "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()),
300
  "lake", "env", "comparator", "config.json",
301
  ]
302
+ stop = threading.Event()
303
+ sweeper = threading.Thread(target=empty_build_scratch, args=(run, stop), daemon=True)
304
+ sweeper.start()
305
+ try:
306
+ code, stdout, stderr = run_with_timeout(
307
+ cmd, cwd=run, timeout_sec=timeout_sec,
308
+ kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True),
309
+ )
310
+ finally:
311
+ stop.set()
312
+ sweeper.join()
313
  return code, stdout + "\n--- stderr ---\n" + stderr
314
 
315
 
 
349
  if code is None:
350
  return 0, "timed out while building or checking the submission"
351
  tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:]
352
+ if out_of_disk(out):
353
+ return 0, "rejected: the build ran out of disk space (10 GB) | " + " | ".join(tail)[-3000:]
354
  if out_of_memory(out):
355
  return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:]
356
  return 0, "rejected: " + " | ".join(tail)[-4000:]
 
365
  task = json.loads((TESTS / "task.json").read_text())
366
  details: dict = {"task": task["challenge"], "started_at": time.time()}
367
  reward: int | None = None
368
+ log = ""
369
  try:
370
  RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True)
371
  deadline = time.time() + int(task["grade_timeout_sec"])
 
380
  # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one,
381
  # in a fresh directory: the first attempt's .lake was written by the submission's own
382
  # build and must not be trusted for the challenge.
383
+ shutil.rmtree(run, ignore_errors=True)
384
  run = fresh_run(task)
385
  unpack_submission(run)
386
  code, out = run_comparator(run, int(deadline - time.time()), threads="1")
387
  log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out
388
  kill_grader()
389
  details["retried_single_thread"] = True
 
390
  reward, details["reason"] = classify(code, out)
391
  details["comparator_exit"] = code
392
  except Rejected as exc:
393
  reward, details["reason"] = 0, f"rejected: {exc}"
394
  except GradingError as exc:
395
  reward, details["reason"] = None, f"grading error: {exc}"
396
+ except Exception as exc:
397
+ reward, details["reason"] = None, f"grading error: {type(exc).__name__}: {exc}"
398
  finally:
399
  try:
400
  kill_grader()
401
  except GradingError as exc:
402
  reward, details["reason"] = None, f"grading error: {exc}"
403
+ # Free the build before writing anything. A build that filled the disk would otherwise
404
+ # make these writes fail, and with no space left the sandbox cannot report that the
405
+ # verifier exited, so Harbor waits until its own timeout and records no verdict.
406
+ shutil.rmtree(RUN_ROOT, ignore_errors=True)
407
  details["reward"] = reward
408
  details["finished_at"] = time.time()
409
+ (VERIFIER_DIR / "comparator.log").write_text(log)
410
  (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2))
411
  print(json.dumps(details, indent=2))
412
  if reward is not None: