|
| 1 | +"""FrontierCS 2 task limits shared by the solver inputs and local controller.""" |
| 2 | + |
| 3 | +from dataclasses import dataclass |
| 4 | +import math |
| 5 | +from pathlib import Path |
| 6 | +import re |
| 7 | +import tomllib |
| 8 | + |
| 9 | + |
| 10 | +def _integer(name: str, value: object, minimum: int) -> int: |
| 11 | + if type(value) is not int or value < minimum: |
| 12 | + raise ValueError(f"{name} must be an integer >= {minimum}") |
| 13 | + return value |
| 14 | + |
| 15 | + |
| 16 | +def _merged_table(defaults: dict, task: dict, name: str) -> dict: |
| 17 | + inherited, overrides = defaults.get(name, {}), task.get(name, {}) |
| 18 | + if not isinstance(inherited, dict) or not isinstance(overrides, dict): |
| 19 | + raise ValueError(f"{name} must be a table") |
| 20 | + return inherited | overrides |
| 21 | + |
| 22 | + |
| 23 | +@dataclass(frozen=True) |
| 24 | +class TrialLimits: |
| 25 | + answering_seconds: int | None |
| 26 | + max_train_calls: int |
| 27 | + max_train_wall_seconds: int |
| 28 | + eval_timeout_seconds: int |
| 29 | + max_payload_bytes: int |
| 30 | + |
| 31 | + def __post_init__(self) -> None: |
| 32 | + if self.answering_seconds is not None: |
| 33 | + _integer("answering_seconds", self.answering_seconds, 1) |
| 34 | + _integer("max_train_calls", self.max_train_calls, 0) |
| 35 | + _integer("max_train_wall_seconds", self.max_train_wall_seconds, 0) |
| 36 | + _integer("eval_timeout_seconds", self.eval_timeout_seconds, 1) |
| 37 | + _integer("max_payload_bytes", self.max_payload_bytes, 1) |
| 38 | + |
| 39 | + @classmethod |
| 40 | + def from_task( |
| 41 | + cls, |
| 42 | + task_path: Path, |
| 43 | + defaults_path: Path, |
| 44 | + *, |
| 45 | + natural: bool = False, |
| 46 | + answering_seconds: int | None = None, |
| 47 | + ) -> "TrialLimits": |
| 48 | + with task_path.open("rb") as stream: |
| 49 | + task = tomllib.load(stream) |
| 50 | + with defaults_path.open("rb") as stream: |
| 51 | + defaults = tomllib.load(stream) |
| 52 | + if task.get("schema") != "frontier.task/v1": |
| 53 | + raise ValueError("Expected a frontier.task/v1 definition") |
| 54 | + quota = _merged_table(defaults, task, "quota") |
| 55 | + submission = _merged_table(defaults, task, "submission") |
| 56 | + native_answering = _integer("wall_time_seconds", quota.get("wall_time_seconds"), 1) |
| 57 | + if natural and answering_seconds is not None: |
| 58 | + raise ValueError("A natural trial cannot declare an answering limit") |
| 59 | + effective_answering = answering_seconds if answering_seconds is not None else native_answering |
| 60 | + return cls( |
| 61 | + None if natural else effective_answering, |
| 62 | + _integer("max_train_calls", quota.get("max_train_calls"), 0), |
| 63 | + _integer("max_train_wall_seconds", quota.get("max_train_wall_seconds"), 0), |
| 64 | + _integer("eval_timeout_seconds", quota.get("eval_timeout_seconds"), 1), |
| 65 | + _integer("max_bytes", submission.get("max_bytes"), 1), |
| 66 | + ) |
| 67 | + |
| 68 | + def answering_deadline(self, started_at: float) -> float | None: |
| 69 | + if not math.isfinite(started_at): |
| 70 | + raise ValueError("Answering time requires a finite start timestamp") |
| 71 | + return None if self.answering_seconds is None else started_at + self.answering_seconds |
| 72 | + |
| 73 | + def answering_remaining(self, deadline: float | None, now: float) -> float | None: |
| 74 | + if (deadline is None) != (self.answering_seconds is None): |
| 75 | + raise ValueError("Answering deadline disagrees with the trial policy") |
| 76 | + if not math.isfinite(now) or (deadline is not None and not math.isfinite(deadline)): |
| 77 | + raise ValueError("Trial timestamps must be finite") |
| 78 | + return None if deadline is None else max(0.0, deadline - now) |
| 79 | + |
| 80 | + def train_timeout(self, *, spent: float, deadline: float | None, now: float) -> int: |
| 81 | + if not math.isfinite(spent) or spent < 0: |
| 82 | + raise ValueError("Spent Train time must be finite and nonnegative") |
| 83 | + remaining = self.max_train_wall_seconds - spent |
| 84 | + answering = self.answering_remaining(deadline, now) |
| 85 | + if answering is not None: |
| 86 | + remaining = min(remaining, answering) |
| 87 | + return max(0, int(remaining)) |
| 88 | + |
| 89 | + def final_payload(self, *, explicit: str | None, saved: str | None, cancelled: bool) -> str | None: |
| 90 | + if cancelled: |
| 91 | + return None |
| 92 | + return explicit or (saved if self.answering_seconds is not None else None) |
| 93 | + |
| 94 | + def render_limits(self) -> str: |
| 95 | + if self.answering_seconds is None: |
| 96 | + answering = "- This trial has no overall answering deadline." |
| 97 | + else: |
| 98 | + answering = ( |
| 99 | + f"- The answering phase allows **{self.answering_seconds} seconds**," |
| 100 | + " including planning, solver work, and any overlapping Train." |
| 101 | + ) |
| 102 | + return "\n".join(( |
| 103 | + answering, |
| 104 | + f"- At most **{self.max_train_calls} Train calls** and " |
| 105 | + f"**{self.max_train_wall_seconds} seconds** of cumulative Train verifier time." |
| 106 | + " These are ceilings. Each accepted request consumes one call even if verification fails." |
| 107 | + " Only one Train may be queued or running. A concurrent request is rejected without a charge." |
| 108 | + " A Train uses the remaining verifier allowance, bounded by any answering deadline.", |
| 109 | + f"- Final evaluation has a separate **{self.eval_timeout_seconds}-second** allowance." |
| 110 | + " It runs after answering closes and does not consume Train time or calls." |
| 111 | + " The final submission command returns acceptance rather than the evaluation score.", |
| 112 | + f"- Each submitted archive may contain up to **{self.max_payload_bytes} bytes**.", |
| 113 | + )) |
| 114 | + |
| 115 | + def render_submission_policy(self) -> str: |
| 116 | + if self.answering_seconds is None: |
| 117 | + return ( |
| 118 | + "Saving keeps a candidate snapshot and returns `null` for `remaining_runtime_s`." |
| 119 | + " Finish by submitting an explicit final and exiting." |
| 120 | + " An interrupted attempt without an explicit final retains its evidence for analysis." |
| 121 | + ) |
| 122 | + return ( |
| 123 | + "Saving keeps a candidate snapshot and returns the remaining answering seconds." |
| 124 | + " An accepted explicit final takes precedence." |
| 125 | + " On normal exit, a deadline, or a crash, the controller may use the last accepted save." |
| 126 | + " Operator cancellation stops automatic final evaluation." |
| 127 | + ) |
| 128 | + |
| 129 | + |
| 130 | +LIMITS_SLOT = "<!-- frontiercs2:trial-limits -->" |
| 131 | +SUBMISSION_POLICY_SLOT = "<!-- frontiercs2:submission-policy -->" |
| 132 | +_LIMITS_SECTION = re.compile(r"^## Limits[ \t]*\n(?P<body>.*?)(?=^## |\Z)", re.MULTILINE | re.DOTALL) |
| 133 | +_STOCK_QUOTA_LABELS = ( |
| 134 | + re.compile(r"- \*\*\d+ train calls\*\*;"), |
| 135 | + re.compile(r"- Cumulative train wall time:"), |
| 136 | + re.compile(r"- Only one train runs at a time:"), |
| 137 | + re.compile(r"- These limits are ceilings,"), |
| 138 | + re.compile(r"- The overall answering window is "), |
| 139 | + re.compile(r"- Final evaluation has a separate "), |
| 140 | +) |
| 141 | +_STOCK_STORAGE_RUNTIME = re.compile( |
| 142 | + r"^The JSON returns `remaining_runtime_s` \(Agent time remaining\) and\n" |
| 143 | + r"`remaining_checkpoint_submissions`.*?Agent-time limits still apply\.$", |
| 144 | + re.MULTILINE | re.DOTALL, |
| 145 | +) |
| 146 | +_STOCK_FINAL_POLICY = re.compile( |
| 147 | + r"^If no explicit final submission was accepted .*?(?=\n\nIterate only while useful\.)", |
| 148 | + re.MULTILINE | re.DOTALL, |
| 149 | +) |
| 150 | + |
| 151 | + |
| 152 | +def render_task_instructions(source: str, limits: TrialLimits) -> str: |
| 153 | + """Render a task template or the generated Limits block in existing task images.""" |
| 154 | + if LIMITS_SLOT not in source: |
| 155 | + sections = list(_LIMITS_SECTION.finditer(source)) |
| 156 | + if len(sections) != 1: |
| 157 | + raise ValueError("Expected one native Limits section or an explicit trial-limits slot") |
| 158 | + section = sections[0] |
| 159 | + body = section["body"] |
| 160 | + bullets = list(re.finditer(r"^- .+", body, re.MULTILINE)) |
| 161 | + matches = [ |
| 162 | + idx for idx in range(len(bullets) - len(_STOCK_QUOTA_LABELS) + 1) |
| 163 | + if all(label.match(bullets[idx + offset].group()) |
| 164 | + for offset, label in enumerate(_STOCK_QUOTA_LABELS)) |
| 165 | + ] |
| 166 | + if len(matches) != 1: |
| 167 | + raise ValueError("Unexpected native quota block; provide an explicit trial-limits slot") |
| 168 | + first = matches[0] |
| 169 | + last = first + len(_STOCK_QUOTA_LABELS) - 1 |
| 170 | + start = section.start("body") + bullets[first].start() |
| 171 | + # The generated quota bullets are contiguous with indented wrapped lines. |
| 172 | + end = section.start("body") + bullets[last].end() |
| 173 | + continuation = re.match(r"(?:\n[ \t]+[^ \t\n][^\n]*)*", source[end:]) |
| 174 | + end += continuation.end() |
| 175 | + between = source[start:end] |
| 176 | + if any(line and not line.startswith(("- ", " ", "\t")) for line in between.splitlines()): |
| 177 | + raise ValueError("Native quota block contains additional text; provide an explicit trial-limits slot") |
| 178 | + source = source[:start] + LIMITS_SLOT + source[end:] |
| 179 | + if source.count(LIMITS_SLOT) != 1: |
| 180 | + raise ValueError("Expected exactly one Frontier trial-limits slot") |
| 181 | + return source.replace(LIMITS_SLOT, limits.render_limits()) |
| 182 | + |
| 183 | + |
| 184 | +def render_submission_skill(source: str, limits: TrialLimits) -> str: |
| 185 | + """Apply the same policy to a template or the standard native submission skill.""" |
| 186 | + if SUBMISSION_POLICY_SLOT not in source: |
| 187 | + source, policy_blocks = _STOCK_FINAL_POLICY.subn(SUBMISSION_POLICY_SLOT, source) |
| 188 | + source, storage_blocks = _STOCK_STORAGE_RUNTIME.subn( |
| 189 | + "The JSON reports `remaining_checkpoint_submissions` for the remaining save allowance." |
| 190 | + " A null value means there is no separate save-count quota.", |
| 191 | + source, |
| 192 | + ) |
| 193 | + if policy_blocks != 1 or storage_blocks != 1: |
| 194 | + raise ValueError("Unexpected native skill; provide an explicit submission-policy slot") |
| 195 | + source = source.replace("save a fallback final answer", "save a candidate snapshot") |
| 196 | + if source.count(SUBMISSION_POLICY_SLOT) != 1: |
| 197 | + raise ValueError("Expected exactly one Frontier submission-policy slot") |
| 198 | + return source.replace(SUBMISSION_POLICY_SLOT, limits.render_submission_policy()) |
0 commit comments