File size: 37,073 Bytes
ce6548c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
"""Controlled dataset builder for Fork-and-Flush probe: Control vs MG-CPIL.

Builds:
  1. IDENTICAL FULL official 6 evaluation suites (exact same seeds, splits & dedup as groundedness_guard/data_builder.py):
       - ood_ragtruth (n=1,500)
       - ood_summeval (full test)
       - ood_frank (full test)
       - ood_finqa (full)
       - psiloqa_test (14 langs, up to 200/lang)
       - lc_rag_needle (4 depths: 250 / 800 / 1,600 / 3,200 tok, 60+/60- = 480 rows)
  2. Controlled ~90K multilingual training set + ~3,500 validation set:
       - variant=control: Exact v3.1 groundedness_guard recipe scaled cleanly to ~90K rows.
       - variant=mg_cpil: Same ~90K budget with:
           * Exact char-level hallucination spans (`hal_spans`) from PsiloQA gold labels,
             MiniCheck composed-paragraph bad sentences, SummEdits difflib edits, and
             Synthetic Minimal-Edit Counterfactuals (numbers/years/polarity/same-doc entity swaps).
           * PsiloQA label-noise fix (drops train rows where labels==[] yet '[HAL]' in annotated_span).
           * Same-document `group_id` for contrastive pairwise ranking (including same-haystack LC pairs!).
           * 4,000 synthetic minimal-edit counterfactuals replacing 4,000 generic WANLI/MultiNLI rows
             (matched total sample budget!).
"""

from __future__ import annotations

import argparse
import difflib
import hashlib
import json
import os
import random
import re
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any

from schema import COUNTERFACTUAL_ANCHORS, DISTRACTOR_CHUNKS, PSILOQA_LANGS

MNLI_PERMISSIVE_GENRES = {
    "government", "telephone", "travel", "oup", "letters",
    "verbatim", "nineeleven", "facetoface", "fundraising",
}

POLARITY_SWAPS: list[tuple[str, str]] = [
    ("increased", "decreased"),
    ("decreased", "increased"),
    ("higher", "lower"),
    ("lower", "higher"),
    ("more than", "less than"),
    ("less than", "more than"),
    ("before", "after"),
    ("after", "before"),
    ("includes", "excludes"),
    ("excludes", "includes"),
    ("included", "excluded"),
    ("excluded", "included"),
    ("largest", "smallest"),
    ("smallest", "largest"),
    ("first", "second"),
    ("cannot", "can"),
    ("never", "always"),
    ("without", "with"),
    ("rose", "fell"),
    ("fell", "rose"),
    ("grew", "shrank"),
    ("approved", "rejected"),
    ("rejected", "approved"),
    ("allowed", "prohibited"),
    ("prohibited", "allowed"),
]

STOP_CAPS = {
    "The", "This", "That", "These", "Those", "There", "Their", "They", "When", "Where",
    "While", "After", "Before", "During", "Although", "However", "Because", "Since",
    "January", "February", "March", "April", "May", "June", "July", "August",
    "September", "October", "November", "December", "Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday", "Sunday", "Document", "Evidence", "Question",
    "Chunk", "According", "In", "On", "At", "By", "For", "From", "With", "And", "But",
}


def _norm_md5(text: str) -> str:
    return hashlib.md5(re.sub(r"\s+", " ", text.strip().lower()).encode("utf-8", errors="ignore")).hexdigest()


def _hash_bucket(text: str, mod: int = 100) -> int:
    return int(hashlib.md5(text.encode("utf-8", errors="ignore")).hexdigest()[:8], 16) % mod


def _write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("w", encoding="utf-8") as f:
        for r in rows:
            f.write(json.dumps(r, ensure_ascii=False) + "\n")


def _embed_in_rag_haystack(context: str, target_chars: int, rng: random.Random) -> str:
    chunks: list[str] = []
    cur = len(context)
    while cur < target_chars:
        c = rng.choice(DISTRACTOR_CHUNKS)
        chunks.append(c)
        cur += len(c) + 2
    if not chunks:
        return context
    pos = rng.randint(0, len(chunks))
    chunks.insert(pos, f"Document Evidence:\n{context}")
    return "\n\n".join(chunks)


def _extract_ragtruth_context(row: dict[str, Any]) -> str:
    raw = row.get("source_info")
    if isinstance(raw, str) and raw.strip().startswith("{"):
        try:
            obj = json.loads(raw)
            if isinstance(obj, dict):
                parts = []
                for k in ("passages", "passage", "context", "document", "text"):
                    if obj.get(k):
                        parts.append(str(obj[k]))
                if parts:
                    return "\n\n".join(parts)
                return json.dumps(obj, ensure_ascii=False)
        except Exception:
            pass
    if isinstance(raw, str) and len(raw.strip()) > 20:
        return raw.strip()
    return str(row.get("prompt") or "").strip()


def _extract_difflib_spans(seed_text: str, edited_text: str) -> tuple[bool, list[list[int]]]:
    """Compute exact character spans in edited_text that were replaced or inserted vs seed_text."""
    if not seed_text or not edited_text or seed_text == edited_text:
        return False, []
    seed_tokens = [m.group(0) for m in re.finditer(r"\S+", seed_text)]
    ed_matches = list(re.finditer(r"\S+", edited_text))
    ed_tokens = [m.group(0) for m in ed_matches]
    if not seed_tokens or not ed_tokens:
        return False, []
    sm = difflib.SequenceMatcher(None, [t.lower() for t in seed_tokens], [t.lower() for t in ed_tokens])
    spans: list[list[int]] = []
    changed_chars = 0
    for tag, _i1, _i2, j1, j2 in sm.get_opcodes():
        if tag in ("replace", "insert") and j2 > j1:
            s = ed_matches[j1].start()
            e = ed_matches[j2 - 1].end()
            spans.append([s, e])
            changed_chars += (e - s)
    if not spans or changed_chars > 0.85 * len(edited_text):
        return False, []
    return True, spans


def _mutate_counterfactual(premise: str, hyp: str, rng: random.Random) -> tuple[str, list[list[int]]] | None:
    """Create a zero-style-leak minimal-edit factual counterfactual + exact mutated char span."""
    # Strategy 1: Year mutation (1900-2029)
    year_matches = list(re.finditer(r"\b(19[0-9]{2}|20[0-2][0-9])\b", hyp))
    if year_matches and rng.random() < 0.70:
        m = rng.choice(year_matches)
        yr = int(m.group(1))
        for delta in rng.sample([-7, -4, -3, -2, 2, 3, 4, 6, 9], k=5):
            ny = yr + delta
            if 1850 <= ny <= 2032 and str(ny) not in premise:
                new_s = str(ny)
                new_hyp = hyp[: m.start()] + new_s + hyp[m.end() :]
                return new_hyp, [[m.start(), m.start() + len(new_s)]]

    # Strategy 2: Numeric / percentage / currency mutation
    num_matches = list(re.finditer(r"(?<![A-Za-z0-9])(\d+(?:,\d{3})*(?:\.\d+)?)(%?)(?![A-Za-z0-9])", hyp))
    if num_matches and rng.random() < 0.70:
        m = rng.choice(num_matches)
        raw_num, pct = m.group(1), m.group(2)
        try:
            val = float(raw_num.replace(",", ""))
            if val > 0:
                factor = rng.choice([0.6, 0.75, 1.35, 1.6, 2.0])
                nval = val * factor
                if "." in raw_num:
                    dec = len(raw_num.split(".")[1])
                    new_num = f"{nval:.{dec}f}"
                else:
                    nint = max(1, int(round(nval)))
                    if nint == int(val):
                        nint = int(val) + rng.choice([2, 3, 5])
                    new_num = f"{nint:,}" if "," in raw_num else str(nint)
                new_tok = new_num + pct
                if new_num != raw_num and new_num not in premise:
                    new_hyp = hyp[: m.start()] + new_tok + hyp[m.end() :]
                    return new_hyp, [[m.start(), m.start() + len(new_tok)]]
        except Exception:
            pass

    # Strategy 3: Same-premise entity swap (intrinsic entity confusion)
    if rng.random() < 0.65:
        prem_ents = [
            e for e in dict.fromkeys(re.findall(r"\b[A-Z][a-z]{3,}(?:\s+[A-Z][a-z]{2,})?\b", premise))
            if e.split()[0] not in STOP_CAPS
        ]
        if len(prem_ents) >= 2:
            in_hyp = [e for e in prem_ents if re.search(rf"\b{re.escape(e)}\b", hyp)]
            not_in_hyp = [e for e in prem_ents if e not in in_hyp and not any(e in h or h in e for h in in_hyp)]
            if in_hyp and not_in_hyp:
                src_e = rng.choice(in_hyp)
                tgt_e = rng.choice(not_in_hyp)
                m = re.search(rf"\b{re.escape(src_e)}\b", hyp)
                if m:
                    new_hyp = hyp[: m.start()] + tgt_e + hyp[m.end() :]
                    return new_hyp, [[m.start(), m.start() + len(tgt_e)]]

    # Strategy 4: Polarity / quantifier / direction swap
    swaps = list(POLARITY_SWAPS)
    rng.shuffle(swaps)
    for src, tgt in swaps:
        m = re.search(rf"\b{re.escape(src)}\b", hyp, flags=re.IGNORECASE)
        if m:
            orig = m.group(0)
            rep = tgt.capitalize() if orig[0].isupper() else tgt
            new_hyp = hyp[: m.start()] + rep + hyp[m.end() :]
            return new_hyp, [[m.start(), m.start() + len(rep)]]

    return None


def _make_rec(
    premise: str,
    hypothesis: str,
    label: int,
    source: str,
    language: str = "en",
    group_id: str | None = None,
    has_span: bool = False,
    hal_spans: list[list[int]] | None = None,
) -> dict[str, Any]:
    if label == 1:
        has_span = True
        hal_spans = []
    return {
        "premise": premise,
        "hypothesis": hypothesis,
        "label": int(label),
        "source": source,
        "language": language,
        "group_id": group_id or _norm_md5(premise),
        "has_span": bool(has_span),
        "hal_spans": hal_spans or [],
    }


def _summarize(rows: list[dict[str, Any]]) -> dict[str, Any]:
    src = Counter(r.get("source", "unknown") for r in rows)
    langs = Counter(r.get("language", "en") for r in rows)
    pos = sum(1 for r in rows if int(r["label"]) == 1)
    span_neg = sum(1 for r in rows if int(r["label"]) == 0 and r.get("has_span"))
    neg_tot = max(1, len(rows) - pos)
    by_g: dict[str, set[int]] = defaultdict(set)
    for r in rows:
        if r.get("group_id"):
            by_g[r["group_id"]].add(int(r["label"]))
    paired_groups = sum(1 for s in by_g.values() if len(s) == 2)
    return {
        "count": len(rows),
        "consistent_rate": round(pos / max(1, len(rows)), 4),
        "neg_with_exact_span": span_neg,
        "neg_exact_span_rate": round(span_neg / neg_tot, 4),
        "same_doc_paired_groups": paired_groups,
        "sources": dict(src),
        "top_languages": dict(langs.most_common(20)),
    }


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--out-dir", type=str, required=True)
    parser.add_argument("--variant", choices=["control", "mg_cpil"], required=True)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--scale", type=float, default=1.0, help="1.0 = ~90K controlled benchmark; 0.1 = fast smoke")
    args = parser.parse_args()

    os.environ.setdefault("HF_HOME", "/tmp/hf")
    from datasets import load_dataset

    rng = random.Random(args.seed)
    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    is_mg = args.variant == "mg_cpil"

    def _sc(n: int) -> int:
        return max(50, int(round(n * args.scale)))

    # ================= 1. BUILD FULL OFFICIAL EVAL SUITES FIRST (100% IDENTICAL TO BASELINE!) =================
    test_suites: dict[str, list[dict[str, Any]]] = {}
    eval_claim_hashes: set[str] = set()
    eval_pair_hashes: set[str] = set()

    # Eval 1: OOD RAGTruth_test (n=1,500)
    try:
        rt_rows = []
        for sp_name in ("qa", "summarization", "data2txt"):
            ds_rt = load_dataset("flowaicom/RAGTruth_test", split=sp_name)
            for row in ds_rt:
                prem = _extract_ragtruth_context(row)
                resp = str(row.get("response") or "").strip()
                sc = row.get("score")
                if len(prem) < 15 or len(resp) < 5 or sc is None:
                    continue
                lbl = 1 if int(sc) == 1 else 0
                rt_rows.append({"premise": prem, "hypothesis": resp, "label": lbl, "source": f"ood_ragtruth_{sp_name}", "language": "en"})
                eval_claim_hashes.add(_norm_md5(resp))
                eval_pair_hashes.add(_norm_md5(prem + " ||| " + resp))
        random.Random(args.seed + 23).shuffle(rt_rows)
        test_suites["ood_ragtruth"] = rt_rows[:1500]
        print(f"[data] OOD RAGTruth test eval: {len(test_suites['ood_ragtruth'])} rows")
    except Exception as e:
        print(f"[warn] Skipping RAGTruth_test: {e}")

    # Eval 2: OOD SummEval (full)
    try:
        ds_se = load_dataset("mteb/summeval", split="test")
        se_rows = []
        for row in ds_se:
            txt = str(row.get("text") or "").strip()
            sums = row.get("machine_summaries") or []
            cons = row.get("consistency") or []
            if len(txt) < 20:
                continue
            for s_t, c_v in zip(sums, cons):
                s_clean = str(s_t or "").strip()
                if len(s_clean) < 10 or c_v is None:
                    continue
                lbl = 1 if float(c_v) >= 5.0 else 0
                se_rows.append({"premise": txt, "hypothesis": s_clean, "label": lbl, "source": "ood_summeval", "language": "en"})
                eval_claim_hashes.add(_norm_md5(s_clean))
                eval_pair_hashes.add(_norm_md5(txt + " ||| " + s_clean))
        random.Random(args.seed + 37).shuffle(se_rows)
        test_suites["ood_summeval"] = se_rows
        print(f"[data] OOD SummEval eval: {len(test_suites['ood_summeval'])} rows")
    except Exception as e:
        print(f"[warn] Skipping SummEval: {e}")

    # Eval 3: OOD FRANK (full test)
    try:
        ds_fr = list(load_dataset("mtc/frank-test-set-with-faithfulness-annotation", split="test"))
        fr_rows = []
        for row in ds_fr:
            art = str(row.get("article") or "").strip()
            summ = str(row.get("summary") or "").strip()
            fac = row.get("Factual")
            if len(art) < 20 or len(summ) < 10 or fac is None:
                continue
            lbl = 1 if bool(fac) else 0
            fr_rows.append({"premise": art, "hypothesis": summ, "label": lbl, "source": "ood_frank", "language": "en"})
            eval_claim_hashes.add(_norm_md5(summ))
            eval_pair_hashes.add(_norm_md5(art + " ||| " + summ))
        random.Random(args.seed + 53).shuffle(fr_rows)
        test_suites["ood_frank"] = fr_rows
        print(f"[data] OOD FRANK eval: {len(test_suites['ood_frank'])} rows")
    except Exception as e:
        print(f"[warn] Skipping FRANK: {e}")

    # Eval 4: OOD FinQA (full)
    try:
        ds_fin = list(load_dataset("Cleanlab/FinQA-hallucination-detection", split="train"))
        fin_rows = []
        for row in ds_fin:
            ctx = str(row.get("context") or "").strip()
            q = str(row.get("query") or "").strip()
            resp = str(row.get("llm_response") or "").strip()
            ic = row.get("is_correct")
            if len(ctx) < 10 or not resp or ic is None:
                continue
            prem = f"{ctx}\n\nQuestion: {q}" if q else ctx
            lbl = 1 if int(ic) == 1 else 0
            fin_rows.append({"premise": prem, "hypothesis": resp, "label": lbl, "source": "ood_finqa", "language": "en"})
            eval_claim_hashes.add(_norm_md5(resp))
            eval_pair_hashes.add(_norm_md5(prem + " ||| " + resp))
        random.Random(args.seed + 11).shuffle(fin_rows)
        test_suites["ood_finqa"] = fin_rows
        print(f"[data] OOD FinQA eval: {len(test_suites['ood_finqa'])} rows")
    except Exception as e:
        print(f"[warn] Skipping FinQA: {e}")

    # Eval 5: PsiloQA test (14 langs) + LC 4-depth needle (exact match!)
    try:
        ds_pq_te = list(load_dataset("s-nlp/PsiloQA", split="test"))
        by_lg: dict[str, list[dict[str, Any]]] = defaultdict(list)
        lc_pos_seeds, lc_neg_seeds = [], []
        for row in ds_pq_te:
            ctx = str(row.get("wiki_passage") or "").strip()
            ans = str(row.get("llm_answer") or "").strip()
            lg = str(row.get("lang") or "en").strip().lower()
            spans = row.get("labels")
            if len(ctx) < 15 or len(ans) < 5 or spans is None:
                continue
            lbl = 1 if len(spans) == 0 else 0
            rec = {"premise": ctx, "hypothesis": ans, "label": lbl, "source": "psiloqa_test", "language": lg}
            by_lg[lg].append(rec)
            eval_claim_hashes.add(_norm_md5(ans))
            eval_pair_hashes.add(_norm_md5(ctx + " ||| " + ans))
            if lg == "en":
                if lbl == 1 and len(lc_pos_seeds) < 60:
                    lc_pos_seeds.append((ctx, ans, 1))
                elif lbl == 0 and len(lc_neg_seeds) < 60:
                    lc_neg_seeds.append((ctx, ans, 0))
        sampled_pq = []
        for lg, items in sorted(by_lg.items()):
            rlg = random.Random(args.seed + _hash_bucket(lg, 997))
            rlg.shuffle(items)
            sampled_pq.extend(items[:200])
        test_suites["psiloqa_test"] = sampled_pq

        if (len(lc_pos_seeds) < 60 or len(lc_neg_seeds) < 60) and test_suites.get("ood_ragtruth"):
            for r in test_suites["ood_ragtruth"]:
                if r["label"] == 1 and len(lc_pos_seeds) < 60 and len(r["premise"]) < 1500:
                    lc_pos_seeds.append((r["premise"], r["hypothesis"], 1))
                elif r["label"] == 0 and len(lc_neg_seeds) < 60 and len(r["premise"]) < 1500:
                    lc_neg_seeds.append((r["premise"], r["hypothesis"], 0))
        lc_rng = random.Random(args.seed + 79)
        lc_rows = []
        for d in (1000, 3200, 6400, 12800):
            for prem, hyp, lbl in lc_pos_seeds + lc_neg_seeds:
                lc_rows.append({
                    "premise": _embed_in_rag_haystack(prem, d, lc_rng),
                    "hypothesis": hyp,
                    "label": lbl,
                    "source": "lc_rag_needle",
                    "language": "en",
                    "approx_token_depth": d // 4,
                })
        test_suites["lc_rag_needle"] = lc_rows
        print(f"[data] PsiloQA test eval: {len(sampled_pq)} | LC 4-depth needle: {len(lc_rows)}")
    except Exception as e:
        print(f"[warn] Skipping PsiloQA test: {e}")

    # ================= 2. BUILD CONTROLLED ~90K MULTILINGUAL TRAIN & ~3.5K VAL =================
    train_rows: list[dict[str, Any]] = []
    val_rows: list[dict[str, Any]] = []

    # Source 1: DocNLI (24K balanced)
    try:
        dn_cap = _sc(24000)
        half_dn = dn_cap // 2
        dn_pos, dn_neg = [], []
        for sp_name, is_val in [("train", False), ("validation", True)]:
            ds_dn = load_dataset("tasksource/doc-nli", split=sp_name, streaming=True)
            v_cnt = 0
            for row in ds_dn:
                if not is_val and len(dn_pos) >= half_dn and len(dn_neg) >= half_dn:
                    break
                if is_val and v_cnt >= _sc(1000):
                    break
                p = str(row.get("premise") or "").strip()
                h = str(row.get("hypothesis") or "").strip()
                l_s = str(row.get("label") or "").strip().lower()
                if len(p) < 25 or len(p) > 10000 or len(h) < 12 or len(h) > 2500 or l_s not in ("entailment", "not_entailment"):
                    continue
                if _norm_md5(h) in eval_claim_hashes or _norm_md5(p + " ||| " + h) in eval_pair_hashes:
                    continue
                lbl = 1 if l_s == "entailment" else 0
                rec = _make_rec(p, h, lbl, "docnli", "en")
                if is_val:
                    val_rows.append(rec)
                    v_cnt += 1
                else:
                    if lbl == 1 and len(dn_pos) < half_dn:
                        dn_pos.append(rec)
                    elif lbl == 0 and len(dn_neg) < half_dn:
                        dn_neg.append(rec)
        train_rows.extend(dn_pos + dn_neg)
        print(f"[data] DocNLI added: {len(dn_pos) + len(dn_neg):,}")
    except Exception as e:
        print(f"[warn] DocNLI skipped: {e}")

    # Source 2: MiniCheck (c2d + d2c + Multi-Sentence Composed Paragraphs with EXACT bad_sent char spans!)
    try:
        mc_c = 0
        per_sp_cap = _sc(10000)
        doc_claims: dict[str, dict[int, list[str]]] = defaultdict(lambda: {0: [], 1: []})
        for sp in ("c2d", "d2c"):
            ds_mc = list(load_dataset("lytang/C2D-and-D2C-MiniCheck", split=sp))
            random.Random(args.seed + _hash_bucket(sp, 997)).shuffle(ds_mc)
            c_sp = 0
            for row in ds_mc:
                if c_sp >= per_sp_cap:
                    break
                doc = str(row.get("doc") or "").strip()
                clm = str(row.get("claim") or "").strip()
                lbl = row.get("label")
                if len(doc) < 15 or len(clm) < 5 or lbl is None:
                    continue
                if _norm_md5(clm) in eval_claim_hashes or _norm_md5(doc + " ||| " + clm) in eval_pair_hashes:
                    continue
                li = 1 if int(lbl) == 1 else 0
                rec = _make_rec(doc, clm, li, f"minicheck_{sp}", "en")
                if _hash_bucket(doc) < 94:
                    train_rows.append(rec)
                    doc_claims[doc][li].append(clm)
                    mc_c += 1
                    c_sp += 1
                elif len(val_rows) < _sc(1800):
                    val_rows.append(rec)

        para_c = 0
        para_cap = _sc(8000)
        docs_with_both = [d for d, m in doc_claims.items() if len(m[1]) >= 2 and len(m[0]) >= 1]
        rng.shuffle(docs_with_both)
        for doc in docs_with_both:
            if para_c >= para_cap:
                break
            pos_list = list(dict.fromkeys(doc_claims[doc][1]))
            neg_list = list(dict.fromkeys(doc_claims[doc][0]))
            if len(pos_list) < 2 or not neg_list:
                continue
            k = min(len(pos_list), rng.randint(2, 4))
            chosen_pos = rng.sample(pos_list, k)
            gid = _norm_md5(doc)
            train_rows.append(_make_rec(doc, " ".join(chosen_pos), 1, "minicheck_para_pos", "en", group_id=gid, has_span=True))
            bad_sent = rng.choice(neg_list)
            mixed = chosen_pos[: max(1, k - 1)]
            ins_idx = rng.randint(0, len(mixed))
            mixed.insert(ins_idx, bad_sent)
            # Compute exact char span of bad_sent inside joined paragraph
            prefix = " ".join(mixed[:ins_idx])
            b_start = (len(prefix) + 1) if prefix else 0
            b_end = b_start + len(bad_sent)
            mixed_str = " ".join(mixed)
            assert mixed_str[b_start:b_end] == bad_sent
            train_rows.append(
                _make_rec(
                    doc,
                    mixed_str,
                    0,
                    "minicheck_para_neg",
                    "en",
                    group_id=gid,
                    has_span=is_mg,
                    hal_spans=[[b_start, b_end]] if is_mg else [],
                )
            )
            para_c += 2
        print(f"[data] MiniCheck added: {mc_c:,} base + {para_c:,} composed paragraph pairs")
    except Exception as e:
        print(f"[warn] MiniCheck skipped: {e}")

    # Source 3: Salesforce/summedits (ALL rows, with difflib exact edit spans in mg_cpil!)
    try:
        ds_sm = list(load_dataset("Salesforce/summedits", split="train"))
        random.Random(args.seed + 137).shuffle(ds_sm)
        sm_c = 0
        sm_span_c = 0
        for row in ds_sm:
            doc = str(row.get("doc") or "").strip()
            summ = str(row.get("summary") or "").strip()
            seed_s = str(row.get("seed_summary") or "").strip()
            lbl = row.get("label")
            if len(doc) < 25 or len(summ) < 12 or lbl is None:
                continue
            if _norm_md5(summ) in eval_claim_hashes or _norm_md5(doc + " ||| " + summ) in eval_pair_hashes:
                continue
            li = 1 if int(lbl) == 1 else 0
            has_sp, sp_list = (False, [])
            if is_mg and li == 0 and seed_s:
                has_sp, sp_list = _extract_difflib_spans(seed_s, summ)
                if has_sp:
                    sm_span_c += 1
            rec = _make_rec(doc, summ, li, "summedits", "en", has_span=has_sp, hal_spans=sp_list)
            if _hash_bucket(doc) < 92:
                train_rows.append(rec)
                sm_c += 1
            else:
                val_rows.append(rec)
        print(f"[data] SummEdits added: {sm_c:,} (exact diff-span negs={sm_span_c:,})")
    except Exception as e:
        print(f"[warn] SummEdits skipped: {e}")

    # Source 4: WANLI (8K control vs 6K mg_cpil — freeing 2K slots for minimal-edit counterfactuals!)
    try:
        ds_w = list(load_dataset("alisawuffles/WANLI", split="train"))
        random.Random(args.seed + 101).shuffle(ds_w)
        w_cap = _sc(6000 if is_mg else 8000)
        half_w = w_cap // 2
        w_pos, w_neg = [], []
        for row in ds_w:
            p = str(row.get("premise") or "").strip()
            h = str(row.get("hypothesis") or "").strip()
            g = str(row.get("gold") or "").strip().lower()
            if len(p) < 10 or len(h) < 5 or g not in ("entailment", "contradiction", "neutral"):
                continue
            if _norm_md5(h) in eval_claim_hashes:
                continue
            lbl = 1 if g == "entailment" else 0
            rec = _make_rec(p, h, lbl, "wanli", "en")
            if lbl == 1 and len(w_pos) < half_w:
                w_pos.append(rec)
            elif lbl == 0 and len(w_neg) < half_w:
                w_neg.append(rec)
            if len(w_pos) >= half_w and len(w_neg) >= half_w:
                break
        train_rows.extend(w_pos + w_neg)
        print(f"[data] WANLI added: {len(w_pos) + len(w_neg):,}")
    except Exception as e:
        print(f"[warn] WANLI skipped: {e}")

    # Source 5: MultiNLI permissive OANC (8K control vs 6K mg_cpil — freeing 2K slots for counterfactuals!)
    try:
        ds_mn = load_dataset("nyu-mll/multi_nli", split="train", streaming=True)
        mn_cap = _sc(6000 if is_mg else 8000)
        half_m = mn_cap // 2
        m_pos, m_neg = [], []
        for row in ds_mn:
            if len(m_pos) >= half_m and len(m_neg) >= half_m:
                break
            if str(row.get("genre") or "").strip().lower() not in MNLI_PERMISSIVE_GENRES:
                continue
            p = str(row.get("premise") or "").strip()
            h = str(row.get("hypothesis") or "").strip()
            l_raw = row.get("label")
            if len(p) < 15 or len(h) < 5 or l_raw not in (0, 1, 2):
                continue
            if _norm_md5(h) in eval_claim_hashes:
                continue
            lbl = 1 if int(l_raw) == 0 else 0
            rec = _make_rec(p, h, lbl, "mnli_oanc", "en")
            if lbl == 1 and len(m_pos) < half_m:
                m_pos.append(rec)
            elif lbl == 0 and len(m_neg) < half_m:
                m_neg.append(rec)
        train_rows.extend(m_pos + m_neg)
        print(f"[data] MultiNLI added: {len(m_pos) + len(m_neg):,}")
    except Exception as e:
        print(f"[warn] MultiNLI skipped: {e}")

    # Source 6: s-nlp/PsiloQA (14 languages, real llm_answer only + gold char spans in mg_cpil!)
    try:
        pq_c = 0
        pq_dropped_noisy = 0
        for sp_name, tgt_list, max_neg_ratio in [("train", train_rows, 2.0), ("validation", val_rows, 2.0)]:
            ds_pq = list(load_dataset("s-nlp/PsiloQA", split=sp_name))
            by_l_cls: dict[str, dict[int, list[dict[str, Any]]]] = defaultdict(lambda: {0: [], 1: []})
            for row in ds_pq:
                lg = str(row.get("lang") or "en").strip().lower()
                if lg not in PSILOQA_LANGS:
                    continue
                ctx = str(row.get("wiki_passage") or "").strip()
                ans = str(row.get("llm_answer") or "").strip()
                spans = row.get("labels")
                ann_span = str(row.get("annotated_span") or "")
                if len(ctx) < 15 or len(ans) < 5 or spans is None:
                    continue
                if _norm_md5(ans) in eval_claim_hashes or _norm_md5(ctx + " ||| " + ans) in eval_pair_hashes:
                    continue
                # Fix discovered PsiloQA label-noise bug in train for mg_cpil
                if is_mg and sp_name == "train" and len(spans) == 0 and "[HAL]" in ann_span:
                    pq_dropped_noisy += 1
                    continue
                lbl = 1 if len(spans) == 0 else 0
                clean_spans = []
                if is_mg and lbl == 0:
                    for pair in spans:
                        if isinstance(pair, (list, tuple)) and len(pair) == 2:
                            s0, e0 = int(pair[0]), int(pair[1])
                            if 0 <= s0 < e0 <= len(ans):
                                clean_spans.append([s0, e0])
                rec = _make_rec(ctx, ans, lbl, "psiloqa", lg, has_span=(is_mg and (lbl == 1 or bool(clean_spans))), hal_spans=clean_spans)
                by_l_cls[lg][lbl].append(rec)

            per_l_cap = _sc(1500) if sp_name == "train" else _sc(100)
            for lg, cls_map in sorted(by_l_cls.items()):
                rlg = random.Random(args.seed + _hash_bucket(lg + sp_name, 997))
                rlg.shuffle(cls_map[0])
                rlg.shuffle(cls_map[1])
                pos_items = cls_map[1][: per_l_cap // 2]
                n_neg = min(len(cls_map[0]), max(len(pos_items), int(len(pos_items) * max_neg_ratio)), per_l_cap - len(pos_items))
                if not pos_items:
                    continue
                if sp_name == "train" and len(pos_items) < n_neg:
                    extra_pos = (pos_items * 2)[: n_neg - len(pos_items)]
                    chosen = pos_items + extra_pos + cls_map[0][:n_neg]
                else:
                    chosen = pos_items + cls_map[0][:n_neg]
                tgt_list.extend(chosen)
                if sp_name == "train":
                    pq_c += len(chosen)
        print(f"[data] PsiloQA added: {pq_c:,} (dropped noisy [HAL]-with-empty-labels={pq_dropped_noisy})")
    except Exception as e:
        print(f"[warn] PsiloQA skipped: {e}")

    # Source 7: Synthetic Minimal-Edit Counterfactual Hard Negatives (MG-CPIL ONLY, replacing 4K WANLI/MNLI)
    if is_mg:
        cf_target = _sc(4000)
        cf_pool = [
            r for r in train_rows
            if r["label"] == 1 and r["source"] in ("docnli", "minicheck_c2d", "minicheck_d2c", "summedits", "psiloqa")
        ]
        rng.shuffle(cf_pool)
        cf_added = 0
        for r in cf_pool:
            if cf_added >= cf_target:
                break
            res = _mutate_counterfactual(r["premise"], r["hypothesis"], rng)
            if res is None:
                continue
            new_hyp, spans = res
            if _norm_md5(new_hyp) in eval_claim_hashes or _norm_md5(r["premise"] + " ||| " + new_hyp) in eval_pair_hashes:
                continue
            train_rows.append(
                _make_rec(
                    r["premise"],
                    new_hyp,
                    0,
                    "synth_minimal_cf",
                    r["language"],
                    group_id=r["group_id"],
                    has_span=True,
                    hal_spans=spans,
                )
            )
            cf_added += 1
        print(f"[data] Synthetic Minimal-Edit Counterfactuals added (MG-CPIL): {cf_added:,}")

    # Source 8: Counterfactual anchors
    for _ in range(6):
        for prem, hyp, lbl in COUNTERFACTUAL_ANCHORS:
            train_rows.append(_make_rec(prem, hyp, lbl, "counterfactual_anchor", "en"))

    # Source 9: Balanced multi-chunk long-context RAG haystacks (6,000 rows)
    lc_total = _sc(6000)
    buckets = [600, 1400, 3000, 6200, 11200]
    pref_src = ("docnli", "minicheck", "summedits", "psiloqa", "synth_minimal_cf")
    if is_mg:
        # Build SAME-HAYSTACK contrastive pairs whenever a doc has both pos & neg!
        by_g_cls: dict[str, dict[int, list[dict[str, Any]]]] = defaultdict(lambda: {0: [], 1: []})
        for r in train_rows:
            if r["source"].startswith(pref_src) and len(r["premise"]) <= 2200:
                by_g_cls[r["group_id"]][r["label"]].append(r)
        paired_gids = [g for g, m in by_g_cls.items() if m[1] and m[0]]
        rng.shuffle(paired_gids)
        lc_added = 0
        for i in range(lc_total // 2):
            d = max(350, buckets[i % len(buckets)] + rng.randint(-150, 250))
            if paired_gids and i < len(paired_gids) * 2:
                g = paired_gids[i % len(paired_gids)]
                ex_p = rng.choice(by_g_cls[g][1])
                ex_n = rng.choice(by_g_cls[g][0])
                haystack = _embed_in_rag_haystack(ex_p["premise"], d, rng)
                hgid = _norm_md5(haystack)
                train_rows.append(_make_rec(haystack, ex_p["hypothesis"], 1, "long_ctx_pos", ex_p["language"], group_id=hgid, has_span=True))
                train_rows.append(
                    _make_rec(
                        haystack,
                        ex_n["hypothesis"],
                        0,
                        "long_ctx_neg",
                        ex_n["language"],
                        group_id=hgid,
                        has_span=ex_n["has_span"],
                        hal_spans=ex_n["hal_spans"],
                    )
                )
                lc_added += 2
            else:
                break
        # Fill any remainder with balanced single haystacks
        pos_pool = [r for r in train_rows if r["label"] == 1 and r["source"].startswith(pref_src) and len(r["premise"]) <= 2200]
        neg_pool = [r for r in train_rows if r["label"] == 0 and r["source"].startswith(pref_src) and len(r["premise"]) <= 2200]
        while lc_added < lc_total and pos_pool and neg_pool:
            d = max(350, buckets[(lc_added // 2) % len(buckets)] + rng.randint(-150, 250))
            ex_p = rng.choice(pos_pool)
            ex_n = rng.choice(neg_pool)
            train_rows.append(_make_rec(_embed_in_rag_haystack(ex_p["premise"], d, rng), ex_p["hypothesis"], 1, "long_ctx_pos", ex_p["language"], has_span=True))
            train_rows.append(_make_rec(_embed_in_rag_haystack(ex_n["premise"], d, rng), ex_n["hypothesis"], 0, "long_ctx_neg", ex_n["language"], has_span=ex_n["has_span"], hal_spans=ex_n["hal_spans"]))
            lc_added += 2
        print(f"[data] Long-Context RAG Haystacks added (MG-CPIL same-haystack paired): {lc_added:,}")
    else:
        pos_pool = [r for r in train_rows if r["label"] == 1 and r["source"].startswith(pref_src) and len(r["premise"]) <= 2200]
        neg_pool = [r for r in train_rows if r["label"] == 0 and r["source"].startswith(pref_src) and len(r["premise"]) <= 2200]
        for i in range(lc_total // 2):
            d = max(350, buckets[i % len(buckets)] + rng.randint(-150, 250))
            ex_p = rng.choice(pos_pool)
            ex_n = rng.choice(neg_pool)
            train_rows.append(_make_rec(_embed_in_rag_haystack(ex_p["premise"], d, rng), ex_p["hypothesis"], 1, "long_ctx_pos", ex_p["language"]))
            train_rows.append(_make_rec(_embed_in_rag_haystack(ex_n["premise"], d, rng), ex_n["hypothesis"], 0, "long_ctx_neg", ex_n["language"]))
        print(f"[data] Long-Context RAG Haystacks added (Control): {lc_total:,}")

    # Strict dedup against val & eval (exact hygiene!)
    val_clean, vseen = [], set()
    for r in val_rows:
        ph = _norm_md5(r["premise"] + " ||| " + r["hypothesis"])
        if ph in eval_pair_hashes or ph in vseen:
            continue
        vseen.add(ph)
        val_clean.append(r)
    rng.shuffle(val_clean)
    val_rows = val_clean[: _sc(3500)]

    val_pair_hashes = {_norm_md5(r["premise"] + " ||| " + r["hypothesis"]) for r in val_rows}
    blocked = eval_pair_hashes | val_pair_hashes
    cleaned, seen = [], set()
    for r in train_rows:
        ph = _norm_md5(r["premise"] + " ||| " + r["hypothesis"])
        if ph in blocked:
            continue
        if ph in seen and r["source"] != "psiloqa":
            continue
        seen.add(ph)
        cleaned.append(r)
    rng.shuffle(cleaned)
    train_rows = cleaned

    _write_jsonl(out_dir / "train.jsonl", train_rows)
    _write_jsonl(out_dir / "val.jsonl", val_rows)
    for sname, srows in test_suites.items():
        _write_jsonl(out_dir / f"test_{sname}.jsonl", srows)

    stats = {
        "variant": args.variant,
        "scale": args.scale,
        "train": _summarize(train_rows),
        "val": _summarize(val_rows),
        "tests": {k: len(v) for k, v in test_suites.items()},
    }
    (out_dir / "dataset_stats.json").write_text(json.dumps(stats, indent=2), encoding="utf-8")
    print("[data] Done:", json.dumps(stats, indent=2))


if __name__ == "__main__":
    main()