rl-env-2605.07119-classification-fields / server /classification_fields_environment.py
ArnavM10's picture
surface eval_version in get_task/get_training_levels/submit report
c651d25 verified
Raw History Blame Contribute Delete
32.7 kB
# 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