File size: 12,574 Bytes
d9d71ad | 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 | #!/usr/bin/env python3
"""RT-cut patch: --emit-top-k, --blocked-restart (prepare); trace-exec (harness);
trace + restart rendering (renderer). All opt-in; bit-identical when off."""
import sys
def apply(path, edits):
s = open(path).read()
for old, new in edits:
n = s.count(old)
if n != 1:
sys.exit(f"ANCHOR FAIL in {path} ({n}): {old[:80]!r}")
s = s.replace(old, new)
open(path, "w").write(s)
print(f"{path}: {len(edits)} edits")
# ── prepare: emit-top-k + blocked-restart ────────────────────────────────
P = "minipatch/selffb/selffb_v2_prepare.py"
apply(P, [
# emit-top-k truncation at emission
(""" if merged:
pub = {"inputs": [t["input"] for t in merged],
"outputs": [t["output"] for t in merged]}""",
""" emit = merged[:args.emit_top_k] if args.emit_top_k > 0 else merged
if emit:
pub = {"inputs": [t["input"] for t in emit],
"outputs": [t["output"] for t in emit]}"""),
(""" if any(t.get("out_validator") for t in merged):
# D-cut (C): per-test property validators ride inside
# public_tests verbatim to the (patched) probe harness
pub["out_validators"] = [t.get("out_validator") for t in merged]
rec = {"id": pid, "n_tests": len(merged),
"public_tests": json.dumps(pub)}""",
""" if any(t.get("out_validator") for t in emit):
# D-cut (C): per-test property validators ride inside
# public_tests verbatim to the (patched) probe harness
pub["out_validators"] = [t.get("out_validator") for t in emit]
rec = {"id": pid, "n_tests": len(emit),
"public_tests": json.dumps(pub)}"""),
# streak machinery now also serves blocked-restart
(""" fire_counts = None
if merged and (args.emit_order == "failcount" or args.fb_summary
or args.trace_repair):""",
""" fire_counts = None
if merged and (args.emit_order == "failcount" or args.fb_summary
or args.trace_repair or args.blocked_restart):"""),
(""" if args.trace_repair:
blocked = sum(1 for res in mres
if any(test_fires(res[j], t)
for j, t in enumerate(merged)))
funnel["trace_blocked_frac"] = round(
blocked / max(1, len(fc_cands)), 3)""",
""" if args.trace_repair or args.blocked_restart:
blocked = sum(1 for res in mres
if any(test_fires(res[j], t)
for j, t in enumerate(merged)))
funnel["trace_blocked_frac"] = round(
blocked / max(1, len(fc_cands)), 3)"""),
(""" if args.trace_repair and fire_counts:
bf = funnel.get("trace_blocked_frac", 0.0)""",
""" if (args.trace_repair or args.blocked_restart) and fire_counts:
bf = funnel.get("trace_blocked_frac", 0.0)"""),
(""" funnel["trace_streak"] = streak
if streak >= args.trace_streak and max(fire_counts) > 0:""",
""" funnel["trace_streak"] = streak
# ── RT-cut: blocked-restart — population-level diversity injection.
# Under the canonical operator all parents share ONE prompt, so
# restart = show only the best few failed parents and demand
# structurally different fresh attempts (renderer side).
if (args.blocked_restart and streak >= args.trace_streak):
async with lock:
with open(args.out + ".restart.jsonl", "a") as rf:
rf.write(json.dumps({"id": pid, "loop": args.loop,
"keep": args.restart_keep}) + "\\n")
funnel["restart_fired"] = True
if args.trace_repair and streak >= args.trace_streak and max(fire_counts) > 0:"""),
(""" ap.add_argument("--trace-blocked-frac", type=float, default=0.5)
ap.add_argument("--trace-streak", type=int, default=2)""",
""" ap.add_argument("--trace-blocked-frac", type=float, default=0.5)
ap.add_argument("--trace-streak", type=int, default=2)
ap.add_argument("--emit-top-k", type=int, default=0,
help="emit only the first K tests of the (ordered) bank to "
"the feedback suite (0 = all); bank itself unchanged")
ap.add_argument("--blocked-restart", action="store_true",
help="RT-cut: on trace-streak, write a restart row -> the "
"renderer shows only --restart-keep parents and demands "
"structurally fresh attempts (diversity injection)")
ap.add_argument("--restart-keep", type=int, default=4)"""),
])
# fix: the trace-repair summary emission was indented under its old `if`; the
# new combined gate rewrote only the header. Verify the jtop block still refers
# to the right condition (it now sits under the trace_repair-only if above).
# ── harness: instrumented execution trace on first fail ──────────────────
H = "minipatch/scripts/lcb_public_probe_harness_spj.py"
apply(H, [
("""def run_stdin(code, inputs, outputs, tl, max_fails=1, checker_path=None, order=None,
oval_paths=None):""",
'''def _traced_exec(compiled, stdin_text, tl, src, max_events=48):
"""RT-cut (env LCB_TRACE_EXEC=1): re-execute ONE failing test under
sys.settrace, returning a compact "last executed lines + variable changes"
trace (the DebugRepair/TraceCoder-style runtime-state channel). Best-effort:
any tracer failure returns None and the feedback is unchanged."""
lines = src.split("\\n")
events, prev = [], {}
def tracer(frame, event, arg):
if event == "line" and frame.f_code.co_filename == "<candidate>":
ch = {}
try:
for k, v in list(frame.f_locals.items()):
if k.startswith("__"):
continue
try:
r = repr(v)
except Exception: # noqa: BLE001
r = "<unrepr>"
if len(r) > 48:
r = r[:45] + "..."
if prev.get(k) != r:
ch[k] = r
prev[k] = r
except Exception: # noqa: BLE001
pass
events.append((frame.f_lineno, ch))
if len(events) > max_events:
events.pop(0)
return tracer
old_in, old_out = sys.stdin, sys.stdout
sys.stdin = _mk_stdin(stdin_text)
buf, raw = _mk_stdout()
sys.stdout = buf
tail = ""
try:
sys.settrace(tracer)
_alarm(min(tl, 5.0))
try:
exec(compiled, {"__name__": "__main__"})
except SystemExit:
pass
_cancel()
except TimeoutError:
_cancel(); tail = "\\n[trace cut: TIME LIMIT hit here — the lines above are the hot loop]"
except Exception as e: # noqa: BLE001
_cancel(); tail = f"\\n[trace ends at the raising line: {type(e).__name__}: {e}]"
finally:
sys.settrace(None)
sys.stdin, sys.stdout = old_in, old_out
if not events:
return None
out = []
for ln, ch in events[-max_events:]:
srcl = lines[ln - 1].strip() if 0 < ln <= len(lines) else "?"
s = f"L{ln}: {srcl[:90]}"
if ch:
s += " || " + ", ".join(f"{k}={v}" for k, v in list(ch.items())[:6])
out.append(s)
txt = "\\n".join(out) + tail
return txt[-2400:]
def run_stdin(code, inputs, outputs, tl, max_fails=1, checker_path=None, order=None,
oval_paths=None):'''),
(""" cat = fails[0]["kind"] if fails else "all_pass"
return (cat, npass, len(inputs), n_ran, fails)""",
""" cat = fails[0]["kind"] if fails else "all_pass"
if (fails and os.environ.get("LCB_TRACE_EXEC")
and fails[0].get("input") is not None
and fails[0]["kind"] in ("wrong_answer", "runtime_error", "timeout")):
try:
compiled2 = compile(code, "<candidate>", "exec")
tr = _traced_exec(compiled2, fails[0]["input"], tl, code)
if tr:
fails[0]["trace"] = tr
except Exception: # noqa: BLE001
pass
return (cat, npass, len(inputs), n_ran, fails)"""),
])
# ── renderer: show trace; restart mode ───────────────────────────────────
A = "minipatch/benchmarks/livecodebench/_feedback_aggregate.py"
apply(A, [
(""" if kind == "wrong_answer":
parts.append(f"[test {f.get('idx')}] wrong_answer\\nInput:\\n{_trunc(f.get('input'))}\\n"
f"Expected output:\\n{_trunc(f.get('expected'))}\\nActual output:\\n{_trunc(f.get('actual'))}")
elif kind in ("runtime_error", "no_callable", "compile_error"):
parts.append(f"[test {f.get('idx')}] {kind}\\nInput:\\n{_trunc(f.get('input'))}\\n"
f"Error:\\n{_trunc(f.get('error'), 300)}")""",
""" if kind == "wrong_answer":
parts.append(f"[test {f.get('idx')}] wrong_answer\\nInput:\\n{_trunc(f.get('input'))}\\n"
f"Expected output:\\n{_trunc(f.get('expected'))}\\nActual output:\\n{_trunc(f.get('actual'))}")
elif kind in ("runtime_error", "no_callable", "compile_error"):
parts.append(f"[test {f.get('idx')}] {kind}\\nInput:\\n{_trunc(f.get('input'))}\\n"
f"Error:\\n{_trunc(f.get('error'), 300)}")
if f.get("trace"):
# RT-cut: actual runtime states beat outcome-only feedback
parts.append("RUNTIME TRACE of THIS code on that input (last executed "
"lines, with variable changes) — find the first line where "
"the state diverges from what the statement requires:\\n"
+ _trunc(f.get("trace"), 2400))"""),
])
C = "minipatch/benchmarks/livecodebench/_feedback_canonical.py"
apply(C, [
(""" parts, n_blocks = [], 0
summ = _summary_for(pid)""",
""" parts, n_blocks = [], 0
# RT-cut restart mode: LCB_FB_RESTART jsonl of {id, loop, keep} (last row
# wins). For flagged problems show only the FIRST `keep` parents and
# demand structurally different fresh attempts. Env unset -> identical.
restart_keep = None
rp = os.environ.get("LCB_FB_RESTART")
if rp and os.path.exists(rp):
try:
for _line in open(rp):
_r = json.loads(_line)
if str(_r.get("id")) == str(pid):
restart_keep = int(_r.get("keep", 4))
except Exception: # noqa: BLE001
restart_keep = None
summ = _summary_for(pid)"""),
(""" for j, (c, a) in enumerate(zip(candidates, fbs), 1):
parts.append(f"\\n---- Solution {j} ----\\n{(c or '').strip()}\\n")
if a[0] is not None:
parts.append(f"---- Visible feedback on Solution {j} ----\\n{a[0]}\\n")
n_blocks += 1""",
""" shown = candidates if restart_keep is None else candidates[:max(1, restart_keep)]
for j, (c, a) in enumerate(zip(shown, fbs), 1):
parts.append(f"\\n---- Solution {j} ----\\n{(c or '').strip()}\\n")
if a[0] is not None:
parts.append(f"---- Visible feedback on Solution {j} ----\\n{a[0]}\\n")
n_blocks += 1
if restart_keep is not None:
parts.append(
"\\n---- RESTART DIRECTIVE ----\\n"
f"This problem has resisted repair for multiple rounds; only {len(shown)} "
"of the failed attempts are shown above. Do NOT produce another variation "
"of those approaches — they share a flaw. Re-read the statement from "
"scratch and write a structurally DIFFERENT solution: different algorithm, "
"different reading of the tricky clause, or a simple brute-force if limits "
"allow. Diversity matters more than polish this round.\\n")""" ),
])
print("patch v3 complete")
|