File size: 12,795 Bytes
29f1507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Miner2 v4: risk-gated, deadline-bounded differential verification for SN99."""

import hashlib
import json
import os
import re
import resource
import signal
import subprocess
import sys
import tempfile
import time


_FORMAT = "miner2-risk-gated-stress-v4"
_MODEL = "openai/gpt-5.6-luna"
_EFFORTS = ("low", "medium", "high")
_OUTPUT_LIMIT = 8 * 1024 * 1024
_CASE_TIMEOUT_S = 8.0
_GEN_TIMEOUT_S = 4.0
_CHILD_CPU_S = 9
_CHILD_AS_BYTES = 1 << 30
_CHILD_NPROC = 16
_CHILD_NOFILE = 32
_STRESS_ROUNDS = 24
_MIN_VALID_STRESS = 8
_SIZES = (2, 3, 5, 8, 12, 20)

_SAMPLE = re.compile(r"^Sample (Input|Output)\s*(\d+)\s*$", re.MULTILINE)
_FENCE = re.compile(r"```(?:python|py)?\s*\n(.*?)```", re.DOTALL | re.IGNORECASE)
_NAMED = re.compile(r"```(reference|generator)\s*\n(.*?)```", re.DOTALL | re.IGNORECASE)
_UNSAFE = re.compile(
    r"\b(?:subprocess|multiprocessing|socket)\b|"
    r"\bos\s*\.\s*(?:fork|forkpty|posix_spawn|system|popen)\b|"
    r"\bpty\s*\.\s*spawn\b"
)
_CODE_REQUEST = (
    "Use the full constraints to choose a provably correct algorithm and suitable buffered I/O. "
    "Check every explicit condition and published example. Return only complete raw Python 3 "
    "source, without Markdown fences or prose."
)
_TOOLS_REQUEST = (
    "Independently test the proposed solution. Return exactly two fenced blocks: `reference` must "
    "be a simple correctness-first program for small legal inputs and must not reuse the optimized "
    "algorithm; `generator` must accept seed and size arguments, seed Python random, and print one "
    "legal varied input. Output no text outside those blocks."
)
_REPAIR_REQUEST = (
    "A generated legal case disagrees with an independently derived small-case reference. Solve "
    "the original problem again from first principles; do not patch or special-case this case.\n"
    "Input:\n%s\nPrevious output:\n%s\nReference output:\n%s\nReturn only complete raw Python 3 source."
)
_INCONCLUSIVE = object()


def _is_code_prompt(text):
    value = str(text)
    return (
        "Write a complete Python 3 program" in value
        and "standard input" in value
        and "standard output" in value
    )


def _is_choice_prompt(text):
    body = "\n" + str(text)
    return all("\n" + letter + ")" in body for letter in "ABCD")


def _samples(prompt, maximum):
    text = str(prompt)
    marks = [(m.start(), m.end(), m.group(1), m.group(2)) for m in _SAMPLE.finditer(text)]
    blocks = {}
    for index, (_start, end, kind, number) in enumerate(marks):
        stop = marks[index + 1][0] if index + 1 < len(marks) else len(text)
        body = text[end:stop].replace("\r\n", "\n").replace("\r", "\n").strip("\n")
        if kind == "Output":
            body = body.split("\n\n", 1)[0]
        blocks.setdefault(number, {})[kind] = body.strip("\n")
    pairs = []
    for number in sorted(blocks, key=lambda item: int(item) if item.isdigit() else item):
        row = blocks[number]
        if row.get("Input", "").strip() and "Output" in row:
            pairs.append((row["Input"] + "\n", row["Output"]))
    return pairs[:maximum]


def _program(response):
    value = str(response or "")
    match = _FENCE.search(value)
    return (match.group(1) if match else value).strip()


def _named_blocks(response):
    return {name.lower(): code.strip() for name, code in _NAMED.findall(str(response or ""))}


def _limits():  # pragma: no cover - child only
    resource.setrlimit(resource.RLIMIT_CPU, (_CHILD_CPU_S, _CHILD_CPU_S))
    resource.setrlimit(resource.RLIMIT_AS, (_CHILD_AS_BYTES, _CHILD_AS_BYTES))
    resource.setrlimit(resource.RLIMIT_NPROC, (_CHILD_NPROC, _CHILD_NPROC))
    resource.setrlimit(resource.RLIMIT_NOFILE, (_CHILD_NOFILE, _CHILD_NOFILE))
    resource.setrlimit(resource.RLIMIT_FSIZE, (_OUTPUT_LIMIT, _OUTPUT_LIMIT))
    resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
    os.setsid()


def _kill_group(process):
    try:
        os.killpg(os.getpgid(process.pid), signal.SIGKILL)
    except Exception:  # noqa: BLE001
        try:
            process.kill()
        except Exception:  # noqa: BLE001
            pass


def _execute(code, stdin_text, timeout, argv=()):
    if not str(code).strip():
        return "empty", ""
    if _UNSAFE.search(str(code)):
        return "rejected", ""
    path = None
    output = None
    process = None
    try:
        descriptor, path = tempfile.mkstemp(suffix=".py")
        with os.fdopen(descriptor, "w") as handle:
            handle.write(str(code))
        output = tempfile.TemporaryFile()
        process = subprocess.Popen(
            [sys.executable, path, *[str(item) for item in argv]],
            stdin=subprocess.PIPE,
            stdout=output,
            stderr=subprocess.DEVNULL,
            preexec_fn=_limits,
            close_fds=True,
            cwd=tempfile.gettempdir(),
            env={"PATH": "/usr/bin:/bin", "PYTHONIOENCODING": "utf-8"},
        )
        try:
            process.communicate(str(stdin_text).encode("utf-8"), timeout=timeout)
        except subprocess.TimeoutExpired:
            _kill_group(process)
            process.communicate(timeout=2)
            return "timeout", ""
        output.seek(0)
        raw = output.read(_OUTPUT_LIMIT + 1)
        if len(raw) > _OUTPUT_LIMIT:
            return "output_limit", ""
        if process.returncode != 0:
            return "crash", raw.decode("utf-8", "replace")
        return "ok", raw.decode("utf-8", "replace")
    except Exception:  # noqa: BLE001
        return "harness", ""
    finally:
        if process is not None and process.poll() is None:
            _kill_group(process)
        if output is not None:
            output.close()
        if path:
            try:
                os.unlink(path)
            except OSError:
                pass


def _first_failure(answer, cases):
    if not cases:
        return None
    code = _program(answer)
    if not code:
        return cases[0][0], "<empty>", cases[0][1]
    if _UNSAFE.search(code):
        return _INCONCLUSIVE
    for stdin_text, expected in cases:
        status, observed = _execute(code, stdin_text, _CASE_TIMEOUT_S)
        if status in ("rejected", "timeout", "output_limit", "harness"):
            return _INCONCLUSIVE
        if status != "ok":
            return stdin_text, "<%s>" % status, expected
        if observed.split() != expected.split():
            return stdin_text, observed.strip(), expected.strip()
    return None


def _same_values(left, right, rel=1e-7):
    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) > rel * max(1.0, abs(fx), abs(fy)):
            return False
    return True


def _stress(solution, reference, generator):
    valid = 0
    first_mismatch = None
    for index in range(_STRESS_ROUNDS):
        size = _SIZES[index % len(_SIZES)]
        status, case = _execute(generator, "", _GEN_TIMEOUT_S, argv=(7919 + index, size))
        if status != "ok" or not case.strip():
            continue
        ref_status, wanted = _execute(reference, case, _CASE_TIMEOUT_S)
        if ref_status != "ok":
            continue
        valid += 1
        if first_mismatch is not None:
            continue
        got_status, got = _execute(solution, case, _CASE_TIMEOUT_S)
        if got_status == "ok" and (got.split() == wanted.split() or _same_values(got, wanted)):
            continue
        observed = got.strip() if got_status == "ok" else "<%s>" % got_status
        first_mismatch = (case, observed, wanted.strip())
    return first_mismatch, valid


def _needs_verification(prompt, policy):
    text = str(prompt)
    lower = text.lower()
    return (
        len(text) >= policy["verify_min_chars"]
        and (
            lower.count("operation") >= policy["verify_operation_mentions"]
            or lower.count("swap") >= policy["verify_swap_mentions"]
        )
    )


def _load_policy(weights):
    try:
        policy = json.loads(bytes(weights).decode("utf-8"))
    except Exception as exc:
        raise ValueError("miner2-v4 weights are not valid JSON") from exc
    allowed = {
        "format", "model", "draft_effort", "floor_effort", "repair_effort",
        "tools_effort", "max_tokens", "max_examples", "prompt_revision",
        "verify_min_chars", "verify_operation_mentions", "verify_swap_mentions",
        "verify_start_deadline_s", "repair_start_deadline_s",
    }
    if not isinstance(policy, dict) or set(policy) != allowed:
        raise ValueError("miner2-v4 policy schema is malformed")
    if policy.get("format") != _FORMAT or policy.get("model") != _MODEL:
        raise ValueError("miner2-v4 policy identity is malformed")
    if any(policy.get(key) not in _EFFORTS for key in
           ("draft_effort", "floor_effort", "repair_effort", "tools_effort")):
        raise ValueError("miner2-v4 effort policy is malformed")
    if type(policy.get("max_tokens")) is not int or policy["max_tokens"] != 8192:
        raise ValueError("miner2-v4 token limit is malformed")
    if type(policy.get("max_examples")) is not int or not 1 <= policy["max_examples"] <= 8:
        raise ValueError("miner2-v4 example limit is malformed")
    if policy.get("prompt_revision") != 4:
        raise ValueError("miner2-v4 prompt revision is malformed")
    if (policy.get("verify_min_chars") != 1400
            or policy.get("verify_operation_mentions") != 4
            or policy.get("verify_swap_mentions") != 2):
        raise ValueError("miner2-v4 risk policy is malformed")
    if (policy.get("verify_start_deadline_s") != 28
            or policy.get("repair_start_deadline_s") != 30):
        raise ValueError("miner2-v4 deadline policy is malformed")
    return policy


def build_agent(weights):
    policy = _load_policy(weights)
    batch_started = [None]

    def params(effort):
        return {"max_tokens": policy["max_tokens"], "reasoning": {"effort": effort}}

    def ask(call_model, content, effort):
        return call_model(_MODEL, [{"role": "user", "content": content}], params(effort))

    def agent(prompt, call_model):
        original = str(prompt)
        if batch_started[0] is None:
            batch_started[0] = time.monotonic()
        if _is_choice_prompt(original):
            return ask(call_model, original, policy["floor_effort"])
        if not _is_code_prompt(original):
            marker = int.from_bytes(hashlib.sha256(original.encode("utf-8")).digest()[:8], "big")
            request = (
                original + "\n\nSolve in the requested units and put the final numeric answer "
                "alone on the last line. Ignore audit marker %d; it is answer-independent "
                "metadata and must not appear in the answer." % marker
            )
            return ask(call_model, request, policy["floor_effort"])

        draft = ask(call_model, original + "\n\n" + _CODE_REQUEST, policy["draft_effort"])
        cases = _samples(original, policy["max_examples"])
        sample_failure = _first_failure(draft, cases)
        if sample_failure is not None and sample_failure is not _INCONCLUSIVE:
            repaired = ask(
                call_model, original + "\n\n" + (_REPAIR_REQUEST % sample_failure),
                policy["repair_effort"],
            )
            return repaired if _first_failure(repaired, cases) is None else draft
        if sample_failure is _INCONCLUSIVE or not cases:
            return draft

        if not _needs_verification(original, policy):
            return draft
        if time.monotonic() - batch_started[0] > policy["verify_start_deadline_s"]:
            return draft

        tools = ask(call_model, original + "\n\n" + _TOOLS_REQUEST, policy["tools_effort"])
        blocks = _named_blocks(tools)
        reference, generator = blocks.get("reference"), blocks.get("generator")
        if not reference or not generator or _first_failure(reference, cases) is not None:
            return draft
        mismatch, valid = _stress(_program(draft), reference, generator)
        if mismatch is None or valid < _MIN_VALID_STRESS:
            return draft
        if time.monotonic() - batch_started[0] > policy["repair_start_deadline_s"]:
            return draft
        repaired = ask(
            call_model, original + "\n\n" + (_REPAIR_REQUEST % mismatch),
            policy["repair_effort"],
        )
        if _first_failure(repaired, cases) is not None:
            return draft
        disagreement, checked = _stress(_program(repaired), reference, generator)
        return repaired if disagreement is None and checked >= _MIN_VALID_STRESS else draft

    return agent