#!/usr/bin/env python3 # -*- coding: utf-8 -*- r""" nwp_v3_counterexample_engine.py =============================== Pure-CPU engine for **`NWP-v3` (Next-CodeWazn Prediction v3: *Tawaqquf* Self-Test Quarantine + Stage 18.8 True-Diction Fusion + *Al-Taṣghīr* Minimal-Counterexample Witness Judging)**! Directly fixes the 4 root causes that left `40` already-solved `Oracle@8` tasks on the table in Stage 19.2 (`506/615` selected vs `546/615` `Oracle@8`): 1. **Al-Azharī *Tawaqquf* Single-Witness Self-Test Quarantine (`AZ-01`, `Tahdhīb` L613–616)**: When `>= 3` licit candidates pass public tests, any LLM-synthesized self-assertion (`tard`/`aks`) passed by ONLY `1` candidate (`agree == 1`) is quarantined (`w = 0.10` instead of `1.00`) so a coinciding hallucinated assertion can never override a multi-candidate consensus cluster. 2. **Stage 18.8 True-Diction Fusion (`khalil_code_wazn_calculator.py`)**: Runs `score_candidate_true_diction` on every unique candidate (live `inspect.signature` `API_MUHMAL` hard kills, mathematical law oracles, radix negative traps, unmemoized exponential recursion, tuple-arity mismatches, input mutation checks) — recovering Stage 18.8's `154/164` `HumanEval+` edge! 3. **Al-Mubarrad *al-Taṣghīr* Minimal-Counterexample Multi-Witness Discovery (`MB-03`, `Muqtaḍab` L9863)**: Fuses LLM probe calls with deterministic Al-Khalīl `root_probes` (`synthesize_deterministic_root_inputs`), collects ALL concrete inputs `x*` where Candidate A and Candidate B disagree, sorts them **shortest-first** (*al-Taṣghīr* downscaling to minimal form!), and presents up to `3` concrete `(call -> out_A vs out_B)` witnesses to the symmetric judge! 4. **Al-Akhfash De Morgan (`AK-02`) + Al-Zajjājī Polarity (`ZH-02`) Symmetric Judge Prompt**: Highlights negated disjunctions (`NOT(X) AND NOT(Y)`) and concrete input-output witnesses so the symmetric `Judge(A,B)` + `Judge(B,A)` tournament traces the exact minimal counterexample! """ from __future__ import annotations import ast import concurrent.futures import math import re import sys from pathlib import Path from typing import Any, Dict, List, Optional, Tuple ROOT = Path("/workspace/rootstar") if Path("/workspace/rootstar").exists() else Path(__file__).resolve().parent.parent if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from scripts.andalusian_al_farq_verifier import ( # noqa: E402 _run_candidate_probes, extract_probe_calls_from_tests, ) from scripts.andalusian_code_verifier import khalil_code_licit_check # noqa: E402 from scripts.eval_code_sandbox import _run_script_subprocess, extract_python_code # noqa: E402 from scripts.khalil_code_wazn_calculator import ( # noqa: E402 CodeRoot, extract_code_root, score_candidate_true_diction, synthesize_deterministic_root_inputs, ) from scripts.stage21_nwp_trace_engine import compile_ak02_negation_hint # noqa: E402 def normalize_ast_key(code: str) -> str: try: return ast.unparse(ast.parse(code)) except Exception: return re.sub(r"\s+", " ", (code or "").strip()) def _format_probe_out(out_pair: Tuple[str, str]) -> str: kind, val = out_pair if kind == "OK": return str(val) if str(val).startswith("EXC:"): return f"raises {val[4:]}" return f"raises {val}" def find_multi_counterexamples_mb03( probe_calls: List[str], sig_a: Optional[Tuple[Tuple[str, str], ...]], sig_b: Optional[Tuple[Tuple[str, str], ...]], code_root: Optional[CodeRoot] = None, root_probes: Optional[List[Tuple[Any, ...]]] = None, td_res_a: Optional[List[str]] = None, td_res_b: Optional[List[str]] = None, max_witnesses: int = 3, ) -> List[Dict[str, Any]]: """ MB-03 (*al-Taṣghīr Yarudd ilā al-Aṣl*): Collects ALL concrete calls where Candidate A and Candidate B return different outputs across BOTH LLM-extracted probe calls and deterministic Al-Khalīl `root_probes`, then sorts them by expression length ascending (minimal counterexample first!) and returns up to `max_witnesses`. """ diffs: List[Dict[str, Any]] = [] seen_calls = set() if sig_a is not None and sig_b is not None and len(sig_a) == len(probe_calls) and len(sig_b) == len(probe_calls): for call_expr, oa, ob in zip(probe_calls, sig_a, sig_b): if oa != ob and call_expr not in seen_calls: seen_calls.add(call_expr) diffs.append( { "call_expr": call_expr, "out_a": oa, "out_b": ob, "source": "probe_call", } ) if ( code_root is not None and code_root.entry_point and root_probes and td_res_a is not None and td_res_b is not None and len(td_res_a) == len(root_probes) and len(td_res_b) == len(root_probes) ): for inp, ra, rb in zip(root_probes, td_res_a, td_res_b): if ra != rb: arg_str = ", ".join(repr(x) for x in inp) call_expr = f"{code_root.entry_point}({arg_str})" if call_expr not in seen_calls: seen_calls.add(call_expr) oa = ("ERR", ra[4:]) if str(ra).startswith("EXC:") else ("OK", str(ra)) ob = ("ERR", rb[4:]) if str(rb).startswith("EXC:") else ("OK", str(rb)) diffs.append( { "call_expr": call_expr, "out_a": oa, "out_b": ob, "source": "khalil_root_probe", } ) # MB-03 *al-Taṣghīr*: sort shortest/simplest concrete counterexample first! diffs.sort(key=lambda d: (len(d["call_expr"]), 0 if d["source"] == "khalil_root_probe" else 1, d["call_expr"])) return diffs[:max_witnesses] def build_nwp_v3_counterexample_judge_prompt( user_prompt: str, code_a: str, trace_a: str, code_b: str, trace_b: str, counterexamples: Optional[List[Dict[str, Any]]] = None, swapped: bool = False, ) -> str: """ Constructs the NWP-v3 Symmetric Pairwise Judge prompt combining: - AK-02 De Morgan Negated Constraint Reminder - MB-03 Minimal Concrete Counterexample Witnesses (`x* -> y_A vs y_B`) - True-Diction + Public/Consensus Execution Summary - ZH-02 Polarity Checklist (`[WAJIB]` positive + `[MUMTANI']` negated requirements) """ ak02_hint = compile_ak02_negation_hint(user_prompt) ak02_blk = f"\nDe Morgan Constraint Guard [AK-02]: {ak02_hint}\n" if "AK-02" in ak02_hint else "" ce_lines: List[str] = [] if counterexamples: ce_lines.append("=== CONCRETE COUNTEREXAMPLE WITNESSES (Shortest First [MB-03 al-Taṣghīr]) ===") ce_lines.append("Candidate A and Candidate B produce DIFFERENT outputs on these exact concrete calls:") for idx, ce in enumerate(counterexamples[:3], start=1): oa = ce["out_b"] if swapped else ce["out_a"] ob = ce["out_a"] if swapped else ce["out_b"] ce_lines.append( f" Witness #{idx}: `{ce['call_expr']}`\n" f" -> Candidate A output: `{_format_probe_out(oa)}`\n" f" -> Candidate B output: `{_format_probe_out(ob)}`" ) ce_lines.append( "MANDATORY STEP: Inside ``, trace Witness #1 step-by-step against the Specification to prove which output is right!\n" ) ce_blk = "\n".join(ce_lines) return ( f"Audit **Candidate A** vs **Candidate B** against EVERY requirement of the Specification below.\n\n" f"=== SPECIFICATION ===\n{user_prompt}\n" f"{ak02_blk}\n" f"{ce_blk}\n" f"=== CANDIDATE A ===\n```python\n{code_a[:3400]}\n```\n" f"Verification Ledger A: {trace_a[:550]}\n\n" f"=== CANDIDATE B ===\n```python\n{code_b[:3400]}\n```\n" f"Verification Ledger B: {trace_b[:550]}\n\n" f"Audit Checklist (Al-Sibr wa-l-Taqsīm + ZH-02 Polarity Protocol):\n" f" 1. [MB-03 Counterexample Witness]: If Concrete Counterexample Witnesses are listed above, trace Witness #1 by hand and determine whether Candidate A or Candidate B produces the spec-mandated result.\n" f" 2. [WAJIB Positive Contract]: Exact signature, return type, ordering, tie-breaking, and value semantics.\n" f" 3. [MUMTANI' Negated & Edge Guards]: Empty/zero/negative boundaries, required exceptions (`Raises:`), non-mutation, and time complexity.\n" f" 4. [Musta'mal API Truth]: Real Python 3 library signatures and return types.\n\n" f"Complete your audit concisely INSIDE `` (do NOT pick TIE unless both candidates are behaviorally identical). " f"Immediately after ``, your VERY FIRST LINE must be ONLY one of:\n" f"VERDICT: A\nVERDICT: B\nVERDICT: TIE\n" f"(followed optionally by ONE short sentence naming the decisive witness or bug)." ) def evaluate_nwp_v3_matrix( candidates: List[str], cand_logprobs: List[float], prompt_text: str, public_tests: List[str], tard_tests: List[str], aks_tests: List[str], *, entry_point: Optional[str] = None, code_root: Optional[CodeRoot] = None, root_probes: Optional[List[Tuple[Any, ...]]] = None, setup_code: str = "", prompt_imports: str = "", quarantine_single_witness: bool = True, max_workers: int = 10, timeout_sec: float = 2.5, ) -> Dict[str, Any]: """ NWP-v3 Unified Verification Matrix: 1. Static Licit Check + Stage 18.8 `score_candidate_true_diction` (live `inspect.signature` + deterministic `root_probes` + math laws). 2. Public doctests (`100.0` each) + `*al-Ṭard*` + `*al-ʿAks*` self-tests WITH `AZ-01` *Tawaqquf* single-witness quarantine! 3. Multi-witness `MB-03` *al-Taṣghīr* minimal counterexample discovery across LLM probe calls + deterministic `root_probes`! """ n_c = len(candidates) codes = [extract_python_code(c) for c in candidates] if code_root is None: code_root = extract_code_root(prompt_text, entry_point=entry_point) if root_probes is None: root_probes = synthesize_deterministic_root_inputs(code_root) licit_info = [khalil_code_licit_check(code, prompt_text, entry_point=entry_point) for code in codes] static_ok = [li["is_licit"] for li in licit_info] static_errs = [li["hard_issues"] for li in licit_info] # Deduplicate unique code strings u_map: Dict[str, int] = {} c_to_u: List[int] = [] u_codes: List[str] = [] for code in codes: if code not in u_map: u_map[code] = len(u_codes) u_codes.append(code) c_to_u.append(u_map[code]) # Run Stage 18.8 True-Diction (AST + Live API + Deterministic Root Probes + Math Oracles) on unique valid candidates! u_td: Dict[int, Dict[str, Any]] = {} valid_us = [ui for ui in range(len(u_codes)) if any(static_ok[i] for i, u in enumerate(c_to_u) if u == ui)] def _run_td(ui: int) -> Tuple[int, Dict[str, Any]]: full_c = f"{prompt_imports}\n{setup_code}\n\n{u_codes[ui]}".strip() if (prompt_imports or setup_code) else u_codes[ui] return ui, score_candidate_true_diction(full_c, prompt_text, code_root, probe_inputs=root_probes) if valid_us: with concurrent.futures.ThreadPoolExecutor(max_workers=min(max_workers, len(valid_us))) as ex: for ui, td_res in ex.map(_run_td, valid_us): u_td[ui] = td_res # Apply Tier-1 True-Diction `is_licit` kills (e.g., live `inspect.signature` API_MUHMAL or return tuple arity mismatch) api_muhmal_kills = 0 for ci in range(n_c): if not static_ok[ci]: continue td_c = u_td.get(c_to_u[ci]) if td_c is not None and not td_c["is_licit"]: static_ok[ci] = False static_errs[ci] = list(td_c["ast"].get("hard_issues", ["TRUE_DICTION_MUHMAL"])) api_muhmal_kills += 1 valid_us = [ui for ui in range(len(u_codes)) if any(static_ok[i] for i, u in enumerate(c_to_u) if u == ui)] # Deduplicate tests while keeping source tag seen_t = set() all_tests: List[Tuple[str, str]] = [] for t in public_tests: if t not in seen_t: seen_t.add(t) all_tests.append(("pub", t)) for t in tard_tests: if t not in seen_t: seen_t.add(t) all_tests.append(("tard", t)) for t in aks_tests: if t not in seen_t: seen_t.add(t) all_tests.append(("aks", t)) n_pub = sum(1 for k, _ in all_tests if k == "pub") u_pass: Dict[Tuple[int, int], bool] = {} u_first_err: Dict[int, str] = {} u_pub_err: Dict[int, str] = {} def _exec_t(u_idx: int, t_idx: int, t_kind: str, t_stmt: str) -> Tuple[int, int, str, bool, str]: script = f"{prompt_imports}\n{setup_code}\n\n{u_codes[u_idx]}\n\n{t_stmt}\n" ok, err = _run_script_subprocess(script, timeout_sec=timeout_sec) return u_idx, t_idx, t_kind, ok, err jobs = [(ui, ti, tk, ts) for ui in valid_us for ti, (tk, ts) in enumerate(all_tests)] if jobs: with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as ex: for ui, ti, tk, ok, err in ex.map(lambda j: _exec_t(*j), jobs): u_pass[(ui, ti)] = ok if not ok: if tk == "pub" and ui not in u_pub_err: u_pub_err[ui] = err if ui not in u_first_err: u_first_err[ui] = err # Count how many candidates survive public tests pub_survivors = sum( 1 for ci in range(n_c) if static_ok[ci] and all(u_pass.get((c_to_u[ci], pi), False) for pi in range(n_pub)) ) # AZ-01 *Tawaqquf* Consensus Self-Test Weighting: # Quarantine single-witness assertions (`agree == 1`) when `pub_survivors >= 3` so a lone hallucinated # self-test cannot poison the score matrix! test_w: List[float] = [] quarantined_assertions = 0 for ti, (tk, _) in enumerate(all_tests): if tk == "pub": test_w.append(100.0) else: agree = 0 for ci in range(n_c): ui = c_to_u[ci] if not static_ok[ci]: continue pub_all = all(u_pass.get((ui, pi), False) for pi in range(n_pub)) if pub_all and u_pass.get((ui, ti), False): agree += 1 if agree == 0: test_w.append(0.0) elif quarantine_single_witness and agree == 1 and pub_survivors >= 3: test_w.append(0.10) quarantined_assertions += 1 else: mult = 1.15 if (tk == "aks" and agree >= 2) else 1.0 test_w.append(mult * math.sqrt(agree)) # Execute LLM probe calls AND combine with deterministic `root_probes` for behavioral clustering! probe_calls = extract_probe_calls_from_tests([ts for tk, ts in all_tests], entry_point) u_probes: Dict[int, Optional[List[Tuple[str, str]]]] = {} if probe_calls and len(valid_us) >= 2: with concurrent.futures.ThreadPoolExecutor(max_workers=min(max_workers, len(valid_us))) as ex: fmap = { ex.submit(_run_candidate_probes, u_codes[ui], probe_calls, prompt_imports, setup_code, timeout_sec): ui for ui in valid_us } for fut in concurrent.futures.as_completed(fmap): u_probes[fmap[fut]] = fut.result() # Build joint behavioral signature = (LLM probe outputs + deterministic Al-Khalīl root_probe outputs)! sig_counts: Dict[Tuple[Any, ...], int] = {} c_sigs: List[Optional[Tuple[Any, ...]]] = [] c_llm_sigs: List[Optional[Tuple[Tuple[str, str], ...]]] = [] c_td_results: List[List[str]] = [] for ci in range(n_c): ui = c_to_u[ci] td_c = u_td.get(ui, {}) td_res_list = list(td_c.get("probes", {}).get("results", [])) c_td_results.append(td_res_list) if not static_ok[ci]: c_sigs.append(None) c_llm_sigs.append(None) continue p_all = all(u_pass.get((ui, pi), False) for pi in range(n_pub)) pr = u_probes.get(ui) llm_sig = tuple(pr) if pr is not None else () c_llm_sigs.append(tuple(pr) if pr is not None else None) if p_all and (pr is not None or td_res_list): joint_sig = (llm_sig, tuple(td_res_list)) sig_counts[joint_sig] = sig_counts.get(joint_sig, 0) + 1 c_sigs.append(joint_sig) else: c_sigs.append(None) scores: List[float] = [] pub_counts: List[int] = [] syn_counts: List[int] = [] td_scores: List[float] = [] for ci in range(n_c): ui = c_to_u[ci] if not static_ok[ci]: scores.append(-1e6 + cand_logprobs[ci]) pub_counts.append(0) syn_counts.append(0) td_scores.append(-100.0) continue p_ok = sum(1 for pi in range(n_pub) if u_pass.get((ui, pi), False)) s_ok = sum(1 for ti in range(n_pub, len(all_tests)) if u_pass.get((ui, ti), False)) w_sum = sum(test_w[ti] for ti in range(len(all_tests)) if u_pass.get((ui, ti), False)) cl_sz = sig_counts.get(c_sigs[ci], 1) if c_sigs[ci] is not None else 1 cl_bonus = 1.5 * math.sqrt(cl_sz) khalil_pen = licit_info[ci]["soft_penalty"] + licit_info[ci]["hadhf_cost"] td_c = u_td.get(ui, {}) td_raw = float(td_c.get("score", 0.0)) td_pen = max(-25.0, min(0.0, td_raw)) td_scores.append(round(td_raw, 3)) score = w_sum + cl_bonus + 0.85 * td_pen + 0.65 * cand_logprobs[ci] - khalil_pen + (0.04 if ci == 0 else 0.0) scores.append(score) pub_counts.append(p_ok) syn_counts.append(s_ok) # Identify top-2 distinct behavioral clusters (both passing ALL public tests!) and extract MB-03 multi-witness counterexamples! al_farq_query: Optional[Dict[str, Any]] = None ranked_clusters: List[Tuple[float, Tuple[Any, ...], List[int]]] = [] by_sig: Dict[Tuple[Any, ...], List[int]] = {} for ci, sig in enumerate(c_sigs): if sig is not None: by_sig.setdefault(sig, []).append(ci) for sig, c_idxs in by_sig.items(): top_sc = max(scores[ci] for ci in c_idxs) ranked_clusters.append((top_sc, sig, c_idxs)) ranked_clusters.sort(key=lambda x: x[0], reverse=True) if len(ranked_clusters) >= 2: sc_a, _sig_a, idxs_a = ranked_clusters[0] sc_b, _sig_b, idxs_b = ranked_clusters[1] rep_a = max(idxs_a, key=lambda c: scores[c]) rep_b = max(idxs_b, key=lambda c: scores[c]) if (sc_a - sc_b) <= 8.5: witnesses = find_multi_counterexamples_mb03( probe_calls=probe_calls, sig_a=c_llm_sigs[rep_a], sig_b=c_llm_sigs[rep_b], code_root=code_root, root_probes=root_probes, td_res_a=c_td_results[rep_a], td_res_b=c_td_results[rep_b], max_witnesses=3, ) if witnesses: w0 = witnesses[0] al_farq_query = { "call_expr": w0["call_expr"], "out_a": w0["out_a"], "out_b": w0["out_b"], "witnesses": witnesses, "idxs_a": idxs_a, "idxs_b": idxs_b, "rep_a": rep_a, "rep_b": rep_b, "score_a": round(sc_a, 3), "score_b": round(sc_b, 3), } best_idx = max(range(n_c), key=lambda i: scores[i]) best_u = c_to_u[best_idx] needs_repair = (not static_ok[best_idx]) or (n_pub > 0 and pub_counts[best_idx] < n_pub) repair_err = "; ".join(static_errs[best_idx]) if not static_ok[best_idx] else (u_pub_err.get(best_u) or u_first_err.get(best_u, "")) if not repair_err and scores[best_idx] <= -1e5: for ui in range(len(u_codes)): td_c = u_td.get(ui, {}) hi = td_c.get("ast", {}).get("hard_issues", []) if hi: repair_err = "; ".join(hi[:2]) break return { "best_idx": best_idx, "best_code": codes[best_idx], "codes": codes, "scores": [round(s, 3) for s in scores], "td_scores": td_scores, "pub_passed": pub_counts, "syn_passed": syn_counts, "n_pub": n_pub, "n_syn": len(all_tests) - n_pub, "num_clusters": len(ranked_clusters), "quarantined_assertions": quarantined_assertions, "api_muhmal_kills": api_muhmal_kills, "al_farq_query": al_farq_query, "needs_repair": needs_repair, "repair_err": repair_err, }