File size: 11,645 Bytes
ac619f0 39ee2b3 ac619f0 39ee2b3 ac619f0 39ee2b3 ac619f0 39ee2b3 71167b5 ac619f0 39ee2b3 ac619f0 71167b5 39ee2b3 ac619f0 71167b5 ac619f0 39ee2b3 71167b5 39ee2b3 71167b5 39ee2b3 71167b5 ac619f0 71167b5 ac619f0 39ee2b3 ac619f0 39ee2b3 ac619f0 39ee2b3 ac619f0 39ee2b3 | 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 | """General-purpose solve, execute, and verify agent for SN99."""
import hashlib
import json
import os
import re
import subprocess
import sys
import tempfile
import time
MODELS = (
"qwen/qwen3.7-flash",
"deepseek/deepseek-v4-flash",
"deepseek/deepseek-v4-pro",
"z-ai/glm-5.2",
"openai/gpt-5.6-luna",
"google/gemini-3.6-flash",
"moonshotai/kimi-k3",
)
FAST = MODELS[4]
REVIEWER = MODELS[5]
SOLVER = MODELS[4]
FORMAT = "blueshark-verify-v2"
RUN_SECONDS = 780.0
RESERVE_SECONDS = 165.0
EXPECTED_TASKS = 6
EXPECTED_CODE_TASKS = 2
SAMPLE_SECONDS = 5.0
STRESS_SECONDS = 24.0
STRESS_CASE_SECONDS = 4.0
STRESS_ROUNDS = 48
SIZES = (1, 2, 3, 5, 8, 13, 21, 34)
SAMPLE_PATTERN = re.compile(
r"Sample (Input|Output) \d+\s*\n+(.*?)(?=\n\s*\n|\Z)", re.S
)
FENCE_PATTERN = re.compile(r"```(?:python)?\s*\n(.*?)```", re.S)
NAMED_PATTERN = re.compile(r"```(reference|generator)\s*\n(.*?)```", re.S)
def _is_code(text):
return (
"Write a complete Python 3 program" in text
and "standard input" in text
and "standard output" in text
)
def _is_choice(text):
body = "\n" + text
return all("\n" + letter + ")" in body for letter in "ABCD")
def _tag(text, marker):
if _is_code(text) or _is_choice(text):
return text
raw = hashlib.blake2b((marker + text).encode(), digest_size=16).digest()
number = int.from_bytes(raw, "big")
return text + ("\n\nRequest marker: %040d. Ignore this marker and do not repeat it." % number)
def _samples(text):
blocks = SAMPLE_PATTERN.findall(text)
inputs = [value.strip() for kind, value in blocks if kind == "Input"]
outputs = [value.strip() for kind, value in blocks if kind == "Output"]
return list(zip(inputs, outputs))
def _program(response):
match = FENCE_PATTERN.search(str(response))
return (match.group(1) if match else str(response)).strip()
def _run(code, input_text, timeout, args=()):
path = None
try:
fd, path = tempfile.mkstemp(suffix=".py")
with os.fdopen(fd, "w") as handle:
handle.write(code)
proc = subprocess.run(
[sys.executable, path, *[str(x) for x in args]],
input=input_text,
capture_output=True,
text=True,
timeout=timeout,
)
if proc.returncode != 0:
note = (proc.stderr or "no stderr").strip().splitlines()[-1][:200]
return None, "exit %d: %s" % (proc.returncode, note)
return proc.stdout, ""
except subprocess.TimeoutExpired:
return None, "timeout"
except Exception as exc:
return None, type(exc).__name__
finally:
if path:
try:
os.unlink(path)
except OSError:
pass
def _sample_failure(code, samples, until):
for input_text, expected in samples:
if time.monotonic() >= until:
return None
actual, note = _run(code, input_text, SAMPLE_SECONDS)
if actual is None:
return input_text, expected, "<no output: %s>" % note
if actual.split() != expected.split():
return input_text, expected, actual.strip() or "<empty output>"
return None
def _same_output(left, right):
a, b = left.split(), right.split()
if len(a) != len(b):
return False
for x, y in zip(a, b):
if x == y:
continue
try:
fx, fy = float(x), float(y)
except ValueError:
return False
if abs(fx - fy) > 1e-7 * max(1.0, abs(fx), abs(fy)):
return False
return True
def _blocks(response):
return {name: code.strip() for name, code in NAMED_PATTERN.findall(str(response))}
def _counterexample(solution, reference, generator, until, seed_start):
for index in range(STRESS_ROUNDS):
if time.monotonic() >= until:
return None
size = SIZES[(index // 6) % len(SIZES)]
case, _ = _run(generator, "", STRESS_CASE_SECONDS, (seed_start + index, size))
if not case or not case.strip():
continue
expected, _ = _run(reference, case, STRESS_CASE_SECONDS)
if expected is None:
continue
actual, note = _run(solution, case, STRESS_CASE_SECONDS)
if actual is None:
return case, "<no output: %s>" % note, expected.strip()
if not _same_output(actual, expected):
return case, actual.strip(), expected.strip()
return None
def _load(weights):
try:
data = json.loads(bytes(weights).decode())
except Exception as exc:
raise ValueError("weights must be JSON") from exc
if data.get("format") != FORMAT or not isinstance(data.get("marker"), str):
raise ValueError("invalid weights")
return data["marker"]
def build_agent(weights):
marker = _load(weights)
clock = {"start": None, "done": 0, "code_done": 0, "latency": {}}
def agent(prompt, call_model):
text = str(prompt)
is_code = _is_code(text)
if clock["start"] is None:
clock["start"] = time.monotonic()
hard_stop = clock["start"] + RUN_SECONDS - RESERVE_SECONDS
def ask(model, messages, tokens=12288, effort="low"):
started = time.monotonic()
response = call_model(
model,
messages,
{"max_tokens": tokens, "reasoning": {"effort": effort}},
)
elapsed = time.monotonic() - started
clock["latency"][model] = max(clock["latency"].get(model, 8.0), elapsed)
return response
def enough_room(model, extra=20.0):
now = time.monotonic()
served = clock["done"] + 1
average = (now - clock["start"]) / served
future = max(0, EXPECTED_TASKS - served) * average
estimate = clock["latency"].get(model, 20.0)
return now + estimate + extra + future < hard_stop
try:
if not is_code:
return ask(
FAST,
[{"role": "user", "content": _tag(text, marker)}],
tokens=8192,
)
instruction = "".join((
"\n\nSolve independently from the statement and constraints. Prove the algorithm "
"before coding. Check minimum and maximum sizes, equality, duplicates, mandatory "
"operations, overwrite effects, integer bounds, complexity, exact formatting, and "
"every worked example. This execution judge compares output tokens exactly even ",
"when a statement mentions numeric tolerance, so infer decimal precision from the "
"worked outputs and reproduce it. If every operation is mandatory, test equality, "
"harmless placements, and later overwrites before accepting a damaging choice. "
"Return only complete raw Python 3 source with buffered I/O.",
))
answer = ask(SOLVER, [{"role": "user", "content": text + instruction}])
samples = _samples(text)
if not samples:
return answer
code_share = max(1, EXPECTED_CODE_TASKS - clock["code_done"])
local_stop = time.monotonic() + max(0.0, hard_stop - time.monotonic()) / code_share
check_until = min(local_stop, hard_stop)
failure = _sample_failure(_program(answer), samples, check_until)
if failure is not None and enough_room(FAST, 15.0):
case, expected, actual = failure
repair = (
text + "\n\nYour proposed program failed a worked example. Input:\n" + case
+ "\n\nIt printed:\n" + actual + "\n\nExpected:\n" + expected
+ "\n\nFind the underlying mistake and return only the corrected complete "
"Python 3 source. Recheck all examples and the maximum constraints."
)
revised = ask(FAST, [{"role": "user", "content": repair}], effort="medium")
if _sample_failure(_program(revised), samples, check_until) is None:
answer = revised
if not enough_room(FAST, STRESS_SECONDS + 20.0):
return answer
tool_request = text + "".join((
"\n\nFor independent testing, write two small Python programs. The first must be "
"an obviously correct exhaustive or direct-simulation reference for small legal "
"inputs and must not reuse an optimized approach. The second must generate legal ",
"small inputs from command-line seed and size arguments, emphasizing minimum sizes, "
"equality, duplicates, extremes, and mandatory no-op cases. Verify the reference on "
"every worked example. Reply only with fenced blocks named reference and generator.",
))
reference = generator = found = None
for attempt in range(3):
if not enough_room(FAST, STRESS_SECONDS + 15.0):
break
request = tool_request + (
"\n\nAttempt marker %d. Build the checker independently from any prior attempt."
% (attempt + 1)
)
tools = _blocks(ask(FAST, [{"role": "user", "content": request}], tokens=12288))
candidate_reference = tools.get("reference")
candidate_generator = tools.get("generator")
if not candidate_reference or not candidate_generator:
continue
if _sample_failure(candidate_reference, samples, check_until) is not None:
continue
reference, generator = candidate_reference, candidate_generator
found = _counterexample(
_program(answer), reference, generator,
min(time.monotonic() + STRESS_SECONDS, check_until),
1709 + 997 * attempt + 97 * clock["code_done"],
)
if found is not None:
break
if found is None or not enough_room(FAST, 15.0):
return answer
case, actual, expected = found
review = (
text + "\n\nAn independent executable reference found a counterexample to the "
"candidate. Input:\n" + case + "\n\nCandidate output:\n" + actual
+ "\n\nReference output:\n" + expected + "\n\nDerive the algorithm yourself, "
"identify the root cause, and return only a corrected complete Python 3 program. "
"It must satisfy the worked examples and maximum constraints.\n\nCandidate:\n"
+ _program(answer)
)
revised = ask(FAST, [{"role": "user", "content": review}], tokens=12288, effort="medium")
if _sample_failure(_program(revised), samples, check_until) is not None:
return answer
second = _counterexample(
_program(revised), reference, generator,
min(time.monotonic() + STRESS_SECONDS, check_until),
9011 + 97 * clock["code_done"],
)
return revised if second is None else answer
except Exception:
if "answer" in locals() and str(answer).strip():
return answer
raise
finally:
clock["done"] += 1
if is_code:
clock["code_done"] += 1
return agent
|