Skip to content

Commit 62a8317

Browse files
committed
Merge commit 'd01c512ffc328f69b1e14b551dafaee33075b7ac' into codex/c1-quota-source-cutover-20261118t185602
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
2 parents 37067ba + d01c512 commit 62a8317

7 files changed

Lines changed: 800 additions & 30 deletions

File tree

‎benchmark/frontiercs2/README.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ a separate disposable directory:
4848
```sh
4949
git fetch origin f3aee4586d87b678581a22d23b61fba7e49d4672
5050
FRONTIER_V2_ROOT=$(mktemp -d)
51+
git init -q "$FRONTIER_V2_ROOT"
5152
git archive f3aee4586d87b678581a22d23b61fba7e49d4672 benchmark/frontiercs2-single-host-v1 |
5253
tar -x -C "$FRONTIER_V2_ROOT" --strip-components=2
5354
git -C "$FRONTIER_V2_ROOT" apply --check "$PWD/benchmark/frontiercs2/compatibility/v2.patch"
@@ -74,6 +75,36 @@ coverage. This is transport validation, not campaign sandbox qualification.
7475
No model, task, native evaluator, reference solution or historical candidate
7576
is executed by these checks. Experiment-specific tests remain opt-in here.
7677

78+
## Task-configured timing
79+
80+
For a new local trial, use [TrialLimits](trial_limits.py) to read the pinned
81+
task's `task.toml` and shared `task-defaults.toml`. By default it uses the native
82+
answering duration. Pass `answering_seconds` to set a calibrated duration, or
83+
`natural=True` to observe when the solver submits its final.
84+
85+
Bind the same object to `Trial(..., limits=limits)` and call `start()` at the
86+
beginning of the answering phase. A controller can pass `started_at` to publish
87+
the same timestamp in the launch receipt. Use `render_task_instructions` for the
88+
read-only task README and derive the worker and planner inputs from that file.
89+
Use `render_submission_skill` for the submission guide and project
90+
`limits.max_payload_bytes` to the client's `FRONTIER_MAX_PAYLOAD_BYTES`.
91+
The renderers support the native instruction blocks and explicit
92+
`<!-- frontiercs2:trial-limits -->` and `<!-- frontiercs2:submission-policy -->`
93+
slots in custom templates.
94+
95+
- Give native Train jobs `trial.train_timeout()`. It uses the remaining Train
96+
allowance and any answering deadline. The bridge enforces one in-flight
97+
Train, the call count, and the payload size.
98+
- After the solver and Train worker stop, call `close_answering(cancelled=...)`.
99+
A timed trial can evaluate the last saved candidate when no explicit final
100+
was accepted. Natural trials require an explicit final and return
101+
`remaining_runtime_s: null` when saving a candidate. Explicit cancellation
102+
stops automatic evaluation in both modes.
103+
- Give the selected final `limits.eval_timeout_seconds` after the answering
104+
phase. Recovery requires the original `TrialLimits` and preserves the
105+
recorded clock and selection. The legacy `Trial(...)` and `start(seconds)`
106+
form remains available for existing controllers.
107+
77108
## Controller integration and remaining limits
78109

79110
Use a new trial directory for a new experiment. A v1 inspection-only state file
@@ -125,3 +156,7 @@ v1 or reinterpret the original study as a repaired run.
125156
原进程和原生结果,不能重复评分、补发预算或虚构成本。恢复文件含凭据,只能私有保存。
126157
原始 controller、工作区完整留存和沙箱资格仍未交付;本修复不能补回历史缺失文件和
127158
时间,也不证明 LoopX 的分数或长程效率提升。
159+
160+
新试验由 `TrialLimits` 读取题目与共享默认配置,题面、计划、提交工具和计时使用同一份
161+
配置。可选题目原生时限、校准后的固定时限或自然完成。自然完成需要显式提交 final。
162+
Train 使用题目定义的累计时长和调用次数,终评在答题结束后使用独立时限。

‎benchmark/frontiercs2/compatibility/v2.patch‎

Lines changed: 232 additions & 19 deletions
Large diffs are not rendered by default.

‎benchmark/frontiercs2/compatibility/verify_v2.py‎

Lines changed: 99 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,17 @@
2424
from types import SimpleNamespace
2525
import uuid
2626

27+
# The verifier runs as a script from a checkout that need not install the research adapter.
28+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
29+
30+
from trial_limits import ( # noqa: E402
31+
LIMITS_SLOT,
32+
SUBMISSION_POLICY_SLOT,
33+
TrialLimits,
34+
render_submission_skill,
35+
render_task_instructions,
36+
)
37+
2738
SOURCE: Path
2839
DOCKER_IMAGE: str | None = None
2940

@@ -89,8 +100,95 @@ def restart(self):
89100
port = self.server.server_address[1]
90101
self.stop_server()
91102
self.jobs = queue.Queue()
92-
self.trial = self.bridge_module.Trial(self.root / 'trial', 'fixture', self.jobs)
103+
self.trial = self.bridge_module.Trial(self.trial.root, 'fixture', self.jobs, limits=self.trial.limits)
104+
self.start_server(port)
105+
106+
def start_configured(self, limits, *, started_at=None):
107+
port = self.server.server_address[1]
108+
self.stop_server()
109+
self.trial = self.bridge_module.Trial(self.root / 'configured', 'fixture', self.jobs, limits=limits)
110+
self.trial.start(started_at=started_at)
111+
self.token_file.write_text(self.trial.token)
93112
self.start_server(port)
113+
self.client = self.client_module.Client()
114+
115+
def test_natural_uses_task_archive_and_train_limits_across_restart(self):
116+
limits = TrialLimits(None, 2, 240, 15, 700_000)
117+
self.start_configured(limits)
118+
large = archive(self.root / 'large.tar', b'x' * 610_000)
119+
oversize = archive(self.root / 'oversize.tar', b'x' * 710_000)
120+
with self.assertRaisesRegex(self.client_module.SubmitError, 'HTTP 413'):
121+
self.client.request('POST', '/v1/payloads', headers={'Content-Length': '700001'})
122+
with patch.dict(os.environ, {'FRONTIER_MAX_PAYLOAD_BYTES': '700000'}):
123+
client = self.client_module.Client()
124+
with self.assertRaisesRegex(self.client_module.SubmitError, '700000-byte submission limit'):
125+
self.client_module.run_store_final(client, oversize)
126+
train, _ = self.client_module.run_train(self.client, large)
127+
self.assertEqual(train['remaining_train_calls'], 1)
128+
with self.assertRaisesRegex(self.client_module.SubmitError, 'HTTP 429'):
129+
self.client_module.run_train(self.client, self.payload)
130+
self.assertEqual(self.trial.train_calls, 1)
131+
self.assertEqual(self.trial.train_timeout(), 240)
132+
stored = self.client_module.run_store_final(self.client, large)
133+
self.assertIsNone(stored['remaining_runtime_s'])
134+
self.restart()
135+
self.assertFalse(self.trial.is_finished())
136+
self.assertEqual(self.trial.train_calls, 1)
137+
self.assertEqual(self.trial.saved, stored['payload_id'])
138+
with self.assertRaisesRegex(ValueError, 'trial limits mismatch'):
139+
self.bridge_module.Trial(self.trial.root, 'fixture', queue.Queue(),
140+
limits=TrialLimits(None, 2, 240, 16, 700_000))
141+
self.assertIsNone(self.trial.close_answering(cancelled=False))
142+
self.assertIsNone(self.trial.final)
143+
self.assertEqual(self.trial.saved, stored['payload_id'])
144+
self.assertEqual(self.trial.jobs[train['verification_id']]['state'], 'failed')
145+
146+
def test_fixed_clock_bounds_train_and_selects_the_saved_candidate(self):
147+
clock = SimpleNamespace(time=lambda: 1_100)
148+
limits = TrialLimits(60, 2, 240, 15, 524_288)
149+
with patch.object(self.bridge_module, 'time', clock):
150+
self.start_configured(limits, started_at=1_080)
151+
self.assertEqual(self.trial.deadline, 1_140)
152+
self.assertEqual(self.trial.train_timeout(), 40)
153+
self.trial.train_wall_seconds = 223
154+
self.assertEqual(self.trial.train_timeout(), 17)
155+
stored = self.client_module.run_store_final(self.client, self.payload)
156+
self.assertEqual(stored['remaining_runtime_s'], 40)
157+
self.restart()
158+
self.assertEqual(self.trial.deadline, 1_140)
159+
clock.time = lambda: 1_140
160+
self.assertTrue(self.trial.is_finished())
161+
with self.assertRaisesRegex(self.client_module.SubmitError, 'HTTP 409'):
162+
self.client_module.run_store_final(self.client, self.payload)
163+
selected = self.trial.close_answering(cancelled=False)
164+
self.assertEqual(selected['mode'], 'eval')
165+
self.assertEqual(selected['payload_id'], stored['payload_id'])
166+
self.assertEqual(self.trial.limits.eval_timeout_seconds, 15)
167+
168+
def test_manifest_overrides_feed_both_solver_inputs(self):
169+
defaults = self.root / 'defaults.toml'
170+
defaults.write_text(
171+
'[quota]\nwall_time_seconds=120\nmax_train_calls=10\nmax_train_wall_seconds=90\n'
172+
'eval_timeout_seconds=20\n[submission]\nmax_bytes=65536\n',
173+
)
174+
task = self.root / 'task.toml'
175+
task.write_text('schema="frontier.task/v1"\n[quota]\nmax_train_calls=3\n[submission]\nmax_bytes=98304\n')
176+
natural = TrialLimits.from_task(task, defaults, natural=True)
177+
fixed = TrialLimits.from_task(task, defaults, answering_seconds=75)
178+
self.assertEqual(natural, TrialLimits(None, 3, 90, 20, 98304))
179+
self.assertEqual(fixed, TrialLimits(75, 3, 90, 20, 98304))
180+
with self.assertRaisesRegex(ValueError, 'natural trial'):
181+
TrialLimits.from_task(task, defaults, natural=True, answering_seconds=75)
182+
for limits, deadline_wording in ((natural, 'no overall answering deadline'), (fixed, '75 seconds')):
183+
with self.subTest(limits=limits):
184+
task_text = render_task_instructions(f'# A task\n{LIMITS_SLOT}\n## Feedback\nUse Train.\n', limits)
185+
self.assertIn(deadline_wording, task_text)
186+
self.assertIn('20-second', task_text)
187+
self.assertIn('98304 bytes', task_text)
188+
self.assertIn('## Feedback\nUse Train.', task_text)
189+
skill = render_submission_skill(f'# Submit\n{SUBMISSION_POLICY_SLOT}', limits)
190+
self.assertEqual('`null`' in skill, limits.answering_seconds is None)
191+
self.assertEqual('use the last accepted save' in skill, limits.answering_seconds is not None)
94192

95193
def test_repeat_final_reuses_receipt_and_remote_selection(self):
96194
first = self.client_module.run_final(self.client, self.payload)
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
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

Comments
 (0)