File size: 32,655 Bytes
7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 4c75eda 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 4c75eda 7d4a064 4c75eda 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 c651d25 7d4a064 4c75eda 7d4a064 4c75eda 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 fc5bee1 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 c651d25 7d4a064 c651d25 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 c651d25 7d4a064 c651d25 7d4a064 c651d25 7d4a064 c651d25 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 4c75eda ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 7d4a064 ea72eb7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 | # Classification Fields Environment for OpenEnv (v2).
#
# An RL environment for arXiv:2605.07119 "Classification Fields: Arbitrarily
# Fine Recursive Hierarchical Clustering From Few Examples" with two modes:
#
# mode="easy" (opt-in) — the v1 task: reproduce Table 1 of arXiv:2605.07119
# with `run_reproduction` and submit it. Kept exactly
# as in v1.
# mode="hard" (DEFAULT) — procedurally generated task: every episode seed
# generates a NEW random smooth nonlinear IFS
# hierarchy (the paper's own random_nonlinear_ifs
# family, official repo cb52f15). The agent only
# receives levels 0-2 and must predict the ordered
# point sets at levels 3-5. The server holds the
# hidden ground truth, computes the ordered MSE and
# normalizes the reward with a log-ratio scale: the
# paper's affine residual predictor = 0, the paper's
# CFP = 1, up to 3 (log-ratio, v2.2 — the previous
# linear scale saturated at its 1.2 cap under exact
# least-squares agents and could not separate
# strong agents).
#
# Hard mode has NO run_reproduction: the answer cannot be looked up, it must
# be researched and predicted.
from __future__ import annotations
import threading
from typing import Any, Dict, Optional
from uuid import uuid4
try:
# In-repo imports (when running from the OpenEnv repository)
from openenv.core.env_server.mcp_environment import MCPEnvironment
from openenv.core.env_server.mcp_types import CallToolAction, CallToolObservation
from openenv.core.env_server.types import Action, Observation, State
except ImportError:
# Standalone imports (when the environment is standalone with openenv from pip)
from openenv.core.env_server.mcp_environment import MCPEnvironment
from openenv.core.env_server.mcp_types import CallToolAction, CallToolObservation
from openenv.core.env_server.types import Action, Observation, State
from fastmcp import FastMCP
from .ifs_core import (
DEPTH,
EVAL_BASE,
NUM_EVAL_SEEDS,
OBSERVED_LEVELS,
PREDICT_LEVELS,
PRACTICE_MAX,
PRACTICE_MIN,
RUN_PYTHON_MAX_CALLS,
RUN_PYTHON_TIMEOUT_S,
episode_anchors,
generate_hierarchy,
load_eval_salt,
ordered_mse_levels,
parse_predictions,
parse_seed_address,
resolve_eval_address,
reward_from_mses,
)
from .reference_table import (
BENCHMARKS,
CORRECT_VERDICT,
METHODS,
OFFICIAL_COMMIT,
OFFICIAL_REPO,
PAPER_ID,
PAPER_URL,
REFERENCE_CELLS,
VERDICT_OPTIONS,
VERIFIED_REPRO_SPACE,
cell_tolerance,
score_submission,
)
from .runner import RUN_BUDGET_SECONDS, run_official_reproduction
# Tool-call durations: run_reproduction is a multi-minute CPU job; run_python
# is capped at 120 s per call. Both exceed the 60 s default MCP tool timeout,
# so they get an explicit raised timeout.
RUN_PYTHON_TOOL_TIMEOUT_S = RUN_PYTHON_TIMEOUT_S + 60.0
LONG_TOOLS = {"run_reproduction", "run_python"}
HARD_MODE = "hard"
EASY_MODE = "easy"
def _hard_task_text() -> str:
return (
"A NEW random smooth nonlinear IFS hierarchy has been generated for this "
"episode seed (same construction family as the paper's Sierpinski/Cantor/"
"Koch benchmarks of arXiv:2605.07119, official repo cb52f15: random "
"affine contractions + a small sinusoidal warp per map). You receive "
"ONLY levels 0-2 via get_training_levels. Predict the ordered point "
"sets at levels 3, 4 and 5 (K children per parent, parent-by-parent "
"slot order: levels[l][j*K+k] is the k-th child of parent j) and submit "
"them with submit_predictions. The server holds the hidden ground "
"truth and scores the ordered MSE (mean over levels 3-5) itself. "
"Reward = clip(log(MSE_affine/MSE_agent) / log(MSE_affine/MSE_cfp), 0, 3), "
"where both anchors are computed by the server for YOUR seed with the "
"paper's own protocol (Adam-trained LinearHRG / HRGMLP on the observed "
"levels 0-2, 2000 epochs, lr 1e-3): the affine predictor scores 0, the "
"CFP scores 1, and every further factor-of-k MSE improvement counts the "
"same up to the cap of 3. Research the method "
"(get_paper_summary), fit the residual rule on the observed levels with "
"run_python, and roll out autoregressively. CPU-only; episodes run in "
"under 10 minutes."
)
class ClassificationFieldsEnvironment(MCPEnvironment):
"""OpenEnv environment for arXiv:2605.07119 with easy and hard modes.
Easy-mode tools (mode="easy"):
- ``get_task``: the full task description and reward rubric.
- ``get_paper_summary``: method context from arXiv:2605.07119.
- ``get_submission_schema``: the exact ``submit_table`` payload format.
- ``run_reproduction``: runs the official repo's nonlinear IFS suite at the
pinned commit on CPU and returns the Table 1 cells.
- ``submit_table``: deterministic, checkable scoring of the reproduced
Table 1.
Hard-mode tools (mode="hard", the default):
- ``get_task`` / ``get_paper_summary``: task and method context.
- ``get_training_levels``: levels 0-2 of this episode's hierarchy.
- ``run_python``: sandboxed CPU Python (numpy+torch), 120 s per call,
30 calls per episode.
- ``submit_predictions``: submit predicted levels 3-5; ends the episode
with the normalized reward.
"""
SUPPORTS_CONCURRENT_SESSIONS = True
def __init__(self) -> None:
mcp = FastMCP("classification_fields_env")
# Per-episode state. One env instance serves one HTTP session.
self._lock = threading.Lock()
self._mode = HARD_MODE
# Easy-mode (v1) state.
self._run_result: Optional[Dict[str, Any]] = None
self._submitted = False
self._final_reward: Optional[float] = None
# Hard-mode state.
self._hard: Optional[Dict[str, Any]] = None
self._py_calls_used = 0
self._hard_submitted = False
self._hard_final_reward: Optional[float] = None
self._hard_report: Dict[str, Any] = {}
def _require_mode(tool_name: str, required: str) -> None:
if self._mode != required:
raise ValueError(
f"tool '{tool_name}' is only available in mode='{required}'; "
f"this episode is mode='{self._mode}'. Reset with "
f"mode='{required}' to switch."
)
# ------------------------------------------------------------------
# Mode-agnostic tools
# ------------------------------------------------------------------
@mcp.tool
def get_task() -> dict:
"""Get the task description and reward rubric for the current episode mode (hard by default, easy opt-in)."""
if self._mode == HARD_MODE:
ep = self._hard or {}
return {
"paper": PAPER_ID,
"paper_url": PAPER_URL,
"mode": HARD_MODE,
"seed_address": ep.get("seed_address"),
"seed_kind": ep.get("seed_kind"),
"eval_version": ep.get("eval_version"),
"task": _hard_task_text(),
"reward_formula": (
"clip(log(MSE_affine/MSE_agent) / log(MSE_affine/MSE_cfp), 0, 3)"
),
"reward_rubric": (
"Ordered MSE (mean over levels 3-5) of your submitted "
"predictions, scored by the server against hidden ground "
"truth. The paper's affine residual predictor on your "
"seed = 0.0; the paper's CFP on your seed = 1.0; the "
"log-ratio scale caps at 3 (a factor-of-k MSE "
"improvement counts the same at any depth). Both "
"anchors use the paper's own protocol (Adam, 2000 "
"epochs) on the observed levels only."
),
"seed_namespaces": {
"practice": (
f"addresses {PRACTICE_MIN}..{PRACTICE_MAX} (public; "
"full recipe is public, good for developing)"
),
"eval": (
f"addresses {EVAL_BASE}..{EVAL_BASE + NUM_EVAL_SEEDS - 1} "
"(hidden parameters, salt-derived; this is the "
"reported benchmark)"
),
},
"official_repo": OFFICIAL_REPO,
"official_commit": OFFICIAL_COMMIT,
"budget": {
"run_python_seconds_per_call": RUN_PYTHON_TIMEOUT_S,
"run_python_calls_per_episode": RUN_PYTHON_MAX_CALLS,
"episode_wall_clock_target_s": 600,
},
}
return {
"paper": PAPER_ID,
"paper_url": PAPER_URL,
"mode": EASY_MODE,
"task": (
"Reproduce Table 1 of arXiv:2605.07119 (Classification Fields): "
"the nonlinear IFS benchmarks. For each of the three benchmarks "
"(Sierpinski triangle, Cantor dust, Koch curve) report the "
"ordered MSE (x 1e-3, mean over evaluation levels 3-5 and over "
"5 seeds) of the paper's Classification Field Predictor (CFP) "
"and of the affine residual predictor, trained on levels 0-2 "
"and rolled out to levels 3-5. Then state the paper's verdict."
),
"reward_rubric": (
"Deterministic and checkable. Each of the 6 benchmark cells "
"(3 benchmarks x {cfp, affine}) earns 0.8/6 of the reward if it "
"is within tolerance of the paper's number "
"(|submitted - paper_mean| <= max(2 * paper_std, 0.20 * paper_mean)). "
"The verdict earns the remaining 0.2. Full credit (1.0) requires "
"the verdict AND all three benchmarks to match. Everything runs "
"on CPU in under 15 minutes per episode."
),
"verdict_options": list(VERDICT_OPTIONS),
"official_repo": OFFICIAL_REPO,
"official_commit": OFFICIAL_COMMIT,
"verified_reproduction_space": VERIFIED_REPRO_SPACE,
}
@mcp.tool
def get_paper_summary() -> dict:
"""Get method context from arXiv:2605.07119: CFG -> CFP, affine baseline, protocol, and the hard-mode IFS construction."""
return {
"paper": PAPER_ID,
"title": (
"Classification Fields: Arbitrarily Fine Recursive Hierarchical "
"Clustering From Few Examples"
),
"method": (
"A Classification Field Generator (CFG) is a local rule mapping "
"each parent cluster centre to an ordered K-tuple of child "
"residuals: x_{ak} = x_a + s^(|a|+1) * r(x_a)_k. Given only the "
"observed hierarchy prefix (levels 0-2), a Classification Field "
"Predictor (CFP) - a neural network approximating the residual "
"rule r^ - is trained and then rolled out recursively to depths "
"the predictor never saw (each level's inputs are the model's "
"OWN predictions). The affine residual predictor (a linear map "
"trained with Adam) is the paper's main baseline."
),
"table_1_protocol": (
"Nonlinear IFS benchmarks (Sierpinski triangle, Cantor dust, "
"Koch curve). Train on levels 0-2; evaluate rollout ordered MSE "
"on levels 3, 4, 5; 5 seeds (5000-5004); 2000 epochs per model; "
"metric reported in units of 1e-3."
),
"hard_mode_construction": (
"Hard-mode hierarchies are drawn from the same family as the "
"paper's benchmarks (official repo cb52f15): each of the K maps "
"is a random affine contraction (c ~ U(0.20, 0.38), rotation, "
"translation ~ U(-0.45, 0.45)^2) plus a small sinusoidal warp "
"(amp ~ U(0.055, 0.085), random directions scaled U(2.5, 3.5)), "
"exactly the paper's random_nonlinear_ifs recipe. Scale s = 1.0, "
"d = 2, root x0 = (0, 0), K in {3, 4}. The learned rule is "
"r_hat(x)_k = f_k(x) - x."
),
"hard_mode_scoring": (
"Ordered MSE: mean((pred - true)^2) per level over all points "
"and coordinates, in parent-by-parent slot order (no "
"alignment), averaged over levels 3-5. The server's anchors "
"are trained on the same observed levels you get, with the "
"paper's protocol (Adam lr 1e-3, 2000 epochs, loss = sum of "
"squared errors over predicted children). Both anchors are "
"trained with the PUBLISHED seed torch.manual_seed(0), so "
"they are exactly reproducible: a solution replicating the "
"paper's CFP protocol with that seed earns exactly 1.0, and "
"an affine-baseline solution earns exactly 0.0."
),
"verdict": (
"The CFP's level-3-5 rollout MSE is >= 10x lower than the "
"affine residual predictor on all three benchmarks "
"(Sierpinski ~18x, Cantor dust ~34x, Koch curve ~13x)."
),
"caveat": (
"The affine anchor is the paper's Adam-2000 fit, which is "
"under-trained. A correctly fitted least-squares affine model "
"(regress the residuals Y - X on [x, 1] per slot, then roll "
"out) can beat the CFP and earn reward above 1."
),
}
# ------------------------------------------------------------------
# Easy-mode-only tools (v1, unchanged behaviour)
# ------------------------------------------------------------------
@mcp.tool
def get_submission_schema() -> dict:
"""Get the exact submit_table payload schema (easy mode only)."""
_require_mode("get_submission_schema", EASY_MODE)
return {
"tool": "submit_table",
"verdict": list(VERDICT_OPTIONS),
"cells": {
benchmark: {method: "<ordered MSE x 1e-3, mean over levels 3-5 "
"and 5 seeds>" for method in METHODS}
for benchmark in BENCHMARKS
},
"example_correct_shape": {
"verdict": CORRECT_VERDICT,
"cells": {
"sierpinski": {"cfp": 0.90, "affine": 16.46},
"cantor_dust": {"cfp": 0.47, "affine": 16.15},
"koch_curve": {"cfp": 0.71, "affine": 9.13},
},
"note": "values shown are illustrative; run the pipeline for yours",
},
}
@mcp.tool
def run_reproduction() -> dict:
"""Run the official nonlinear IFS suite (Table 1 of arXiv:2605.07119) on CPU at the pinned commit and return the Table 1 cells (easy mode only). Takes several minutes; results are cached for the episode."""
_require_mode("run_reproduction", EASY_MODE)
with self._lock:
if self._run_result is not None:
return {
**self._run_result,
"cached": True,
"note": "already ran in this episode; returning cached results",
}
result = run_official_reproduction()
with self._lock:
self._run_result = result
return {**result, "cached": False}
@mcp.tool
def submit_table(verdict: str, cells: dict) -> dict:
"""Submit the reproduced Table 1 of arXiv:2605.07119 for deterministic scoring (easy mode only). Ends the episode with a reward in [0, 1]."""
_require_mode("submit_table", EASY_MODE)
report = score_submission(verdict, cells)
with self._lock:
if self._submitted:
return {
**report,
"reward": self._final_reward,
"already_submitted": True,
}
self._submitted = True
self._final_reward = float(report["reward"])
return report
# ------------------------------------------------------------------
# Hard-mode-only tools
# ------------------------------------------------------------------
@mcp.tool
def get_training_levels() -> dict:
"""Get the observed prefix (levels 0-2) of this episode's nonlinear IFS hierarchy: points, parent indices and slot order. The hidden levels 3-5 stay server-side."""
_require_mode("get_training_levels", HARD_MODE)
ep = self._hard
if ep is None:
raise ValueError(
"no hard-mode episode is active; call reset first"
)
levels, K = ep["levels"], ep["K"]
out_levels: Dict[str, Any] = {}
parent_index: Dict[str, Any] = {}
slot: Dict[str, Any] = {}
for l in OBSERVED_LEVELS:
arr = levels[l]
out_levels[str(l)] = arr.tolist()
parent_index[str(l)] = [-1] * arr.shape[0] if l == 0 else [
idx // K for idx in range(arr.shape[0])
]
slot[str(l)] = list(range(arr.shape[0])) if l == 0 else [
idx % K for idx in range(arr.shape[0])
]
return {
"mode": HARD_MODE,
"seed_address": ep["seed_address"],
"seed_kind": ep["seed_kind"],
"eval_version": ep.get("eval_version"),
"K": K,
"d": ep["d"],
"depth": DEPTH,
"x0": [float(v) for v in ep["x0"]],
"scale": ep["scale"],
"levels": out_levels,
"parent_index": parent_index,
"slot": slot,
"convention": (
"levels[l][j*K+k] is the k-th child of parent j at level l-1; "
"child = parent + scale^l * r(parent)_k with scale=1.0, i.e. "
"child = f_k(parent)"
),
"predict_levels": list(PREDICT_LEVELS),
"budget": {
"run_python_seconds_per_call": RUN_PYTHON_TIMEOUT_S,
"run_python_calls_per_episode": RUN_PYTHON_MAX_CALLS,
},
"note": (
"Ground truth for levels 3-5 is held server-side and never "
"returned. Predict them with submit_predictions."
),
}
@mcp.tool
def run_python(code: str) -> dict:
"""Run short analysis Python (numpy/torch available) in a sandboxed CPU subprocess: no network variables, no repo files, 120 s per call, 30 calls per episode (hard mode only)."""
_require_mode("run_python", HARD_MODE)
with self._lock:
if self._py_calls_used >= RUN_PYTHON_MAX_CALLS:
raise ValueError(
f"run_python budget exhausted: {RUN_PYTHON_MAX_CALLS} calls "
"per episode"
)
self._py_calls_used += 1
calls_used = self._py_calls_used
result = self._run_sandboxed_python(code)
result["calls_used"] = calls_used
result["calls_remaining"] = RUN_PYTHON_MAX_CALLS - calls_used
return result
@mcp.tool
def submit_predictions(predictions: dict) -> dict:
"""Submit predicted levels 3, 4 and 5 (ordered point sets) for server-side scoring against hidden ground truth (hard mode only). Ends the episode with the normalized reward."""
_require_mode("submit_predictions", HARD_MODE)
ep = self._hard
if ep is None:
raise ValueError("no hard-mode episode is active; call reset first")
pred = parse_predictions(predictions, ep["K"])
per_level, mse_agent = ordered_mse_levels(pred, ep["levels"])
with self._lock:
if self._hard_submitted:
return {
**self._hard_report,
"already_submitted": True,
}
anchors = episode_anchors(ep)
reward, note = reward_from_mses(
mse_agent, anchors["affine_mse"], anchors["cfp_mse"]
)
report = {
"reward": reward,
"note": note,
"seed_address": ep["seed_address"],
"seed_kind": ep["seed_kind"],
"eval_version": ep.get("eval_version"),
"K": ep["K"],
"mse_agent_per_level": {str(k): v for k, v in per_level.items()},
"mse_agent_mean": mse_agent,
"mse_affine": anchors["affine_mse"],
"mse_cfp": anchors["cfp_mse"],
"anchors": (
"paper's Adam-trained affine residual predictor / CFP on "
"the observed levels, 2000 epochs"
),
}
self._hard_report = report
self._hard_submitted = True
self._hard_final_reward = reward
return report
super().__init__(mcp)
self._state = State(episode_id=str(uuid4()), step_count=0)
# ------------------------------------------------------------------
# Sandbox for run_python
# ------------------------------------------------------------------
@staticmethod
def _run_sandboxed_python(code: str) -> Dict[str, Any]:
"""Execute ``code`` in an isolated CPU subprocess (numpy+torch venv).
Resource limits: 120 s wall clock, RLIMIT_CPU 130 s, 2 GB address
space, 10 MB file size, no core dumps. Environment variables are
stripped (no tokens, no repo paths) and the working directory is a
throwaway temp dir. Note: network access is not hard-blocked by this
sandbox; no credentials are reachable from it.
"""
import os
import resource
import signal
import subprocess
import tempfile
import time
if not isinstance(code, str) or not code.strip():
raise ValueError("code must be a non-empty string")
def _limits() -> None:
resource.setrlimit(
resource.RLIMIT_CPU, (int(RUN_PYTHON_TIMEOUT_S) + 10, 130)
)
resource.setrlimit(resource.RLIMIT_AS, (2 * 1024**3, 2 * 1024**3))
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
resource.setrlimit(resource.RLIMIT_FSIZE, (10 * 1024**2, 10 * 1024**2))
resource.setrlimit(resource.RLIMIT_NPROC, (64, 64))
os.setsid()
env = {
"PATH": "/usr/bin:/bin:/usr/local/bin",
"HOME": "/tmp",
"TMPDIR": "/tmp",
"PYTHONDONTWRITEBYTECODE": "1",
"PYTHONHASHSEED": "0",
"OMP_NUM_THREADS": "1",
"MKL_NUM_THREADS": "1",
"OPENBLAS_NUM_THREADS": "1",
}
started = time.time()
import sys
proc = subprocess.Popen(
[sys.executable, "-I", "-c", code],
cwd=tempfile.mkdtemp(prefix="cf-runpy-"),
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
preexec_fn=_limits,
)
timed_out = False
try:
stdout, _ = proc.communicate(timeout=RUN_PYTHON_TIMEOUT_S)
except subprocess.TimeoutExpired:
timed_out = True
try:
os.killpg(proc.pid, signal.SIGKILL)
except ProcessLookupError:
pass
stdout, _ = proc.communicate()
elapsed = time.time() - started
stdout = (stdout or "")[-6000:]
result = {
"returncode": proc.returncode,
"stdout": stdout,
"elapsed_s": round(elapsed, 2),
}
if timed_out:
result["error"] = (
f"exceeded the {RUN_PYTHON_TIMEOUT_S:.0f}s per-call budget and "
"was killed"
)
return result
# ------------------------------------------------------------------
# OpenEnv Environment interface
# ------------------------------------------------------------------
def reset(
self,
seed: Optional[int] = None,
episode_id: Optional[str] = None,
mode: str = HARD_MODE,
**kwargs: Any,
) -> Observation:
"""Reset the episode. mode="hard" (default) starts a procedurally
generated prediction task at ``seed`` (practice 0..99, hidden eval
100..109); mode="easy" starts the v1 Table 1 reproduction task."""
mode = str(mode).strip().lower()
if mode not in (HARD_MODE, EASY_MODE):
raise ValueError(f"mode must be '{EASY_MODE}' or '{HARD_MODE}', got {mode!r}")
with self._lock:
self._mode = mode
self._run_result = None
self._submitted = False
self._final_reward = None
self._hard = None
self._py_calls_used = 0
self._hard_submitted = False
self._hard_final_reward = None
self._hard_report = {}
self._state = State(
episode_id=episode_id or str(uuid4()),
step_count=0,
)
if mode == EASY_MODE:
return Observation(
done=False,
reward=0.0,
metadata={
"status": "ready",
"mode": EASY_MODE,
"task": (
f"Reproduce Table 1 of {PAPER_ID} (Classification Fields): "
"nonlinear IFS benchmarks, CFP vs affine residual predictor, "
"ordered MSE (x 1e-3) at levels 3-5 over 5 seeds. Partial "
"credit per benchmark cell within tolerance; full credit when "
"the verdict and all three benchmarks match. CPU-only, under "
"15 minutes. Start with the get_task tool."
),
"reward_range": [0.0, 1.0],
},
)
# Hard mode: build the procedural episode.
if seed is None:
seed = 0 # deterministic default: public practice address 0
kind, address = parse_seed_address(seed)
if kind == "practice":
params_seed = 5000 + address
episode = generate_hierarchy(params_seed)
else:
salt_info = load_eval_salt()
if salt_info is None:
raise ValueError(
"eval seeds are unavailable: EVAL_SALT is not set and the "
"private salt repo could not be read. Use a practice seed "
f"({PRACTICE_MIN}..{PRACTICE_MAX}) or configure EVAL_SALT / "
"EVAL_SALT_VERSION."
)
eval_version, salt = salt_info
params_seed, k = resolve_eval_address(address, salt)
episode = generate_hierarchy(params_seed, K=k)
episode["eval_version"] = eval_version
episode["seed_address"] = address
episode["seed_kind"] = kind
with self._lock:
self._hard = episode
return Observation(
done=False,
reward=0.0,
metadata={
"status": "ready",
"mode": HARD_MODE,
"seed_address": address,
"seed_kind": kind,
"K": episode["K"],
"task": (
"Predict levels 3-5 of a hidden nonlinear IFS hierarchy from "
"its observed levels 0-2 (mode=hard). Start with the "
"get_training_levels tool; ground truth is server-held."
),
"reward_range": [0.0, 3.0],
},
)
def _step_impl(
self,
action: Action,
timeout_s: Optional[float] = None,
**kwargs: Any,
) -> Observation:
"""Handle non-MCP actions (this env is MCP-only)."""
return Observation(
done=False,
reward=0.0,
metadata={
"error": (
f"Unknown action type: {type(action).__name__}. Use "
"ListToolsAction or CallToolAction for MCP interactions."
)
},
)
def _effective_timeout(
self, action: Action, timeout_s: Optional[float]
) -> Optional[float]:
"""Raise the default MCP tool timeout for the long-running tools."""
if (
isinstance(action, CallToolAction)
and action.tool_name in LONG_TOOLS
and timeout_s is None
):
if action.tool_name == "run_reproduction":
return RUN_BUDGET_SECONDS + 60.0
return RUN_PYTHON_TOOL_TIMEOUT_S
return timeout_s
def _finalize(self, obs: Observation, action: Action) -> Observation:
"""Attach the reward to a successful submit_* call."""
if not isinstance(action, CallToolAction):
return obs
if action.tool_name not in ("submit_table", "submit_predictions"):
return obs
if getattr(obs, "error", None) is not None:
return obs
data = getattr(obs.result, "data", None)
if isinstance(data, dict) and "reward" in data:
already = data.get("already_submitted", False)
return CallToolObservation(
tool_name=action.tool_name,
result=obs.result,
reward=None if already else float(data["reward"]),
done=not already,
metadata={
"score_details": data,
"paper": PAPER_ID,
"mode": self._mode,
},
)
return obs
def step(
self,
action: Action,
timeout_s: Optional[float] = None,
**kwargs: Any,
) -> Observation:
"""Execute a step; MCP actions are routed by the base class."""
self._state.step_count += 1
obs = super().step(
action, timeout_s=self._effective_timeout(action, timeout_s), **kwargs
)
return self._finalize(obs, action)
async def step_async(
self,
action: Action,
timeout_s: Optional[float] = None,
**kwargs: Any,
) -> Observation:
"""Async step used by the WebSocket handler."""
self._state.step_count += 1
obs = await super().step_async(
action, timeout_s=self._effective_timeout(action, timeout_s), **kwargs
)
return self._finalize(obs, action)
@property
def state(self) -> State:
"""Current episode state."""
return self._state
|