File size: 28,931 Bytes
98299a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Production Dataset Builder for Tamarillo/groundedness-guard (Token-Span MIL Architecture).

100% commercially permissive training sources (MIT / Apache-2.0 / CC-BY-4.0 / OANC; zero CC-BY-NC,
zero CC-BY-SA, zero gated datasets, zero leakage into OOD RAGTruth / SummEval / FRANK / FinQA):
  - Stage 1 (~112K Clean Semantic NLI):
      * MoritzLaurer/synthetic_zeroshot_mixtral_v0.1 (Apache-2.0, 46K)
      * alisawuffles/WANLI (CC-BY-4.0, 36K)
      * nyu-mll/multi_nli OANC permissive genres only (30K)
  - Stage 2 (Length-Debiased Groundedness + Exact-Span Localization + Conversational QA):
      * McGill-NLP/FaithDial (MIT, 10K conversational grounded vs hallucinated QA pairs)
      * lytang/C2D-and-D2C-MiniCheck (MIT, all c2d + d2c)
      * Salesforce/summedits (CC-BY-4.0, 1.5x with exact difflib spans)
      * s-nlp/PsiloQA (CC-BY-4.0, 14 languages up to 4,500/lang in multilingual mode; EN-only in en mode;
        filters 39 noisy train rows with [HAL] tag & empty labels)
      * Synthetic Minimal-Edit Counterfactuals (6K exact-span numeric/unit/calendar/entity mutations)
      * Length-Matched Multi-Passage Composed Pairs (14K rows = 7K pairs w/ exact bad-sentence spans)
      * Same-Haystack Paired Long-Context RAG Examples (8K rows spanning 350..11,500 chars)
      * Hard Counterfactual & Asymmetric Entailment Anchors
"""

from __future__ import annotations

import argparse
import json
import os
import random
import re
from collections import defaultdict
from pathlib import Path
from typing import Any

from data_builder_probe import (
    MNLI_PERMISSIVE_GENRES,
    _embed_in_rag_haystack,
    _extract_difflib_spans,
    _extract_ragtruth_context,
    _hash_bucket,
    _make_rec,
    _norm_md5,
    _summarize,
    _write_jsonl,
)
from data_builder_r2 import _compose_multipassage_pairs
from data_builder_r3 import _mutate_counterfactual_v2
from schema import COUNTERFACTUAL_ANCHORS, PSILOQA_LANGS


def _format_triples_structured(triples: list[list[str]], style: int) -> str:
    """Render DART triples as realistic JSON (matching RAGTruth data2txt / MCP tool outputs)
    or Markdown key-value table."""
    if style == 0:
        obj: dict[str, dict[str, Any]] = {}
        for tr in triples:
            if len(tr) != 3:
                continue
            s, p, o = [str(x).strip() for x in tr]
            if s == "[TABLECONTEXT]":
                s = "record"
            p_clean = p.strip("[]").lower()
            if s not in obj:
                obj[s] = {}
            if p_clean in obj[s]:
                cur = obj[s][p_clean]
                obj[s][p_clean] = (cur + [o]) if isinstance(cur, list) else [cur, o]
            else:
                obj[s][p_clean] = o
        return json.dumps(obj, ensure_ascii=False, indent=2)
    elif style == 1:
        rows = [
            {"entity": str(t[0]).strip(), "attribute": str(t[1]).strip(), "value": str(t[2]).strip()}
            for t in triples
            if len(t) == 3
        ]
        return json.dumps({"attributes": rows}, ensure_ascii=False)
    else:
        lines = ["| Entity | Field | Value |", "|---|---|---|"]
        for tr in triples:
            if len(tr) == 3:
                lines.append(f"| {str(tr[0]).strip()} | {str(tr[1]).strip()} | {str(tr[2]).strip()} |")
        return "\n".join(lines)


def _build_dart_data2txt_pairs(
    dart_rows: list[dict[str, Any]],
    target_pairs: int,
    rng: random.Random,
    eval_claim_hashes: set[str],
    eval_pair_hashes: set[str],
) -> list[dict[str, Any]]:
    vals_by_pred: dict[str, list[str]] = defaultdict(list)
    clean_rows: list[tuple[list[list[str]], str]] = []
    for row in dart_rows:
        tset = row.get("tripleset") or []
        tgt = re.sub(r"\s+", " ", str(row.get("target") or "")).strip()
        if len(tset) < 2 or len(tgt) < 25 or len(tgt) > 600:
            continue
        if _norm_md5(tgt) in eval_claim_hashes:
            continue
        clean_rows.append((tset, tgt))
        for tr in tset:
            if len(tr) == 3:
                p, o = str(tr[1]).strip(), str(tr[2]).strip()
                if 2 <= len(o) <= 60:
                    vals_by_pred[p].append(o)

    for p in list(vals_by_pred.keys()):
        vals_by_pred[p] = list(dict.fromkeys(vals_by_pred[p]))

    rng.shuffle(clean_rows)
    out: list[dict[str, Any]] = []
    pair_cnt = 0

    for tset, tgt in clean_rows:
        if pair_cnt >= target_pairs:
            break
        style = rng.choice([0, 0, 1, 2])
        prem = _format_triples_structured(tset, style)
        if len(prem) < 25 or _norm_md5(prem + " ||| " + tgt) in eval_pair_hashes:
            continue
        gid = _norm_md5(prem)

        neg_hyp = None
        hal_spans: list[list[int]] = []
        mode = rng.random()

        if mode < 0.65:
            cand_tris = [tr for tr in tset if len(tr) == 3 and 2 <= len(str(tr[2]).strip()) <= 50]
            rng.shuffle(cand_tris)
            for _s, pred, obj in cand_tris:
                obj_s = str(obj).strip()
                m = re.search(re.escape(obj_s), tgt)
                pool = vals_by_pred.get(str(pred).strip(), [])
                if m and len(pool) >= 3:
                    for _ in range(5):
                        alt = rng.choice(pool)
                        if alt.lower() != obj_s.lower() and alt.lower() not in prem.lower():
                            neg_hyp = tgt[: m.start()] + alt + tgt[m.end() :]
                            hal_spans = [[m.start(), m.start() + len(alt)]]
                            break
                if neg_hyp is not None:
                    break

        if neg_hyp is None and len(tset) >= 3:
            drop_idx = rng.randrange(len(tset))
            dropped = tset[drop_idx]
            if len(dropped) == 3:
                obj_s = str(dropped[2]).strip()
                m = re.search(re.escape(obj_s), tgt)
                if m and len(obj_s) >= 3:
                    sub_tset = [t for idx, t in enumerate(tset) if idx != drop_idx]
                    sub_prem = _format_triples_structured(sub_tset, style)
                    if obj_s.lower() not in sub_prem.lower():
                        out.append(_make_rec(prem, tgt, 1, "dart_data2txt_pos", "en", group_id=gid, has_span=True))
                        out.append(
                            _make_rec(
                                sub_prem,
                                tgt,
                                0,
                                "dart_data2txt_drop",
                                "en",
                                group_id=_norm_md5(sub_prem),
                                has_span=True,
                                hal_spans=[[m.start(), m.end()]],
                            )
                        )
                        pair_cnt += 1
                        continue

        if neg_hyp is None:
            mut = _mutate_counterfactual_v2(prem, tgt, rng)
            if mut is not None:
                neg_hyp, hal_spans = mut

        if neg_hyp is not None and _norm_md5(neg_hyp) not in eval_claim_hashes:
            out.append(_make_rec(prem, tgt, 1, "dart_data2txt_pos", "en", group_id=gid, has_span=True))
            out.append(_make_rec(prem, neg_hyp, 0, "dart_data2txt_swap", "en", group_id=gid, has_span=True, hal_spans=hal_spans))
            pair_cnt += 1

    return out


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--out-dir", type=str, required=True)
    parser.add_argument("--mode", choices=["multilingual", "en"], default="multilingual")
    parser.add_argument("--eval-only", action="store_true")
    parser.add_argument("--seed", type=int, default=42)
    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)

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

    rt_rows = []
    for sp_name in ("qa", "summarization", "data2txt"):
        for row in load_dataset("flowaicom/RAGTruth_test", split=sp_name):
            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
            rt_rows.append({"premise": prem, "hypothesis": resp, "label": 1 if int(sc) == 1 else 0, "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]

    se_rows = []
    for row in load_dataset("mteb/summeval", split="test"):
        txt = str(row.get("text") or "").strip()
        if len(txt) < 20:
            continue
        for s_t, c_v in zip(row.get("machine_summaries") or [], row.get("consistency") or []):
            s_clean = str(s_t or "").strip()
            if len(s_clean) < 10 or c_v is None:
                continue
            se_rows.append({"premise": txt, "hypothesis": s_clean, "label": 1 if float(c_v) >= 5.0 else 0, "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

    fr_rows = []
    for row in load_dataset("mtc/frank-test-set-with-faithfulness-annotation", split="test"):
        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
        fr_rows.append({"premise": art, "hypothesis": summ, "label": 1 if bool(fac) else 0, "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

    fin_rows = []
    for row in load_dataset("Cleanlab/FinQA-hallucination-detection", split="train"):
        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
        fin_rows.append({"premise": prem, "hypothesis": resp, "label": 1 if int(ic) == 1 else 0, "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

    by_lg: dict[str, list[dict[str, Any]]] = defaultdict(list)
    lc_pos_seeds, lc_neg_seeds = [], []
    for row in load_dataset("s-nlp/PsiloQA", split="test"):
        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

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

    if args.eval_only:
        stats = {"tests": {k: len(v) for k, v in test_suites.items()}}
        (out_dir / "eval_dataset_stats.json").write_text(json.dumps(stats, indent=2), encoding="utf-8")
        print("[data] Eval-only build complete:", json.dumps(stats, indent=2))
        return

    # ================= 2. STAGE-1 SEMANTIC NLI (~112K) + STAGE-2 GROUNDEDNESS =================
    stage1_rows: list[dict[str, Any]] = []
    stage2_rows: list[dict[str, Any]] = []
    val_rows: list[dict[str, Any]] = []
    allowed_langs = set(PSILOQA_LANGS) if args.mode == "multilingual" else {"en"}

    # A. Mixtral-NLI (46K)
    mix_all: list[dict[str, Any]] = []
    for cfg_name, cap in [
        ("mixtral_refinedweb_nli", 30000),
        ("mixtral_written_texts_for_tasks", 10000),
        ("mixtral_refinedweb_characteristics", 6000),
    ]:
        try:
            ds_m = load_dataset("MoritzLaurer/synthetic_zeroshot_mixtral_v0.1", cfg_name, split="train", streaming=True)
            pos_c = neg_c = 0
            half = cap // 2
            for row in ds_m:
                p = str(row.get("text") or "").strip()
                h = str(row.get("hypothesis") or "").strip()
                raw_l = row.get("labels")
                if len(p) < 15 or len(h) < 8 or raw_l not in (0, 1):
                    continue
                if _norm_md5(h) in eval_claim_hashes or _norm_md5(p + " ||| " + h) in eval_pair_hashes:
                    continue
                lbl = 1 if int(raw_l) == 0 else 0
                if lbl == 1 and pos_c >= half:
                    continue
                if lbl == 0 and neg_c >= half:
                    continue
                rec = _make_rec(p, h, lbl, f"mixtral_{cfg_name}", "en")
                if _hash_bucket(p) < 96:
                    mix_all.append(rec)
                    if lbl == 1:
                        pos_c += 1
                    else:
                        neg_c += 1
                elif len(val_rows) < 400:
                    val_rows.append(rec)
                if pos_c >= half and neg_c >= half:
                    break
        except Exception as e:
            print(f"[warn] Mixtral {cfg_name} skipped: {e}")
    rng.shuffle(mix_all)
    stage1_rows.extend(mix_all)
    stage2_rows.extend(mix_all[:14000])
    print(f"[data] Mixtral: {len(mix_all):,}")

    # B. WANLI (36K)
    ds_w = list(load_dataset("alisawuffles/WANLI", split="train"))
    random.Random(args.seed + 101).shuffle(ds_w)
    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) < 18000:
            w_pos.append(rec)
        elif lbl == 0 and len(w_neg) < 18000:
            w_neg.append(rec)
        if len(w_pos) >= 18000 and len(w_neg) >= 18000:
            break
    wanli_all = w_pos + w_neg
    rng.shuffle(wanli_all)
    stage1_rows.extend(wanli_all)
    stage2_rows.extend(wanli_all[:10000])
    print(f"[data] WANLI: {len(wanli_all):,}")

    # C. MultiNLI OANC (30K)
    m_pos, m_neg = [], []
    for row in load_dataset("nyu-mll/multi_nli", split="train", streaming=True):
        if len(m_pos) >= 15000 and len(m_neg) >= 15000:
            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) < 15000:
            m_pos.append(rec)
        elif lbl == 0 and len(m_neg) < 15000:
            m_neg.append(rec)
    mnli_all = m_pos + m_neg
    rng.shuffle(mnli_all)
    stage1_rows.extend(mnli_all)
    stage2_rows.extend(mnli_all[:8000])
    print(f"[data] MultiNLI OANC: {len(mnli_all):,}")

    # D. McGill-NLP/FaithDial Conversational Grounded QA (MIT)
    # (A/B tested GEM/dart in cca57190ad14 vs eecadc240e6a: synthetic DART swaps hurt OOD RAGTruth by -9.0 AUC; excluded!)
    try:
        fd_train, fd_val = [], []
        for sp_name, tgt_l in [("train", fd_train), ("validation", fd_val)]:
            ds_fd = list(load_dataset("McGill-NLP/FaithDial", "plain_text", split=sp_name))
            for row in ds_fd:
                know = str(row.get("knowledge") or "").strip()
                resp = str(row.get("response") or "").strip()
                orig = str(row.get("original_response") or "").strip()
                beg = [str(x).lower() for x in (row.get("BEGIN") or [])]
                if len(know) < 20 or len(resp) < 12:
                    continue
                gid = _norm_md5(know)
                if _norm_md5(resp) not in eval_claim_hashes:
                    tgt_l.append(_make_rec(know, resp, 1, "faithdial_pos", "en", group_id=gid, has_span=True))
                if "hallucination" in beg and len(orig) >= 12 and orig != resp and _norm_md5(orig) not in eval_claim_hashes:
                    tgt_l.append(_make_rec(know, orig, 0, "faithdial_neg", "en", group_id=gid, has_span=False))
        rng.shuffle(fd_train)
        stage2_rows.extend(fd_train[:10000])
        val_rows.extend(fd_val[:300])
        print(f"[data] FaithDial Conversational Grounded QA: {min(10000, len(fd_train)):,} train + {min(300, len(fd_val))} val")
    except Exception as e:
        print(f"[warn] FaithDial skipped: {e}")

    # F. MiniCheck (MIT, ALL c2d + d2c)
    mc_train: list[dict[str, Any]] = []
    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)
        for row in ds_mc:
            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) < 93:
                mc_train.append(rec)
            elif len(val_rows) < 1600:
                val_rows.append(rec)
    stage2_rows.extend(mc_train)
    print(f"[data] MiniCheck: {len(mc_train):,}")

    # G. SummEdits (CC-BY-4.0, exact difflib spans, 1.5x)
    se_train: list[dict[str, Any]] = []
    for row in load_dataset("Salesforce/summedits", split="train"):
        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 = _extract_difflib_spans(seed_s, summ) if (li == 0 and seed_s) else (False, [])
        rec = _make_rec(doc, summ, li, "summedits", "en", has_span=has_sp, hal_spans=sp_list)
        if _hash_bucket(doc) < 90:
            se_train.append(rec)
        else:
            val_rows.append(rec)
    stage2_rows.extend(se_train)
    stage2_rows.extend(rng.sample(se_train, k=len(se_train) // 2))
    print(f"[data] SummEdits: {len(se_train):,} unique (1.5x)")

    # H. s-nlp/PsiloQA (CC-BY-4.0, 14 langs in multilingual mode up to 4,500/lang; EN-only in en mode)
    pq_train: list[dict[str, Any]] = []
    pq_dropped = 0
    per_l_train_cap = 4500 if args.mode == "multilingual" else 6000
    per_l_val_cap = 180 if args.mode == "multilingual" else 400
    for sp_name, tgt_list, per_l_cap in [("train", pq_train, per_l_train_cap), ("validation", val_rows, per_l_val_cap)]:
        by_l_cls: dict[str, dict[int, list[dict[str, Any]]]] = defaultdict(lambda: {0: [], 1: []})
        for row in load_dataset("s-nlp/PsiloQA", split=sp_name):
            lg = str(row.get("lang") or "en").strip().lower()
            if lg not in allowed_langs:
                continue
            ctx = str(row.get("wiki_passage") or "").strip()
            ans = str(row.get("llm_answer") or "").strip()
            spans = row.get("labels")
            ann = 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
            if sp_name == "train" and len(spans) == 0 and "[HAL]" in ann:
                pq_dropped += 1
                continue
            lbl = 1 if len(spans) == 0 else 0
            clean_spans = []
            if 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=(lbl == 1 or bool(clean_spans)), hal_spans=clean_spans)
            by_l_cls[lg][lbl].append(rec)

        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) * 2.5)), per_l_cap - len(pos_items))
            if not pos_items:
                continue
            if sp_name == "train" and len(pos_items) < n_neg:
                extra = (pos_items * 3)[: n_neg - len(pos_items)]
                chosen = pos_items + extra + cls_map[0][:n_neg]
            else:
                chosen = pos_items + cls_map[0][:n_neg]
            tgt_list.extend(chosen)
    stage2_rows.extend(pq_train)
    print(f"[data] PsiloQA ({args.mode}): {len(pq_train):,} (dropped noisy={pq_dropped})")

    # I. Enhanced Minimal-Edit CFs (6,000)
    cf_pool = [
        r
        for r in stage2_rows
        if r["label"] == 1
        and r["source"] in ("minicheck_c2d", "minicheck_d2c", "summedits", "psiloqa", "faithdial_pos", "mixtral_mixtral_refinedweb_nli")
    ]
    rng.shuffle(cf_pool)
    cf_rows = []
    for r in cf_pool:
        if len(cf_rows) >= 6000:
            break
        res = _mutate_counterfactual_v2(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
        cf_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)
        )
    stage2_rows.extend(cf_rows)
    print(f"[data] Minimal-Edit CFs: {len(cf_rows):,}")

    # J. Length-Matched Multi-Passage Composed Pairs (14,000)
    neg_by_gid: dict[str, list[dict[str, Any]]] = defaultdict(list)
    pos_for_comp: list[dict[str, Any]] = []
    for r in stage2_rows:
        if r["source"] in ("minicheck_c2d", "minicheck_d2c", "psiloqa", "faithdial_pos", "faithdial_neg", "mixtral_mixtral_refinedweb_nli", "wanli"):
            if r["label"] == 1:
                pos_for_comp.append(r)
            else:
                neg_by_gid[r["group_id"]].append(r)
    mp_train = _compose_multipassage_pairs(
        pos_for_comp, neg_by_gid, target_pairs=7000, rng=rng, eval_claim_hashes=eval_claim_hashes, eval_pair_hashes=eval_pair_hashes
    )
    stage2_rows.extend(mp_train)
    print(f"[data] Length-Matched Multi-Passage Composed: {len(mp_train):,}")

    # K. Counterfactual anchors + Same-Haystack Paired Long-Context (8,000)
    for _ in range(8):
        for prem, hyp, lbl in COUNTERFACTUAL_ANCHORS:
            stage2_rows.append(_make_rec(prem, hyp, lbl, "counterfactual_anchor", "en"))

    by_g_cls: dict[str, dict[int, list[dict[str, Any]]]] = defaultdict(lambda: {0: [], 1: []})
    for r in stage2_rows:
        if len(r["premise"]) <= 2200 and not r["source"].startswith("long_ctx"):
            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)
    buckets = [600, 1400, 3000, 6200, 11200]
    lc_train = []
    for i in range(4000):
        if not paired_gids:
            break
        d = max(350, buckets[i % len(buckets)] + rng.randint(-150, 250))
        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)
        lc_train.append(_make_rec(haystack, ex_p["hypothesis"], 1, "long_ctx_pos", ex_p["language"], group_id=hgid, has_span=True))
        lc_train.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"]
            )
        )
    stage2_rows.extend(lc_train)
    print(f"[data] Same-Haystack LC Pairs: {len(lc_train):,}")

    # ================= 3. STRICT DEDUP 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[:4000]
    val_pair_hashes = {_norm_md5(r["premise"] + " ||| " + r["hypothesis"]) for r in val_rows}
    blocked = eval_pair_hashes | val_pair_hashes

    def _clean(rows: list[dict[str, Any]], allow_dup: set[str]) -> list[dict[str, Any]]:
        out, seen = [], set()
        for r in rows:
            ph = _norm_md5(r["premise"] + " ||| " + r["hypothesis"])
            if ph in blocked:
                continue
            if ph in seen and r["source"] not in allow_dup:
                continue
            seen.add(ph)
            out.append(r)
        rng.shuffle(out)
        return out

    stage1_rows = _clean(stage1_rows, set())
    stage2_rows = _clean(stage2_rows, {"psiloqa", "summedits"})

    _write_jsonl(out_dir / "stage1_nli.jsonl", stage1_rows)
    _write_jsonl(out_dir / "stage2_grounded.jsonl", stage2_rows)
    _write_jsonl(out_dir / "val.jsonl", val_rows)

    stats = {
        "mode": args.mode,
        "stage1": _summarize(stage1_rows),
        "stage2": _summarize(stage2_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] Production Build Complete:", json.dumps(stats, indent=2))


if __name__ == "__main__":
    main()