Aelien commited on
Commit
8c857d1
·
verified ·
1 Parent(s): ef7976d

round3 screening pool: 3,144 certified problems, 10 shards, loop0-only + minipatch

Browse files
README.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # round3-screen-pool — 新硬题池 loop0 筛查数据(3,144 题 × 10 shards)
2
+
3
+ 用法见 repo 分支 `claude/round2-matched-compute` 的 `docs/ROUND3_SCREEN_HANDOFF.zh.md`
4
+ (先 git pull —— 分支已合并 harness 关键修复,跑前必须 `python scripts/verify_stdin_buffer_bug.py` 自检)。
5
+
6
+ - `shard00..09/seeds.jsonl` — 每 shard ~315 题,20B 和 120B 各跑一遍 **loop0-only**
7
+ - `manifest.json` — 分片与题池构成(≥2400: 1,120 题,其中 2800+: 507)
8
+ - 判分在我们这边;回传整个 RUN_DIR。
manifest.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "source": "round3_cc_pool_v3.jsonl",
3
+ "n_rows": 3144,
4
+ "n_shards": 10,
5
+ "deal": "round-robin",
6
+ "per_shard": [
7
+ 315,
8
+ 315,
9
+ 315,
10
+ 315,
11
+ 314,
12
+ 314,
13
+ 314,
14
+ 314,
15
+ 314,
16
+ 314
17
+ ],
18
+ "bands": {
19
+ ">=2400": 1120,
20
+ "1800-2399": 859,
21
+ "unrated": 1165
22
+ },
23
+ "special_judge_rows": 264,
24
+ "note": "screening = loop0 only, both models; grading on our side"
25
+ }
minipatch/README.zh.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # minipatch — 最小补丁(不切分支、不动其他文件)
2
+
3
+ 只覆盖 6 个文件:`scripts/lcb_{exec_harness,public_probe_harness,probe_exec}.py`
4
+ (**关键 harness 修复**)+ `scripts/verify_stdin_buffer_bug.py`(自检)+
5
+ `handoff/round3/run_shard_loop0.sh`(round3 loop0 runner)+
6
+ `handoff/configs/se_120b_loop0.yaml`(已存在则跳过)。
7
+
8
+ ```bash
9
+ bash install.sh /path/to/tts-sft # 会自动跑功能自检,必须显示 “自检通过”
10
+ ```
11
+
12
+ 之后直接按 ROUND3_SCREEN_HANDOFF.zh.md 第 ⑤ 步跑(无需 git 操作)。
minipatch/handoff/configs/se_120b_loop0.yaml ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Phase 1: gpt-oss-120b LOOP0 (independent sampling, pop=16) on the FULL cf+cc pool.
2
+ # loops:1 => produces only loop0 + its checkpoint <RUN_DIR>/ck0/<run_name>_loop0.json.
3
+ # gpt-oss port of the se16 codeforces config: chat, reasoning_effort medium, max_tokens 32768 (raised from 16384: cap-hits were frontier-concentrated),
4
+ # dropped extra_body.top_k. Verifier-free (grading is OFFLINE, after this phase).
5
+ # __RUN_DIR__ is substituted by run_pipeline.sh to an ABSOLUTE path (SE runs with cwd=se_dir,
6
+ # so checkpoint_dir/metrics_path MUST be absolute).
7
+ run_name: __RUN_NAME__
8
+ routing:
9
+ k: 4
10
+ population: 16
11
+ groups: 16
12
+ loops: 1 # loop0 ONLY
13
+ confidence_percentiles: []
14
+ fitness: diversity
15
+ selection: uniform
16
+ selection_temperature: 1.0
17
+ update: replace
18
+ lite_fraction: 0.0
19
+ lite_method: majority
20
+ recombination: livecodebench-aggregate
21
+ evaluation: livecodebench-none
22
+ task: code
23
+ generation_batch_size: 30000
24
+ strip_think: true
25
+ seed: 1234
26
+ models:
27
+ - name: gpt-oss-120b
28
+ base_url: http://localhost:8000/v1
29
+ api_key: EMPTY
30
+ endpoint: chat
31
+ max_tokens: 32768
32
+ temperature: 1.0
33
+ top_p: 0.95
34
+ max_concurrency: 256
35
+ reasoning_effort: medium
36
+ seed: 1234
37
+ retry:
38
+ request_timeout_seconds: 3600
39
+ resume: true # resumable: re-run to continue an interrupted loop0
40
+ checkpoint_dir: __RUN_DIR__/ck0
41
+ metrics_path: __RUN_DIR__/metrics_loop0.json
minipatch/handoff/round3/run_shard_loop0.sh ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Round-3 SCREENING: loop0 ONLY (pop=16 independent samples) on one seeds shard.
3
+ # No evolution, no feedback, no grading (判分在我们这边做).
4
+ #
5
+ # REQUIRED env:
6
+ # MODEL 20b | 120b (picks config + --model name)
7
+ # SEEDS this shard's seeds.jsonl (from the HF dataset)
8
+ # RUN_NAME unique, e.g. r3screen_20b_shard03
9
+ # RUN_DIR per-shard output dir (absolute)
10
+ # Optional: REPO SE_DIR CLIENT_PY BASE_URL (default http://localhost:8000/v1)
11
+ # BACKFILL_MAX_ROUNDS (default 10)
12
+ #
13
+ # Output to回传: RUN_DIR/ 整个目录 (loop0.out.jsonl + ck0/ + *.raw.json + run.log)
14
+ set -u
15
+ : "${REPO:=$(cd "$(dirname "$0")/../.." && pwd)}"
16
+ : "${SE_DIR:=$REPO/external/squeeze-evolve}"
17
+ : "${CLIENT_PY:=$REPO/../envs/vllm-gptoss/bin/python}"
18
+ : "${BASE_URL:=http://localhost:8000/v1}"
19
+ : "${MODEL:?set MODEL=20b or 120b}"
20
+ : "${SEEDS:?set SEEDS to this shard's seeds.jsonl}"
21
+ : "${RUN_NAME:?set RUN_NAME}"
22
+ : "${RUN_DIR:?set RUN_DIR}"
23
+ case "$MODEL" in
24
+ 20b) CFG="se_20b_loop0.yaml"; MODEL_NAME="gpt-oss-20b" ;;
25
+ 120b) CFG="se_120b_loop0.yaml"; MODEL_NAME="gpt-oss-120b" ;;
26
+ *) echo "MODEL must be 20b or 120b"; exit 2 ;;
27
+ esac
28
+ H="$REPO/handoff"; mkdir -p "$RUN_DIR"
29
+ rc(){ "$CLIENT_PY" "$@"; }
30
+ unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy 2>/dev/null || true
31
+
32
+ # sanity: this repo MUST carry the stdin-buffer harness fix (5d921c4).
33
+ # Static check — standalone, works on any branch/checkout state.
34
+ if grep -q "sys.stdin = io.StringIO(" "$REPO/scripts/lcb_exec_harness.py"; then
35
+ echo "FATAL: scripts/lcb_exec_harness.py still has the bare-StringIO stdin stub"
36
+ echo " apply the minipatch (or pull branch claude/round2-matched-compute) first"; exit 3
37
+ fi
38
+
39
+ echo "[$(date +%T)] r3 screen loop0: model=$MODEL_NAME seeds=$(wc -l <"$SEEDS") run_dir=$RUN_DIR"
40
+ sed -e "s#__RUN_DIR__#$RUN_DIR#g" -e "s#__RUN_NAME__#$RUN_NAME#g" \
41
+ "$H/configs/$CFG" > "$RUN_DIR/cfg_loop0.yaml"
42
+
43
+ echo "[$(date +%T)] Phase 1: loop0"
44
+ rc "$REPO/scripts/run_squeeze_evolve.py" --input "$SEEDS" --output "$RUN_DIR/loop0.out.jsonl" \
45
+ --config "$RUN_DIR/cfg_loop0.yaml" --squeeze-evolve-dir "$SE_DIR" \
46
+ --model "$MODEL_NAME" --base-url "$BASE_URL" --api-key EMPTY || exit 1
47
+
48
+ echo "[$(date +%T)] Phase 1b: backfill empty candidates"
49
+ rc "$H/scripts/backfill_empty_candidates.py" --run-dir "$RUN_DIR" --run-name "$RUN_NAME" \
50
+ --config "$RUN_DIR/cfg_loop0.yaml" --squeeze-evolve-dir "$SE_DIR" \
51
+ --base-url "$BASE_URL" --api-key EMPTY --max-rounds "${BACKFILL_MAX_ROUNDS:-10}" || \
52
+ echo "[$(date +%T)] WARN: backfill incomplete; continuing"
53
+
54
+ echo "[$(date +%T)] DONE — 回传整个 $RUN_DIR"
minipatch/install.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # 最小补丁安装:只覆盖 6 个文件(3 个 harness 修复 + 自检 + round3 runner + 120B 配置)。
3
+ # 其他任何文件都不动。用法: bash install.sh /path/to/tts-sft
4
+ set -eu
5
+ REPO="${1:?用法: bash install.sh /path/to/tts-sft}"
6
+ HERE="$(cd "$(dirname "$0")" && pwd)"
7
+ cp -v "$HERE"/scripts/lcb_exec_harness.py "$HERE"/scripts/lcb_public_probe_harness.py \
8
+ "$HERE"/scripts/lcb_probe_exec.py "$HERE"/scripts/verify_stdin_buffer_bug.py "$REPO/scripts/"
9
+ mkdir -p "$REPO/handoff/round3"
10
+ cp -v "$HERE"/handoff/round3/run_shard_loop0.sh "$REPO/handoff/round3/"
11
+ chmod +x "$REPO/handoff/round3/run_shard_loop0.sh"
12
+ if [ ! -f "$REPO/handoff/configs/se_120b_loop0.yaml" ]; then
13
+ cp -v "$HERE"/handoff/configs/se_120b_loop0.yaml "$REPO/handoff/configs/"
14
+ else
15
+ echo "keep existing: handoff/configs/se_120b_loop0.yaml"
16
+ fi
17
+ # 功能自检:.buffer 写法的正确解必须 pass(不依赖 git 历史)
18
+ python3 - "$REPO" <<'PY'
19
+ import json, subprocess, sys, tempfile, os
20
+ repo = sys.argv[1]
21
+ tests = {"inputs": ["3 4\n"], "outputs": ["7\n"], "testtype": "stdin"}
22
+ code = "import sys\na,b=map(int,sys.stdin.buffer.read().split())\nprint(a+b)\n"
23
+ with tempfile.TemporaryDirectory() as td:
24
+ cp, tp = os.path.join(td, "c.py"), os.path.join(td, "t.json")
25
+ open(cp, "w").write(code); open(tp, "w").write(json.dumps(tests))
26
+ r = subprocess.run([sys.executable, os.path.join(repo, "scripts", "lcb_exec_harness.py"), cp, tp],
27
+ capture_output=True, text=True, timeout=60)
28
+ v = json.loads(r.stdout.strip().splitlines()[-1])
29
+ assert v.get("passed") is True, f"自检失败: {v}"
30
+ print("自检通过: harness 修复生效 (bug absent)")
31
+ PY
32
+ echo "minipatch 安装完成。"
minipatch/scripts/lcb_exec_harness.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Single-sample LiveCodeBench execution harness (one subprocess per candidate).
3
+
4
+ Runs an extracted code candidate against a problem's hidden test suite and prints
5
+ a JSON verdict to stdout. Isolated in its own process so a crash / sys.exit / TLE
6
+ in untrusted model code is contained (the parent imposes an overall timeout too).
7
+
8
+ Usage:
9
+ python lcb_exec_harness.py <code_file> <tests_json_file>
10
+
11
+ tests_json_file: {"inputs":[...], "outputs":[...], "testtype":"stdin"|"functional",
12
+ "fn_name":"...", "time_limit":int}
13
+ Verdict (stdout, last line): {"passed":bool,"error":"","n_passed":int,"n_total":int,
14
+ "first_fail":int}
15
+
16
+ Test semantics (standard LCB):
17
+ * stdin (atcoder): feed input to stdin, run as __main__ script, compare stdout
18
+ line-wise rstrip + overall strip.
19
+ * functional (leetcode): each test `input` is newline-joined JSON args; parse each
20
+ line with json.loads, call Solution().<fn_name>(*args) (or a bare global fn),
21
+ json-compare against json.loads(output) with a float / list fallback.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import io
26
+ import json
27
+ import os
28
+ import signal
29
+ import sys
30
+
31
+ # --- resource cap (best-effort; this process is the disposable subprocess) ---
32
+ # RLIMIT_AS is the only defense against single-opcode memory bombs ([0]*b,
33
+ # bytearray(b)): SIGALRM fires only between bytecodes, so a C-level allocation
34
+ # fault-ins RAM until the container cgroup OOMs. See lcb_public_probe_harness.
35
+ try:
36
+ import resource
37
+
38
+ def _limit_mem(mem_bytes: int) -> None:
39
+ try:
40
+ resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, mem_bytes))
41
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
42
+ except (ValueError, OSError):
43
+ pass
44
+ except Exception: # pragma: no cover — non-POSIX fallback
45
+ def _limit_mem(mem_bytes: int) -> None:
46
+ return None
47
+
48
+
49
+ def _set_alarm(seconds: float) -> None:
50
+ def _handler(signum, frame):
51
+ raise TimeoutError(f"time limit exceeded ({seconds}s)")
52
+
53
+ signal.signal(signal.SIGALRM, _handler)
54
+ signal.setitimer(signal.ITIMER_REAL, max(0.1, seconds))
55
+
56
+
57
+ def _cancel_alarm() -> None:
58
+ signal.setitimer(signal.ITIMER_REAL, 0)
59
+
60
+
61
+ def _norm_out(s: str) -> str:
62
+ return "\n".join(line.rstrip() for line in str(s).strip().split("\n"))
63
+
64
+
65
+ def _eq(got, want) -> bool:
66
+ if got == want:
67
+ return True
68
+ try:
69
+ if abs(float(got) - float(want)) < 1e-6:
70
+ return True
71
+ except (TypeError, ValueError):
72
+ pass
73
+ try:
74
+ if list(got) == list(want):
75
+ return True
76
+ except TypeError:
77
+ pass
78
+ return False
79
+
80
+
81
+ def _mk_stdin(text: str):
82
+ """Text stream over a real byte buffer, so `sys.stdin.buffer` works.
83
+
84
+ A bare io.StringIO has no `.buffer`, which made every candidate using the
85
+ standard competitive-programming idiom `sys.stdin.buffer.read()` die with
86
+ AttributeError and score as a wrong answer regardless of correctness.
87
+ """
88
+ return io.TextIOWrapper(io.BytesIO(text.encode()), encoding="utf-8", newline="")
89
+
90
+
91
+ def _mk_stdout():
92
+ """(text_stream, raw_bytes) — `.buffer` works; write_through keeps ordering
93
+ correct when a candidate mixes print() and sys.stdout.buffer.write()."""
94
+ raw = io.BytesIO()
95
+ return io.TextIOWrapper(raw, encoding="utf-8", newline="", write_through=True), raw
96
+
97
+
98
+ def _stdout_value(stream, raw) -> str:
99
+ try:
100
+ stream.flush()
101
+ except Exception: # noqa: BLE001 (candidate may have closed it)
102
+ pass
103
+ return raw.getvalue().decode("utf-8", "replace")
104
+
105
+
106
+ def run_stdin(code, inputs, outputs, tl):
107
+ for i, (inp, exp) in enumerate(zip(inputs, outputs)):
108
+ stdin_text = inp if isinstance(inp, str) else "\n".join(str(x) for x in inp)
109
+ want = _norm_out(exp if isinstance(exp, str) else str(exp))
110
+ old_in, old_out = sys.stdin, sys.stdout
111
+ sys.stdin = _mk_stdin(stdin_text)
112
+ buf, buf_raw = _mk_stdout()
113
+ sys.stdout = buf
114
+ try:
115
+ _set_alarm(tl)
116
+ try:
117
+ exec(compile(code, "<candidate>", "exec"), {"__name__": "__main__"})
118
+ except SystemExit:
119
+ pass
120
+ _cancel_alarm()
121
+ except Exception as e: # noqa: BLE001
122
+ _cancel_alarm()
123
+ sys.stdin, sys.stdout = old_in, old_out
124
+ return False, f"{type(e).__name__}: {e}", i
125
+ finally:
126
+ sys.stdin, sys.stdout = old_in, old_out
127
+ if _norm_out(_stdout_value(buf, buf_raw)) != want:
128
+ return False, "wrong_answer", i
129
+ return True, "", len(inputs)
130
+
131
+
132
+ def run_functional(code, fn_name, inputs, outputs, tl):
133
+ g = {"__name__": "__lcb_harness__"}
134
+ try:
135
+ exec(compile(code, "<candidate>", "exec"), g)
136
+ except Exception as e: # noqa: BLE001
137
+ return False, f"import_error: {type(e).__name__}: {e}", 0
138
+
139
+ def resolve():
140
+ if "Solution" in g:
141
+ return getattr(g["Solution"](), fn_name)
142
+ if fn_name in g and callable(g[fn_name]):
143
+ return g[fn_name]
144
+ return None
145
+
146
+ if resolve() is None:
147
+ return False, f"no_callable:{fn_name}", 0
148
+
149
+ for i, (inp, exp) in enumerate(zip(inputs, outputs)):
150
+ try:
151
+ lines = inp.split("\n") if isinstance(inp, str) else list(inp)
152
+ args = [json.loads(line) for line in lines]
153
+ except Exception: # noqa: BLE001
154
+ args = [inp]
155
+ try:
156
+ want = json.loads(exp) if isinstance(exp, str) else exp
157
+ except Exception: # noqa: BLE001
158
+ want = exp
159
+ try:
160
+ fn = resolve() # fresh Solution() per test
161
+ _set_alarm(tl)
162
+ got = fn(*args)
163
+ _cancel_alarm()
164
+ except Exception as e: # noqa: BLE001
165
+ _cancel_alarm()
166
+ return False, f"{type(e).__name__}: {e}", i
167
+ if not _eq(got, want):
168
+ return False, "wrong_answer", i
169
+ return True, "", len(inputs)
170
+
171
+
172
+ def main() -> int:
173
+ _limit_mem(int(os.environ.get("LCB_EXEC_MEM_MB", "4096")) * 1024 * 1024)
174
+ code = open(sys.argv[1]).read()
175
+ tests = json.load(open(sys.argv[2]))
176
+ inputs, outputs = tests["inputs"], tests["outputs"]
177
+ tl = float(tests.get("time_limit", 6))
178
+ testtype = tests.get("testtype", "stdin")
179
+ fn_name = tests.get("fn_name", "")
180
+ try:
181
+ if testtype == "functional" and fn_name:
182
+ passed, err, fail_idx = run_functional(code, fn_name, inputs, outputs, tl)
183
+ else:
184
+ passed, err, fail_idx = run_stdin(code, inputs, outputs, tl)
185
+ except Exception as e: # noqa: BLE001 (harness-level guard)
186
+ passed, err, fail_idx = False, f"harness_error: {type(e).__name__}: {e}", -1
187
+ n_total = len(inputs)
188
+ n_passed = n_total if passed else max(0, fail_idx)
189
+ print(json.dumps({
190
+ "passed": passed, "error": err,
191
+ "n_passed": n_passed, "n_total": n_total, "first_fail": fail_idx,
192
+ }))
193
+ return 0
194
+
195
+
196
+ if __name__ == "__main__":
197
+ raise SystemExit(main())
minipatch/scripts/lcb_probe_exec.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """P1 step 2: run a candidate on PROBE INPUTS with NO expected outputs — capture raw behavior only
3
+ (stdout / function return / error / timeout). Used purely for cross-candidate disagreement detection;
4
+ no correctness judgement is made or implied. Subprocess-isolated, per-input SIGALRM.
5
+
6
+ argv: <code_file> <spec_json_file> spec = {"inputs":[...], "testtype":"stdin"|"functional", "fn_name":""}
7
+ stdout (last line) JSON: {"results":[{"kind":"output"|"error"|"timeout","value":str}, ...]}
8
+ """
9
+ from __future__ import annotations
10
+ import io, json, os, signal, sys
11
+
12
+ # RLIMIT_AS cap: SIGALRM cannot interrupt single-opcode memory bombs ([0]*b);
13
+ # see lcb_public_probe_harness.py (2026-07-20 container-OOM root cause).
14
+ try:
15
+ import resource
16
+
17
+ def _limit_mem(mem_bytes: int) -> None:
18
+ try:
19
+ resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, mem_bytes))
20
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
21
+ except (ValueError, OSError):
22
+ pass
23
+ except Exception: # pragma: no cover — non-POSIX fallback
24
+ def _limit_mem(mem_bytes: int) -> None:
25
+ return None
26
+
27
+
28
+ def _alarm(sec):
29
+ def h(s, f): raise TimeoutError("TLE")
30
+ signal.signal(signal.SIGALRM, h); signal.setitimer(signal.ITIMER_REAL, max(0.1, sec))
31
+ def _cancel(): signal.setitimer(signal.ITIMER_REAL, 0)
32
+ def _norm(s): return "\n".join(l.rstrip() for l in str(s).strip().split("\n"))
33
+
34
+
35
+ def run_stdin(code, inputs, tl):
36
+ try:
37
+ compiled = compile(code, "<candidate>", "exec")
38
+ except Exception as e: # noqa: BLE001
39
+ return [{"kind": "error", "value": f"compile: {type(e).__name__}"} for _ in inputs]
40
+ out = []
41
+ for inp in inputs:
42
+ oi, oo = sys.stdin, sys.stdout
43
+ # TextIOWrapper over BytesIO: bare StringIO has no .buffer, so every
44
+ # candidate using sys.stdin.buffer.read() died as a runtime error.
45
+ sys.stdin = io.TextIOWrapper(io.BytesIO(inp.encode()), encoding="utf-8", newline="")
46
+ obuf = io.BytesIO()
47
+ buf = io.TextIOWrapper(obuf, encoding="utf-8", newline="", write_through=True)
48
+ sys.stdout = buf
49
+ try:
50
+ _alarm(tl)
51
+ try:
52
+ exec(compiled, {"__name__": "__main__"})
53
+ except SystemExit:
54
+ pass
55
+ _cancel()
56
+ try:
57
+ buf.flush()
58
+ except Exception: # noqa: BLE001
59
+ pass
60
+ out.append({"kind": "output", "value": _norm(obuf.getvalue().decode("utf-8", "replace"))[:1000]})
61
+ except TimeoutError:
62
+ _cancel(); out.append({"kind": "timeout", "value": ""})
63
+ except Exception as e: # noqa: BLE001
64
+ _cancel(); out.append({"kind": "error", "value": f"{type(e).__name__}"})
65
+ finally:
66
+ sys.stdin, sys.stdout = oi, oo
67
+ return out
68
+
69
+
70
+ def run_functional(code, fn_name, inputs, tl):
71
+ g = {"__name__": "__probe__"}
72
+ try:
73
+ exec(compile(code, "<candidate>", "exec"), g)
74
+ except Exception as e: # noqa: BLE001
75
+ return [{"kind": "error", "value": f"compile: {type(e).__name__}"} for _ in inputs]
76
+ def resolve():
77
+ if "Solution" in g:
78
+ try: return getattr(g["Solution"](), fn_name)
79
+ except Exception: return None
80
+ f = g.get(fn_name); return f if callable(f) else None
81
+ if resolve() is None:
82
+ return [{"kind": "error", "value": "no_callable"} for _ in inputs]
83
+ out = []
84
+ for inp in inputs:
85
+ try:
86
+ args = [json.loads(x) for x in str(inp).split("\n") if x.strip()]
87
+ except Exception:
88
+ args = [inp]
89
+ try:
90
+ fn = resolve(); _alarm(tl); res = fn(*args); _cancel()
91
+ out.append({"kind": "output", "value": repr(res)[:1000]})
92
+ except TimeoutError:
93
+ _cancel(); out.append({"kind": "timeout", "value": ""})
94
+ except Exception as e: # noqa: BLE001
95
+ _cancel(); out.append({"kind": "error", "value": f"{type(e).__name__}"})
96
+ return out
97
+
98
+
99
+ def main():
100
+ _limit_mem(int(os.environ.get("LCB_EXEC_MEM_MB", "4096")) * 1024 * 1024)
101
+ code = open(sys.argv[1]).read()
102
+ spec = json.load(open(sys.argv[2]))
103
+ inputs = spec["inputs"]; tl = float(spec.get("time_limit", 6))
104
+ if spec.get("testtype") == "functional" and spec.get("fn_name"):
105
+ res = run_functional(code, spec["fn_name"], inputs, tl)
106
+ else:
107
+ res = run_stdin(code, inputs, tl)
108
+ print(json.dumps({"results": res}, ensure_ascii=False))
109
+
110
+
111
+ if __name__ == "__main__":
112
+ main()
minipatch/scripts/lcb_public_probe_harness.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Run a candidate against PUBLIC (non-hidden) LCB tests and return DETAILED, structured results
3
+ for building non-leaky execution feedback (V2/V3/V4 in the LCB feedback-repair probe).
4
+
5
+ Subprocess-isolated (untrusted code), per-test SIGALRM timeout. NEVER touches hidden tests.
6
+
7
+ argv: <code_file> <public_tests_json_file> (tests json = {inputs,outputs,testtype,fn_name,time_limit})
8
+ stdout (last line) JSON: {"category","n_pass","n_total","first_fail":{idx,input,expected,actual,error}|null}
9
+ category in: compile_error | runtime_error | wrong_answer | timeout | all_pass | no_callable
10
+ """
11
+ from __future__ import annotations
12
+ import io, json, os, signal, sys
13
+
14
+ # --- resource cap (best-effort; this process is the disposable subprocess) ---
15
+ # RLIMIT_AS is the only defense that works against single-opcode memory bombs
16
+ # ([0]*b, bytearray(b)): SIGALRM only fires between bytecodes, so a C-level
17
+ # allocation fault-ins RAM until the CONTAINER cgroup OOMs (2026-07-20 root
18
+ # cause: cc-05672 naive-expansion candidates killed both the 20B and 120B
19
+ # shard04 nodes mid-loop-1 feedback exec). With the cap, the bomb raises
20
+ # MemoryError in microseconds and becomes useful runtime_error feedback.
21
+ try:
22
+ import resource
23
+
24
+ def _limit_mem(mem_bytes: int) -> None:
25
+ try:
26
+ resource.setrlimit(resource.RLIMIT_AS, (mem_bytes, mem_bytes))
27
+ resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
28
+ except (ValueError, OSError):
29
+ pass
30
+ except Exception: # pragma: no cover — non-POSIX fallback
31
+ def _limit_mem(mem_bytes: int) -> None:
32
+ return None
33
+
34
+
35
+ def _alarm(sec):
36
+ def h(s, f): raise TimeoutError(f"TLE {sec}s")
37
+ signal.signal(signal.SIGALRM, h); signal.setitimer(signal.ITIMER_REAL, max(0.1, sec))
38
+ def _cancel(): signal.setitimer(signal.ITIMER_REAL, 0)
39
+ def _norm(s): return "\n".join(l.rstrip() for l in str(s).strip().split("\n"))
40
+
41
+
42
+ def _drain(stream, raw):
43
+ """Text written through `stream` plus anything written straight to its .buffer."""
44
+ try:
45
+ stream.flush()
46
+ except Exception: # noqa: BLE001 (candidate may have closed it)
47
+ pass
48
+ return raw.getvalue().decode("utf-8", "replace")
49
+
50
+
51
+ def run_stdin(code, inputs, outputs, tl, max_fails=1):
52
+ # max_fails=1 (default) reproduces the historical stop-at-first-failure behavior exactly.
53
+ # max_fails>1 keeps executing after a failure and collects up to max_fails failing cases
54
+ # (each tagged with its category) so the feedback operator can show more than one bug signal.
55
+ # compile once to detect syntax/compile errors up front
56
+ try:
57
+ compiled = compile(code, "<candidate>", "exec")
58
+ except Exception as e: # noqa: BLE001
59
+ return ("compile_error", 0, len(inputs), 0,
60
+ [{"idx": -1, "input": None, "expected": None, "actual": None,
61
+ "error": f"{type(e).__name__}: {e}", "kind": "compile_error"}])
62
+ npass = 0
63
+ fails = []
64
+ n_ran = 0
65
+ for i, (inp, exp) in enumerate(zip(inputs, outputs)):
66
+ n_ran = i + 1
67
+ stdin = inp if isinstance(inp, str) else "\n".join(str(x) for x in inp)
68
+ want = _norm(exp if isinstance(exp, str) else str(exp))
69
+ oi, oo = sys.stdin, sys.stdout
70
+ # TextIOWrapper over BytesIO so candidates using sys.stdin.buffer.read()
71
+ # / sys.stdout.buffer.write() (ubiquitous in CP code) work too — bare
72
+ # StringIO has no .buffer and crashed them all as runtime_error, which
73
+ # then fed a bogus "your solution crashed" message back to the model.
74
+ sys.stdin = io.TextIOWrapper(io.BytesIO(stdin.encode()), encoding="utf-8", newline="")
75
+ obuf = io.BytesIO()
76
+ buf = io.TextIOWrapper(obuf, encoding="utf-8", newline="", write_through=True)
77
+ sys.stdout = buf
78
+ try:
79
+ _alarm(tl)
80
+ try:
81
+ exec(compiled, {"__name__": "__main__"})
82
+ except SystemExit:
83
+ pass
84
+ _cancel()
85
+ except TimeoutError as e:
86
+ _cancel(); sys.stdin, sys.stdout = oi, oo
87
+ fails.append({"idx": i, "input": stdin, "expected": want, "actual": None,
88
+ "error": str(e), "kind": "timeout"})
89
+ if len(fails) >= max_fails: break
90
+ continue
91
+ except Exception as e: # noqa: BLE001
92
+ _cancel(); sys.stdin, sys.stdout = oi, oo
93
+ fails.append({"idx": i, "input": stdin, "expected": want, "actual": None,
94
+ "error": f"{type(e).__name__}: {e}", "kind": "runtime_error"})
95
+ if len(fails) >= max_fails: break
96
+ continue
97
+ finally:
98
+ sys.stdin, sys.stdout = oi, oo
99
+ got = _norm(_drain(buf, obuf))
100
+ if got == want:
101
+ npass += 1
102
+ else:
103
+ fails.append({"idx": i, "input": stdin, "expected": want, "actual": got[:2000],
104
+ "kind": "wrong_answer"})
105
+ if len(fails) >= max_fails: break
106
+ cat = fails[0]["kind"] if fails else "all_pass"
107
+ return (cat, npass, len(inputs), n_ran, fails)
108
+
109
+
110
+ def run_functional(code, fn_name, inputs, outputs, tl):
111
+ g = {"__name__": "__h__"}
112
+ try:
113
+ exec(compile(code, "<candidate>", "exec"), g)
114
+ except Exception as e: # noqa: BLE001
115
+ return ("compile_error", 0, len(inputs), {"idx": -1, "input": None, "expected": None, "actual": None, "error": f"{type(e).__name__}: {e}"})
116
+ def resolve():
117
+ if "Solution" in g:
118
+ try: return getattr(g["Solution"](), fn_name)
119
+ except Exception: return None
120
+ return g.get(fn_name) if callable(g.get(fn_name)) else None
121
+ if resolve() is None:
122
+ return ("no_callable", 0, len(inputs), {"idx": -1, "input": None, "expected": None, "actual": None, "error": f"no callable {fn_name}"})
123
+ npass = 0
124
+ for i, (inp, exp) in enumerate(zip(inputs, outputs)):
125
+ try:
126
+ args = [json.loads(x) for x in (inp.split("\n") if isinstance(inp, str) else list(inp))]
127
+ except Exception:
128
+ args = [inp]
129
+ try:
130
+ want = json.loads(exp) if isinstance(exp, str) else exp
131
+ except Exception:
132
+ want = exp
133
+ try:
134
+ fn = resolve(); _alarm(tl); got = fn(*args); _cancel()
135
+ except TimeoutError as e:
136
+ _cancel(); return ("timeout", npass, len(inputs), {"idx": i, "input": str(inp), "expected": str(want), "actual": None, "error": str(e)})
137
+ except Exception as e: # noqa: BLE001
138
+ _cancel(); return ("runtime_error", npass, len(inputs), {"idx": i, "input": str(inp), "expected": str(want), "actual": None, "error": f"{type(e).__name__}: {e}"})
139
+ if got == want or str(got) == str(want):
140
+ npass += 1
141
+ else:
142
+ return ("wrong_answer", npass, len(inputs), {"idx": i, "input": str(inp), "expected": str(want), "actual": str(got)[:2000]})
143
+ return ("all_pass", npass, len(inputs), None)
144
+
145
+
146
+ def main():
147
+ _limit_mem(int(os.environ.get("LCB_EXEC_MEM_MB", "4096")) * 1024 * 1024)
148
+ code = open(sys.argv[1]).read()
149
+ t = json.load(open(sys.argv[2]))
150
+ inp, out = t["inputs"], t["outputs"]; tl = float(t.get("time_limit", 6))
151
+ max_fails = max(1, int(os.environ.get("LCB_PROBE_MAX_FAILS", "1")))
152
+ if t.get("testtype") == "functional" and t.get("fn_name"):
153
+ # functional path keeps stop-at-first-failure (no multi-fail need yet)
154
+ cat, npass, ntot, ff = run_functional(code, t["fn_name"], inp, out, tl)
155
+ n_ran, fails = (ff["idx"] + 1 if ff and ff.get("idx", -1) >= 0 else ntot), ([ff] if ff else [])
156
+ else:
157
+ cat, npass, ntot, n_ran, fails = run_stdin(code, inp, out, tl, max_fails=max_fails)
158
+ print(json.dumps({"category": cat, "n_pass": npass, "n_total": ntot, "n_ran": n_ran,
159
+ "first_fail": (fails[0] if fails else None), "fails": fails}, ensure_ascii=False))
160
+
161
+
162
+ if __name__ == "__main__":
163
+ main()
minipatch/scripts/verify_stdin_buffer_bug.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Self-contained check for the `sys.stdin.buffer` harness bug. Trusts nothing.
3
+
4
+ Run with no arguments for levels 1-2 (a few seconds, no data needed):
5
+
6
+ python scripts/verify_stdin_buffer_bug.py
7
+
8
+ Add a run directory from tts-sft/round2-oss-matched to also run level 3 against
9
+ real shipped results:
10
+
11
+ python scripts/verify_stdin_buffer_bug.py --run-dir <DATA>/exp3_120b/node03
12
+
13
+ Level 1 a property of Python itself — no repo, no data, no analysis involved.
14
+ Level 2 this repo's grading harness, on a hand-written solution that is
15
+ obviously correct, at the current commit and at the pre-fix commit.
16
+ Level 3 real shipped candidates the fleet graded 0/16, re-executed here.
17
+
18
+ Exit code 0 = the bug is absent (harness handles .buffer). 1 = present.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import io
24
+ import json
25
+ import os
26
+ import subprocess
27
+ import sys
28
+ import tempfile
29
+
30
+ REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
31
+
32
+ # Correct solution to "read two ints, print their sum", written the way gpt-oss
33
+ # writes it. There is no argument to be had about whether this is correct.
34
+ BUFFER_SOLUTION = "import sys\na, b = map(int, sys.stdin.buffer.read().split())\nprint(a + b)\n"
35
+ PLAIN_SOLUTION = "a, b = map(int, input().split())\nprint(a + b)\n"
36
+ WRONG_SOLUTION = "a, b = map(int, input().split())\nprint(a - b)\n"
37
+ TESTS = {"inputs": ["2 3\n"], "outputs": ["5\n"], "testtype": "stdin"}
38
+
39
+
40
+ def level1() -> bool:
41
+ print("LEVEL 1 — plain Python, nothing to do with this repo")
42
+ print(" sys.stdin = io.StringIO('2 3'); sys.stdin.buffer.read()")
43
+ old = sys.stdin
44
+ sys.stdin = io.StringIO("2 3\n")
45
+ try:
46
+ sys.stdin.buffer.read()
47
+ print(" -> no error (this Python has .buffer on StringIO?!)\n")
48
+ return True
49
+ except AttributeError as e:
50
+ print(f" -> AttributeError: {e}")
51
+ print(" Any candidate reading input this way dies here, correct or not.\n")
52
+ return False
53
+ finally:
54
+ sys.stdin = old
55
+
56
+
57
+ def _verdict(harness: str, code: str) -> dict:
58
+ cf = tempfile.NamedTemporaryFile("w", suffix=".py", delete=False)
59
+ cf.write(code); cf.close()
60
+ tf = tempfile.NamedTemporaryFile("w", suffix=".json", delete=False)
61
+ json.dump(TESTS, tf); tf.close()
62
+ try:
63
+ p = subprocess.run([sys.executable, harness, cf.name, tf.name],
64
+ capture_output=True, text=True, timeout=60)
65
+ out = p.stdout.strip().splitlines()
66
+ return json.loads(out[-1]) if out else {"error": (p.stderr or "")[:200]}
67
+ finally:
68
+ os.unlink(cf.name); os.unlink(tf.name)
69
+
70
+
71
+ def level2() -> bool:
72
+ print("LEVEL 2 — this repo's grading harness on a hand-written correct solution")
73
+ harness = os.path.join(REPO, "scripts", "lcb_exec_harness.py")
74
+
75
+ old_harness = None
76
+ try: # the harness as it was before the fix, straight out of git
77
+ blob = subprocess.run(
78
+ ["git", "-C", REPO, "show", "HEAD~1:scripts/lcb_exec_harness.py"],
79
+ capture_output=True, text=True, timeout=30)
80
+ if blob.returncode == 0 and "def run_stdin" in blob.stdout:
81
+ f = tempfile.NamedTemporaryFile("w", suffix=".py", delete=False)
82
+ f.write(blob.stdout); f.close()
83
+ old_harness = f.name
84
+ except Exception: # noqa: BLE001
85
+ pass
86
+
87
+ ok = True
88
+ rows = [("sys.stdin.buffer.read() [correct]", BUFFER_SOLUTION, True),
89
+ ("input() [correct]", PLAIN_SOLUTION, True),
90
+ ("input(), prints a-b [WRONG] ", WRONG_SOLUTION, False)]
91
+ print(f" {'candidate':38} {'pre-fix':>12} {'current':>12} {'expected':>10}")
92
+ for label, code, want in rows:
93
+ cur = bool(_verdict(harness, code).get("passed"))
94
+ pre = "n/a"
95
+ if old_harness:
96
+ pre = "PASS" if _verdict(old_harness, code).get("passed") else "fail"
97
+ print(f" {label:38} {pre:>12} {'PASS' if cur else 'fail':>12}"
98
+ f" {'PASS' if want else 'fail':>10}")
99
+ if cur != want:
100
+ ok = False
101
+ if old_harness:
102
+ os.unlink(old_harness)
103
+ print(" A correct solution scored 'fail' is the bug. A wrong one must still fail.\n")
104
+ return ok
105
+
106
+
107
+ def level3(run_dir: str) -> bool:
108
+ print(f"LEVEL 3 — real shipped candidates from {run_dir}")
109
+ sys.path.insert(0, os.path.join(REPO, "scripts"))
110
+ sys.path.insert(0, os.path.join(REPO, "handoff", "scripts"))
111
+ import csv
112
+ from score_diversify_ab import extract_code
113
+ from grade_v2_lib import _job_for
114
+ from lcb_grading import _run_once
115
+
116
+ csv_path = os.path.join(run_dir, "final_grade_per_problem.csv")
117
+ graded0 = [r["id"] for r in csv.DictReader(open(csv_path))
118
+ if int(r["correct_count"]) == 0 and r["format"] == "stdin_stdout"]
119
+ print(f" the fleet graded {len(graded0)} stdin problems 0/16; checking the first 5")
120
+
121
+ pool = {}
122
+ for line in open(os.path.join(run_dir, "pool.jsonl")):
123
+ r = json.loads(line)
124
+ pool[r["seed_id"]] = r
125
+ want = set(graded0[:5])
126
+ outs = {}
127
+ for line in open(os.path.join(run_dir, "loops.out.jsonl")):
128
+ d = json.loads(line)
129
+ if d["id"] in want:
130
+ outs[d["id"]] = d
131
+
132
+ bad = 0
133
+ for pid in graded0[:5]:
134
+ harness, tj, n, tl = _job_for(pool[pid], REPO, 8.0)
135
+ code = extract_code((outs[pid].get("candidates") or [""])[0])
136
+ v = _run_once(harness, code, tj, n, tl) or {}
137
+ ok = bool(v.get("passed"))
138
+ bad += ok
139
+ print(f" {pid:>12} fleet said 0/16 | here: "
140
+ f"{'PASSES all ' + str(n) + ' ground-truth tests' if ok else 'fails: ' + str(v.get('error'))[:50]}")
141
+ print(f" {bad}/5 of the fleet's zeros actually pass.\n")
142
+ return bad == 0
143
+
144
+
145
+ if __name__ == "__main__":
146
+ ap = argparse.ArgumentParser()
147
+ ap.add_argument("--run-dir", help="a node dir with final_grade_per_problem.csv, "
148
+ "pool.jsonl and loops.out.jsonl")
149
+ a = ap.parse_args()
150
+ level1()
151
+ clean = level2()
152
+ if a.run_dir:
153
+ clean = level3(a.run_dir) and clean
154
+ print("VERDICT:", "harness handles .buffer — bug absent" if clean
155
+ else "correct solutions are being scored wrong — bug present")
156
+ sys.exit(0 if clean else 1)
shard00/pool.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard00/seeds.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard01/pool.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard01/seeds.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard02/pool.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard02/seeds.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard03/pool.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard03/seeds.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard04/pool.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard04/seeds.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard05/pool.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard05/seeds.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard06/pool.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard06/seeds.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard07/pool.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard07/seeds.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard08/pool.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard08/seeds.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard09/pool.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
shard09/seeds.jsonl ADDED
The diff for this file is too large to render. See raw diff