File size: 32,374 Bytes
fede947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
"""Additive `livecodebench-feedback-aggregate` recombination operator (vfonly config).

Frozen config (see tts-sft/docs/LCB_R2C_OLD_VISIBLE_FAILED_ONLY_CONFIRM.md):
  stay-close + top-level "feedback only for failed candidates" note + CHECK-bearing V2-concise
  feedback ONLY for candidates with a visible PUBLIC/sample-test failure + NO block for all_pass.

Public/sample execution ONLY for feedback (hidden tests never touched here). Self-contained and
fully guarded: any error falls back to a no-feedback stay-close prompt so the SE loop never breaks.
The ORIGINAL `livecodebench-aggregate` operator is untouched; this is a separate registration selected
only when the config sets `recombination: livecodebench-feedback-aggregate`.

Env vars (set by the launcher):
  LCB_FB_SEED    seed JSONL with {id, question, ...} (maps the SE `query` text -> problem id)
  LCB_FB_PUBLIC  data/filtered/lcbv6_public_tests.jsonl ({id, public_tests}) — PUBLIC tests only
  LCB_FB_HARNESS absolute path to scripts/lcb_public_probe_harness.py
  LCB_FB_HARNESS_CALL (optional) scripts/taco_call_harness.py for function_call records
                 (testtype "functional" + truthy fn_name); unset -> those records render no
                 feedback block (legacy behavior, audited via tests_found=false)
  LCB_FB_CASE_SELECT (optional) 'shuffle' | 'rotate' — round-5 feedback-case-selection
                 ablation (diversity cell): each probe run traverses the suite in a
                 per-(problem, call-epoch, candidate) deterministic order instead of first-N,
                 so a stuck candidate is shown DIFFERENT failing cases on different loops
                 (ROUND4_RESULTS staleness finding). Unset -> legacy canonical order,
                 prompts bit-identical to round 4. Requires a harness with LCB_PROBE_ORDER
                 support. LCB_FB_CASE_SALT (optional) is folded into every seed.
"""
from __future__ import annotations
import hashlib, json, os, re, subprocess, sys, tempfile, threading
from concurrent.futures import ThreadPoolExecutor

_LOG_LOCK = threading.Lock()


def _log(rec: dict):
    """Append one audit record per recombination call to LCB_FB_LOG (guarded; never raises)."""
    path = os.environ.get("LCB_FB_LOG")
    if not path:
        return
    try:
        with _LOG_LOCK, open(path, "a") as f:
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")
    except Exception:  # noqa: BLE001
        pass

_STAYCLOSE_TOP = """You are given a competitive programming problem, several candidate solutions, and visible execution feedback for the candidates that failed public/sample execution.

Some candidate solutions may be incorrect. Visible execution feedback is provided only for candidates that failed public/sample execution. Candidates without a feedback block are not guaranteed to be correct; they simply have no visible failure signal. Use visible failures as evidence of bugs, but do not overfit only to the shown public/sample tests. Hidden tests are not available.

Your task is to synthesize one correct Python solution.

Correctness is the primary goal. However, to the extent possible, keep the final solution close to the candidate attempts. Prefer repairing, combining, and minimally modifying useful parts of the candidate solutions over writing a completely different solution from scratch. Only deviate substantially from the candidate attempts if their approaches are clearly flawed.

Do not blindly trust any single candidate or any single feedback item. Reason about the full problem constraints.

Return only one complete Python code block enclosed with triple backticks. Do not include explanation outside the code block.

Problem:
{problem}

Candidate solutions and visible feedback:
{blocks}
Now write one improved solution. Return only a single Python code block enclosed with triple backticks."""

_STATE = {"q2pub": None, "by_problem": None, "q2id": None, "prob2id": None}
_EXEC_CACHE: dict[str, dict] = {}
_ROUTE_CACHE: dict[str, bool] = {}  # md5(tests_json) -> is function_call record
# Guards _EXEC_CACHE / _PROBE_EXEC_CACHE / _ROUTE_CACHE get+put (callers are parallelized).
# NEVER held during subprocess.run — duplicate cache misses are acceptable.
_CACHE_LOCK = threading.Lock()
# Epoch eviction cap: with update=replace every loop replaces the population, so cached keys
# from prior loops are dead — but the dict grew forever (~15-20k entries/loop, scales with
# problem count; the multi-node OOM-kill factor). Wholesale clear at the cap is safe: at
# worst it costs re-executing a few in-flight loop's duplicates.
_CACHE_CAP = int(os.environ.get("LCB_FB_CACHE_CAP", "50000"))
# Per-problem recombination-call counter ("epoch"; == loop number when the config makes one
# recombination call per problem per loop, else loop x groups). Always logged to fb_audit
# (closes the round-4 "no loop field" audit gap); under LCB_FB_CASE_SELECT it also drives the
# per-loop probe order. Resets on process restart (resume), so seeds repeat from epoch 1 there.
_EPOCH: dict[str, int] = {}


def _bump_epoch(key: str) -> int:
    with _CACHE_LOCK:
        _EPOCH[key] = _EPOCH.get(key, 0) + 1
        return _EPOCH[key]


def _case_select():
    m = os.environ.get("LCB_FB_CASE_SELECT")
    return m if m in ("shuffle", "rotate") else None


def _probe_env_for(mode: str, pid, epoch: int, code: str) -> dict:
    """Probe-order env for one candidate's exec. The seed varies by problem, epoch, AND
    candidate code hash: identical candidates in one call share the exec cache, distinct
    candidates get distinct orders, and a candidate unchanged across loops still gets a NEW
    order each epoch (the whole point — the epoch in the seed also keys it out of the cache)."""
    seed = "|".join([str(pid), str(epoch),
                     hashlib.md5(code.encode("utf-8", "ignore")).hexdigest()[:8],
                     os.environ.get("LCB_FB_CASE_SALT", "")])
    return {"LCB_PROBE_ORDER": mode, "LCB_PROBE_ORDER_SEED": seed}


def _is_call(tests_json: str) -> bool:
    """Routing rule: testtype == "functional" AND truthy fn_name -> call harness."""
    key = hashlib.md5(tests_json.encode("utf-8", "ignore")).hexdigest()
    with _CACHE_LOCK:
        if key in _ROUTE_CACHE:
            return _ROUTE_CACHE[key]
    try:
        t = json.loads(tests_json)
        v = t.get("testtype") == "functional" and bool(t.get("fn_name"))
    except Exception:  # noqa: BLE001
        v = False
    with _CACHE_LOCK:
        _ROUTE_CACHE[key] = v
    return v


def _load_lookup():
    id2pub = {}
    with open(os.environ["LCB_FB_PUBLIC"]) as f:
        for line in f:
            r = json.loads(line); id2pub[r["id"]] = r["public_tests"]
    q2pub, by_problem, q2id, prob2id = {}, {}, {}, {}
    with open(os.environ["LCB_FB_SEED"]) as f:
        for line in f:
            r = json.loads(line)
            pid = r.get("id")
            if r.get("question"):
                q2id[r["question"]] = pid
            if r.get("problem"):
                prob2id[r["problem"]] = pid
            pub = id2pub.get(pid)
            if pub is None:
                continue
            if r.get("question"):
                q2pub[r["question"]] = pub
            if r.get("problem"):
                by_problem[r["problem"]] = pub  # fallback: raw problem text is a substring of `query`
    return q2pub, by_problem, q2id, prob2id


def _ensure_lookup():
    if _STATE["q2pub"] is None:
        _STATE["q2pub"], _STATE["by_problem"], _STATE["q2id"], _STATE["prob2id"] = _load_lookup()


def _tests_for(query: str):
    _ensure_lookup()
    pub = _STATE["q2pub"].get(query)
    if pub is None:
        for prob, p in _STATE["by_problem"].items():  # robust fallback (≤ subset size)
            if prob and prob in query:
                pub = p
                break
    if pub is not None and _is_call(pub) and not os.environ.get("LCB_FB_HARNESS_CALL"):
        return None  # no call harness configured -> legacy: call rows get no feedback block
    return pub


def _id_for(query: str):
    _ensure_lookup()
    pid = _STATE["q2id"].get(query)
    if pid is not None:
        return pid
    for prob, pid in _STATE["prob2id"].items():
        if prob and prob in query:
            return pid
    return None


def _load_grader_extract():
    """Import the OFFLINE GRADER's extract_code so operator and grader agree on what counts as code.
    Located via LCB_FB_HARNESS's directory (tts-sft/scripts). Guarded: returns None on any failure."""
    try:
        import importlib.util
        sdir = os.path.dirname(os.environ.get("LCB_FB_HARNESS", ""))
        spec = importlib.util.spec_from_file_location(
            "lcb_fb_grader_extract", os.path.join(sdir, "eval_lcbv6_calibration.py"))
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        return mod.extract_code
    except Exception:  # noqa: BLE001
        return None


_GRADER_EXTRACT = _load_grader_extract()
# Fallback: VERBATIM copy of the grader's _CODE_BLOCK regex (eval_lcbv6_calibration.py:34) — keep in sync.
_CODE_BLOCK = re.compile(r"```(?:python|py)?\s*\n?(.*?)```", re.DOTALL)


def _extract_code(text: str) -> str:
    if _GRADER_EXTRACT is not None:
        try:
            return (_GRADER_EXTRACT(text) or "").strip()
        except Exception:  # noqa: BLE001
            pass
    blocks = _CODE_BLOCK.findall(text or "")
    return blocks[-1].strip() if blocks else ""


def _trunc_store(res: dict, n: int = 2000):
    """Bound failure payloads at STORE time (cache lives for the whole run); the render-time
    _trunc(400) is unchanged."""
    try:
        for f in list(res.get("fails") or []) + ([res["first_fail"]] if res.get("first_fail") else []):
            if isinstance(f, dict):
                for k in ("input", "expected", "actual", "error"):
                    v = f.get(k)
                    if isinstance(v, str) and len(v) > n:
                        f[k] = v[:n] + " …[truncated]"
    except Exception:  # noqa: BLE001
        pass
    return res


def _public_result(code: str, tests_json: str, probe_env: dict | None = None) -> dict:
    # probe_env (case-selection order) is part of the cache key: without it, the code+tests
    # cache would serve a stuck candidate the same loop-1 failing cases at every later epoch.
    key = hashlib.md5((code + "\x00" + tests_json
                       + (("\x00" + json.dumps(probe_env, sort_keys=True)) if probe_env else "")
                       ).encode("utf-8", "ignore")).hexdigest()
    with _CACHE_LOCK:
        if key in _EXEC_CACHE:
            return _EXEC_CACHE[key]
    cp = tp = None
    try:
        n = len(json.loads(tests_json)["inputs"])
        # per-record routing: functional+fn_name records run the call harness (KeyError when
        # LCB_FB_HARNESS_CALL is unset -> "unknown" -> no block, same as any harness failure)
        harness = (os.environ["LCB_FB_HARNESS_CALL"] if _is_call(tests_json)
                   else os.environ["LCB_FB_HARNESS"])
        with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as cf:
            cf.write(code); cp = cf.name
        with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as tf:
            tf.write(tests_json); tp = tf.name
        _cap = int(os.environ.get("LCB_FB_TIMEOUT_CAP", "120"))
        p = subprocess.run([sys.executable, harness, cp, tp],
                           capture_output=True, text=True, timeout=min(n * 6 + 20, _cap),
                           env=({**os.environ, **probe_env} if probe_env else None))
        res = json.loads(p.stdout.strip().splitlines()[-1])
    except Exception:  # noqa: BLE001
        res = {"category": "unknown", "first_fail": None}
    finally:
        for x in (cp, tp):
            if x:
                try: os.unlink(x)
                except OSError: pass
    res = _trunc_store(res)
    with _CACHE_LOCK:
        if len(_EXEC_CACHE) >= _CACHE_CAP:
            _EXEC_CACHE.clear()
        _EXEC_CACHE[key] = res
    return res


def _trunc(s, n=400):
    s = "" if s is None else str(s)
    return s if len(s) <= n else s[:n] + " …[truncated]"


def _mark_pass_block(pub: dict):
    """Opt-in (LCB_FB_MARK_PASS=1): explicitly mark verified-correct candidates instead of the
    default silence, with an anti-copy instruction (archive-arm A/B, option 2). Copying is made
    worthless upstream anyway: the semantic archive dedups rename-level copies."""
    n = pub.get("n_total") or pub.get("n_ran")
    return ("Visible execution feedback:\nSTATUS: VERIFIED CORRECT — this candidate passed "
            + (f"all {n} tests" if n else "the full test suite")
            + " that define correctness; it is already saved.\n\nCHECK:\n"
            "Do NOT copy or lightly edit this candidate (renaming variables or reformatting counts "
            "as copying and is worthless). Use it only as evidence the problem is solvable and for "
            "insight into the constraints. Your task is to produce a DIFFERENT correct solution — "
            "a genuinely distinct algorithm or approach.")


def _rich_block(pub: dict, k: int):
    """Multi-failure feedback (opt-in, LCB_FB_MAX_SHOWN>1): up to k failing cases + pass counts.
    With LCB_FB_FULLTESTS=1 the CHECK wording states the truth of the full-test setup (feedback runs
    the SAME suite that defines correctness; no further hidden tests) instead of the legacy
    public-tests leakage-guard wording. Returns None for all_pass/no-signal like _v2_block."""
    if pub.get("category") == "all_pass" and os.environ.get("LCB_FB_MARK_PASS"):
        return _mark_pass_block(pub)
    fails = pub.get("fails") or ([pub["first_fail"]] if pub.get("first_fail") else [])
    if not fails or pub.get("category") in (None, "all_pass", "unknown"):
        return None
    n_pass, n_ran, n_total = pub.get("n_pass"), pub.get("n_ran"), pub.get("n_total")
    counts = ""
    if n_pass is not None and n_ran:
        counts = (f"Passed {n_pass} of {n_ran} executed tests"
                  + (f" ({n_total} total in the suite)" if n_total and n_total != n_ran else "") + ".")
    if os.environ.get("LCB_FB_FULLTESTS"):
        check = ("These failures come from the problem's FULL test suite — the same tests that define "
                 "correctness; there are no additional hidden tests beyond this suite. Fix the underlying "
                 "logic so ALL tests pass; do not hardcode the shown cases.")
    else:
        check = ("Use these visible execution results to identify possible bugs, but do not overfit only "
                 "to the shown tests.")
    parts = []
    for f in fails[:max(1, k)]:
        kind = f.get("kind") or pub.get("category")
        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)}")
        elif kind == "timeout":
            parts.append(f"[test {f.get('idx')}] timeout — did not finish within the time limit.\n"
                         f"Input:\n{_trunc(f.get('input'))}")
    return ("Visible execution feedback:\nSTATUS: " + str(pub.get("category"))
            + ("\n" + counts if counts else "")
            + "\n\nFAILING CASES:\n" + "\n\n".join(parts)
            + "\n\nCHECK:\n" + check)


def _v2_block(pub: dict):
    """CHECK-bearing V2-concise block for visible-failed candidates; None for all_pass / no-signal."""
    k = int(os.environ.get("LCB_FB_MAX_SHOWN", "1"))
    if k > 1:
        return _rich_block(pub, k)
    if pub.get("category") == "all_pass" and os.environ.get("LCB_FB_MARK_PASS"):
        return _mark_pass_block(pub)
    cat = pub.get("category"); ff = pub.get("first_fail")
    head = ("Visible execution feedback:\nSTATUS: {st}\n\nOBSERVED:\n{ob}\n\nDETAIL:\n{dt}\n\nCHECK:\n"
            "Use this visible execution result to identify possible bugs, but do not overfit only to the "
            "shown public/sample test. Hidden tests are not available.")
    if cat == "wrong_answer" and ff:
        return head.format(st="wrong_answer", ob="A shown public/sample test failed.",
                           dt=f"Input:\n{_trunc(ff.get('input'))}\nExpected output:\n{_trunc(ff.get('expected'))}\n"
                              f"Actual output:\n{_trunc(ff.get('actual'))}")
    if cat in ("runtime_error", "no_callable") and ff:
        return head.format(st="runtime_error", ob="The program raised an error on a shown test.",
                           dt=f"Error:\n{_trunc(ff.get('error'), 300)}")
    if cat == "compile_error" and ff:
        return head.format(st="compile_error", ob="The program failed to compile/parse.",
                           dt=f"Error:\n{_trunc(ff.get('error'), 300)}")
    if cat == "timeout":
        return head.format(st="timeout", ob="The program timed out on a shown public/sample test.",
                           dt="The program did not finish within the time limit on a shown test.")
    return None  # all_pass / unknown -> NO block


def _shown_cases(pub: dict):
    """Suite indices of the failing cases a rendered block shows — mirrors the
    _v2_block/_rich_block selection (fails[:max(1,k)], k=LCB_FB_MAX_SHOWN; k==1 -> first_fail
    only). Audit-only (fb_audit `shown_cases`, the round-4 case-identity gap); keep in sync
    with the render path. None when no failing-case block is rendered."""
    if pub.get("category") in (None, "all_pass", "unknown"):
        return None
    fails = pub.get("fails") or ([pub["first_fail"]] if pub.get("first_fail") else [])
    if not fails:
        return None
    k = max(1, int(os.environ.get("LCB_FB_MAX_SHOWN", "1")))
    return [f.get("idx", -1) if isinstance(f, dict) else -1 for f in fails[:k]]


# ---------------------------------------------------------------------------
# B arm: stay-close, NO feedback (attribution control). Wording = the offline-validated
# R0_stayclose prompt (probe_lcb_r2c_recombine.STAYCLOSE_NOFB), verbatim.
# ---------------------------------------------------------------------------
_STAYCLOSE_NOFB = """You are given a competitive programming problem and several candidate solutions.

Some candidate solutions may be incorrect.

Your task is to synthesize one correct Python solution.

Correctness is the primary goal. However, to the extent possible, keep the final solution close to the candidate attempts. Prefer repairing, combining, and minimally modifying useful parts of the candidate solutions over writing a completely different solution from scratch. Only deviate substantially from the candidate attempts if their approaches are clearly flawed.

Do not blindly trust any single candidate. Reason about the full problem constraints.

Return only one complete Python code block enclosed with triple backticks. Do not include explanation outside the code block.

Problem:
{problem}

Candidate solutions:
{blocks}
Now write one improved solution. Return only a single Python code block enclosed with triple backticks."""


def stayclose_aggregate(query, candidates, **kwargs):
    """B_stayclose_only: stay-close prompt, never any feedback."""
    if not candidates:
        return query
    blocks = "".join(f"\n---- Solution {j} ----\n{(c or '').strip()}\n" for j, c in enumerate(candidates, 1))
    _log({"id": _id_for(query), "n_candidates": len(candidates), "feedback_type": "none_stayclose_b",
          "fallback": False})
    return _STAYCLOSE_NOFB.format(problem=query, blocks=blocks)


# ---------------------------------------------------------------------------
# C2 arm: vfonly + DISAGREEMENT feedback for all-all_pass groups (gate-passed P1 design,
# docs/LCB_DISAGREEMENT_PROBE.md). Visible-failed groups behave EXACTLY like vfonly; groups whose
# parents all pass public tests get differential testing on cached probe inputs (INPUTS only, no
# expected outputs) and — iff cross-candidate disagreement exists — one factual comparison section.
# Extra env: LCB_FB_PROBE_INPUTS (jsonl {id, probe_inputs}), LCB_FB_PROBE_EXEC (lcb_probe_exec.py).
# ---------------------------------------------------------------------------
_D1_TOP = """You are given a competitive programming problem, several candidate solutions, and a cross-candidate execution comparison.

Some candidate solutions may be incorrect. All candidates pass the shown public/sample tests, but they DISAGREE with each other on additional probe inputs. The correct outputs for these probe inputs are unknown — where candidates disagree, at most one behavior can be correct. Use the disagreements as evidence of latent bugs, but determine which logic is correct by reasoning about the problem statement; do not assume the majority behavior is correct. Hidden tests are not available.

Your task is to synthesize one correct Python solution.

Correctness is the primary goal. However, to the extent possible, keep the final solution close to the candidate attempts. Prefer repairing, combining, and minimally modifying useful parts of the candidate solutions over writing a completely different solution from scratch. Only deviate substantially from the candidate attempts if their approaches are clearly flawed.

Do not blindly trust any single candidate or any single feedback item. Reason about the full problem constraints.

Return only one complete Python code block enclosed with triple backticks. Do not include explanation outside the code block.

Problem:
{problem}

Candidate solutions:
{blocks}
---- Cross-candidate execution comparison ----
{comparison}

Now write one improved solution. Return only a single Python code block enclosed with triple backticks."""

_PROBE_STATE = {"inputs": None}
_PROBE_EXEC_CACHE: dict[str, list | None] = {}


def _probe_inputs_for(query: str):
    if _PROBE_STATE["inputs"] is None:
        m = {}
        try:
            with open(os.environ["LCB_FB_PROBE_INPUTS"]) as f:
                for line in f:
                    r = json.loads(line); m[r["id"]] = r.get("probe_inputs") or []
        except Exception:  # noqa: BLE001
            pass
        _PROBE_STATE["inputs"] = m
    pid = _id_for(query)
    return (_PROBE_STATE["inputs"].get(pid) or None), pid


_SEED_META = {"m": None}


def _seed_meta_for(query: str):
    """(testtype, fn_name) for the problem — needed by the probe exec harness."""
    if _SEED_META["m"] is None:
        m = {}
        try:
            with open(os.environ["LCB_FB_SEED"]) as f:
                for line in f:
                    r = json.loads(line)
                    m[r["id"]] = (r.get("testtype") or "stdin", r.get("fn_name") or "")
        except Exception:  # noqa: BLE001
            pass
        _SEED_META["m"] = m
    pid = _id_for(query)
    return _SEED_META["m"].get(pid, ("stdin", ""))


def _probe_run(code: str, inputs: list, testtype: str, fn_name: str):
    """Run code on probe inputs (no expected outputs) via the isolated harness. Cached by code+inputs."""
    key = hashlib.md5((code + "\x00" + json.dumps(inputs) + testtype + fn_name).encode("utf-8", "ignore")).hexdigest()
    with _CACHE_LOCK:
        if key in _PROBE_EXEC_CACHE:
            return _PROBE_EXEC_CACHE[key]
    cp = tp = None
    try:
        spec = json.dumps({"inputs": inputs, "testtype": testtype, "fn_name": fn_name, "time_limit": 6})
        with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as cf:
            cf.write(code); cp = cf.name
        with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as tf:
            tf.write(spec); tp = tf.name
        p = subprocess.run([sys.executable, os.environ["LCB_FB_PROBE_EXEC"], cp, tp],
                           capture_output=True, text=True, timeout=len(inputs) * 6 + 20)
        out = p.stdout.strip().splitlines()
        res = json.loads(out[-1])["results"] if out else None
    except Exception:  # noqa: BLE001
        res = None
    finally:
        for x in (cp, tp):
            if x:
                try: os.unlink(x)
                except OSError: pass
    with _CACHE_LOCK:
        if len(_PROBE_EXEC_CACHE) >= _CACHE_CAP:
            _PROBE_EXEC_CACHE.clear()
        _PROBE_EXEC_CACHE[key] = res
    return res


def _build_comparison(probe_inputs, per_parent_results, max_shown=2):
    """Verbatim logic from probe_lcb_disagreement.build_comparison (gate-passed formatting)."""
    def kindval(r):
        return (r["kind"], r["value"] if r["kind"] == "output" else r["kind"])
    rows = []
    for ii, inp in enumerate(probe_inputs):
        beh = [kindval(per_parent_results[p][ii]) for p in range(len(per_parent_results))]
        clusters = {}
        for p, b in enumerate(beh):
            clusters.setdefault(b, []).append(p + 1)
        if len(clusters) < 2:
            continue
        n_err = sum(1 for b in clusters if b[0] != "output")
        rows.append((len(clusters), -n_err, ii, inp, clusters))
    if not rows:
        return None, 0
    rows.sort(key=lambda r: (-r[0], r[1]))
    parts = []
    for _, _, ii, inp, clusters in rows[:max_shown]:
        seg = [f"Probe input:\n{str(inp)[:400]}"]
        for beh, members in sorted(clusters.items(), key=lambda kv: kv[1][0]):
            who = ", ".join(f"Solution {m}" for m in members)
            if beh[0] == "output":
                seg.append(f"{who} output:\n{beh[1][:300]}")
            elif beh[0] == "timeout":
                seg.append(f"{who}: exceeded the time limit on this input")
            else:
                seg.append(f"{who}: raised an error on this input")
        parts.append("\n".join(seg))
    return "\n\n".join(parts), len(rows)


def feedback_disagreement_aggregate(query, candidates, **kwargs):
    """C2: vfonly behavior, plus disagreement comparison for all-all_pass groups."""
    if not candidates:
        return query
    try:
        tests = _tests_for(query)
        sel = _case_select()
        pid_e = _id_for(query)
        epoch = _bump_epoch(str(pid_e) if pid_e is not None
                            else hashlib.md5(query.encode("utf-8", "ignore")).hexdigest()[:12])

        def assess(c):
            if tests is None:
                return ("no_tests", None, None, None)
            code = _extract_code(c)
            if not code:
                return ("no_code", _v2_block({"category": "compile_error",
                        "first_fail": {"error": "No extractable Python code block."}}), None, None)
            penv = _probe_env_for(sel, pid_e, epoch, code) if sel else None
            pub = _public_result(code, tests, penv)
            return (pub.get("category"), _v2_block(pub), _shown_cases(pub),
                    penv["LCB_PROBE_ORDER_SEED"] if penv else None)

        with ThreadPoolExecutor(max_workers=4) as ex:
            assessed = list(ex.map(assess, candidates))
        cats = [a[0] for a in assessed]

        if any(a[1] is not None for a in assessed):
            # visible-failed group -> EXACT vfonly behavior
            parts, n_blocks = [], 0
            for j, (c, a) in enumerate(zip(candidates, assessed), 1):
                parts.append(f"\n---- Solution {j} ----\n{(c or '').strip()}\n")
                if a[1] is not None:
                    parts.append(f"---- Visible feedback on Solution {j} ----\n{a[1]}\n"); n_blocks += 1
            rec = {"id": pid_e, "n_candidates": len(candidates), "categories": cats,
                   "feedback_type": "visible_failed", "n_feedback_blocks": n_blocks,
                   "n_allpass_omitted": cats.count("all_pass"), "tests_found": tests is not None,
                   "fallback": False, "probe_epoch": epoch, "shown_cases": [a[2] for a in assessed]}
            if sel:
                rec["case_select"] = sel
                rec["case_seeds"] = [a[3] for a in assessed]
            _log(rec)
            return _STAYCLOSE_TOP.format(problem=query, blocks="".join(parts))

        # all parents all_pass -> differential testing on probe inputs
        probe_inputs, pid = _probe_inputs_for(query)
        comparison = None; n_dis = 0
        if probe_inputs:
            testtype, fn_name = _seed_meta_for(query)
            with ThreadPoolExecutor(max_workers=4) as ex:
                results = list(ex.map(lambda c: _probe_run(_extract_code(c), probe_inputs, testtype, fn_name),
                                      candidates))
            if all(r is not None for r in results):
                comparison, n_dis = _build_comparison(probe_inputs, results)
        blocks = "".join(f"\n---- Solution {j} ----\n{(c or '').strip()}\n" for j, c in enumerate(candidates, 1))
        if comparison:
            _log({"id": pid, "n_candidates": len(candidates), "categories": cats,
                  "feedback_type": "disagreement", "n_disagreeing_inputs": n_dis, "fallback": False})
            return _D1_TOP.format(problem=query, blocks=blocks, comparison=comparison)
        _log({"id": pid, "n_candidates": len(candidates), "categories": cats,
              "feedback_type": "none_allpass_agree", "fallback": False})
        return _STAYCLOSE_TOP.format(problem=query, blocks=blocks)
    except Exception as e:  # noqa: BLE001 — never break the SE loop
        _log({"id": None, "n_candidates": len(candidates), "fallback": True, "error": f"{type(e).__name__}: {e}"})
        parts = [f"\n---- Solution {j} ----\n{(c or '').strip()}\n" for j, c in enumerate(candidates, 1)]
        return _STAYCLOSE_TOP.format(problem=query, blocks="".join(parts))


def feedback_aggregate(query, candidates, **kwargs):
    if not candidates:
        return query  # loop 0 (matches the original operator's empty-candidate behaviour)
    try:
        tests = _tests_for(query)
        sel = _case_select()
        pid = _id_for(query)
        epoch = _bump_epoch(str(pid) if pid is not None
                            else hashlib.md5(query.encode("utf-8", "ignore")).hexdigest()[:12])

        def assess(c):
            """Return (category, feedback_block_or_None, shown_case_idxs, probe_seed)."""
            if tests is None:
                return ("no_tests", None, None, None)  # lookup miss -> no block (audited via tests_found=False)
            code = _extract_code(c)
            if not code:
                return ("no_code", _v2_block({"category": "compile_error",
                        "first_fail": {"error": "No extractable Python code block."}}), None, None)
            penv = _probe_env_for(sel, pid, epoch, code) if sel else None
            pub = _public_result(code, tests, penv)
            return (pub.get("category"), _v2_block(pub), _shown_cases(pub),
                    penv["LCB_PROBE_ORDER_SEED"] if penv else None)

        with ThreadPoolExecutor(max_workers=4) as ex:
            assessed = list(ex.map(assess, candidates))
        parts, n_blocks = [], 0
        for j, (c, a) in enumerate(zip(candidates, assessed), 1):
            parts.append(f"\n---- Solution {j} ----\n{(c or '').strip()}\n")
            if a[1] is not None:
                parts.append(f"---- Visible feedback on Solution {j} ----\n{a[1]}\n"); n_blocks += 1
        cats = [a[0] for a in assessed]
        rec = {"id": pid, "n_candidates": len(candidates), "categories": cats,
               "n_feedback_blocks": n_blocks, "n_allpass_omitted": cats.count("all_pass"),
               "tests_found": tests is not None, "fallback": False,
               "probe_epoch": epoch, "shown_cases": [a[2] for a in assessed]}
        if sel:
            rec["case_select"] = sel
            rec["case_seeds"] = [a[3] for a in assessed]
        _log(rec)
        return _STAYCLOSE_TOP.format(problem=query, blocks="".join(parts))
    except Exception as e:  # noqa: BLE001 — never break the SE loop; fall back to stay-close, no feedback
        _log({"id": _id_for(query) if candidates else None, "n_candidates": len(candidates),
              "fallback": True, "error": f"{type(e).__name__}: {e}"})
        parts = [f"\n---- Solution {j} ----\n{(c or '').strip()}\n" for j, c in enumerate(candidates, 1)]
        return _STAYCLOSE_TOP.format(problem=query, blocks="".join(parts))