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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Command-line entry points for generating and auditing BGD-SFT artifacts."""

from __future__ import annotations

import argparse
import hashlib
import json
import sys
from collections import Counter
from concurrent.futures import ProcessPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable

from .audit import StatsAccumulator, build_manifest, build_report
from .generation import GenerationPlan, generate_record
from .io import (
    ShardResult,
    iter_jsonl_gz,
    sha256_file,
    write_json_atomic,
    write_jsonl_gz_atomic,
)
from .serializers import build_messages
from .validation import validate_record


DEFAULT_CONFIG = Path(__file__).resolve().parents[2] / "configs" / "selected_sft_1m.json"


@dataclass
class WorkerResult:
    shard: ShardResult
    stats: StatsAccumulator
    group_splits: dict[str, str]
    invalid_examples: list[dict[str, Any]]


def _load_config(path: str | Path) -> dict[str, Any]:
    config_path = Path(path)
    config = json.loads(config_path.read_text(encoding="utf-8"))
    if not isinstance(config, dict):
        raise ValueError("config must be a JSON object")
    GenerationPlan(config)
    return config


def _config_digest(config: dict[str, Any]) -> str:
    payload = json.dumps(config, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def _record_stream(
    config: dict[str, Any],
    start: int,
    end: int,
    stats: StatsAccumulator,
    group_splits: dict[str, str],
) -> Iterable[dict[str, Any]]:
    plan = GenerationPlan(config)
    for index in range(start, end):
        record = generate_record(config, plan, index)
        errors = validate_record(record)
        if errors:
            raise ValueError(
                f"generated invalid record {record.get('record_id')}: " + "; ".join(errors)
            )
        source_group = record["source_group"]
        split = record["split"]
        previous = group_splits.setdefault(source_group, split)
        if previous != split:
            raise ValueError(f"source group split leakage: {source_group}: {previous} vs {split}")
        stats.ingest(record)
        yield record


def _generate_shard(
    config: dict[str, Any],
    output_path: str,
    start: int,
    end: int,
    compresslevel: int,
) -> WorkerResult:
    stats = StatsAccumulator()
    group_splits: dict[str, str] = {}
    shard = write_jsonl_gz_atomic(
        output_path,
        _record_stream(config, start, end, stats, group_splits),
        compresslevel=compresslevel,
    )
    if shard.records != end - start:
        raise RuntimeError(f"short shard {output_path}: {shard.records} != {end - start}")
    return WorkerResult(shard=shard, stats=stats, group_splits=group_splits, invalid_examples=[])


def _audit_shard(expected: dict[str, Any]) -> WorkerResult:
    path = Path(expected["path"])
    actual_hash = sha256_file(path)
    invalid_examples: list[dict[str, Any]] = []
    stats = StatsAccumulator()
    group_splits: dict[str, str] = {}
    records = 0
    for record in iter_jsonl_gz(path):
        records += 1
        errors = validate_record(record)
        if errors and len(invalid_examples) < 20:
            invalid_examples.append({"record_id": record.get("record_id"), "errors": errors})
        stats.ingest(record)
        source_group = record.get("source_group")
        split = record.get("split")
        if isinstance(source_group, str) and isinstance(split, str):
            previous = group_splits.setdefault(source_group, split)
            if previous != split and len(invalid_examples) < 20:
                invalid_examples.append(
                    {
                        "record_id": record.get("record_id"),
                        "errors": [f"source group split leakage: {source_group}: {previous} vs {split}"],
                    }
                )
    if actual_hash != expected["sha256"]:
        invalid_examples.append(
            {"record_id": None, "errors": [f"checksum mismatch for {path}"]}
        )
    if records != int(expected["records"]):
        invalid_examples.append(
            {
                "record_id": None,
                "errors": [f"record count mismatch for {path}: {records} != {expected['records']}"],
            }
        )
    shard = ShardResult(
        path=path,
        records=records,
        sha256=actual_hash,
        compressed_bytes=path.stat().st_size,
        uncompressed_bytes=int(expected.get("uncompressed_bytes", 0)),
    )
    return WorkerResult(
        shard=shard,
        stats=stats,
        group_splits=group_splits,
        invalid_examples=invalid_examples,
    )


def _merge_worker_results(results: list[WorkerResult]) -> tuple[StatsAccumulator, int, list[dict[str, Any]]]:
    stats = StatsAccumulator()
    all_group_splits: dict[str, str] = {}
    split_conflicts = 0
    invalid_examples: list[dict[str, Any]] = []
    for result in results:
        stats.merge(result.stats)
        for source_group, split in result.group_splits.items():
            previous = all_group_splits.setdefault(source_group, split)
            if previous != split:
                split_conflicts += 1
                if len(invalid_examples) < 20:
                    invalid_examples.append(
                        {
                            "record_id": None,
                            "errors": [
                                f"cross-shard source group leakage: {source_group}: {previous} vs {split}"
                            ],
                        }
                    )
        for example in result.invalid_examples:
            if len(invalid_examples) < 20:
                invalid_examples.append(example)
    return stats, split_conflicts, invalid_examples


def _expected_counts(percent: dict[str, int], total: int) -> dict[str, int]:
    return {key: total * value // 100 for key, value in percent.items()}


def _promotion_gates(
    config: dict[str, Any],
    stats: StatsAccumulator,
    *,
    requested_records: int,
    split_conflicts: int,
    invalid_examples: list[dict[str, Any]],
) -> dict[str, Any]:
    observed = stats.to_dict()
    full_run = requested_records == int(config["total_records"])
    gates: dict[str, bool | None] = {
        "exact_requested_record_count": observed["total_records"] == requested_records,
        "all_records_primary_zh_tw": observed["primary_zh_tw_records"] == requested_records,
        "no_unannotated_simplified_only_hits": observed[
            "unannotated_simplified_only_hit_records"
        ]
        == 0,
        "record_ids_unique": observed["duplicate_record_id_occurrences"] == 0,
        "evidence_references_resolve": observed["evidence_reference_missing"] == 0,
        "source_groups_split_locked": split_conflicts == 0,
        "all_records_semantically_valid": not invalid_examples,
        "exact_split_distribution": None,
        "exact_primitive_distribution": None,
        "exact_mixture_distribution": None,
        "exact_serializer_distribution": None,
        "exact_long_context_distribution": None,
    }
    if full_run:
        gates["exact_split_distribution"] = observed["split"] == _expected_counts(
            config["split_percent"], requested_records
        )
        gates["exact_primitive_distribution"] = observed["primitive"] == _expected_counts(
            config["primitive_percent"], requested_records
        )
        gates["exact_mixture_distribution"] = observed["mixture_category"] == _expected_counts(
            config["mixture_percent"], requested_records
        )
        gates["exact_serializer_distribution"] = observed["serializer"] == _expected_counts(
            config["serializer_percent"], requested_records
        )
        long_total = int(config["long_context_records"])
        long_expected = _expected_counts(config["long_context_bucket_percent"], long_total)
        overall_expected = dict(long_expected)
        overall_expected["0.5K-4K"] += requested_records - long_total
        gates["exact_long_context_distribution"] = observed["context_bucket"] == overall_expected
    evaluated = [value for value in gates.values() if value is not None]
    return {
        "full_run": full_run,
        "gates": gates,
        "all_evaluated_gates_passed": all(evaluated),
        "invalid_examples": invalid_examples,
        "source_group_split_conflicts": split_conflicts,
    }


def _publish_reports(
    output_root: Path,
    config: dict[str, Any],
    results: list[WorkerResult],
    stats: StatsAccumulator,
    gates: dict[str, Any],
    *,
    requested_records: int,
    report_prefix: str,
) -> tuple[Path, Path]:
    shards = sorted((result.shard for result in results), key=lambda shard: str(shard.path))
    metadata = {
        "dataset_name": config["dataset_name"],
        "schema_version": config["schema_version"],
        "generator_version": config["generator_version"],
        "validator_version": config["validator_version"],
        "config_sha256": _config_digest(config),
        "requested_records": requested_records,
        "synthetic_only": True,
        "human_reviewed_records": 0,
        "teacher_generated_records": 0,
    }
    manifest = build_manifest(shards, stats=stats, metadata=metadata)
    manifest_path = output_root / f"{report_prefix}manifest.json"
    write_json_atomic(manifest_path, manifest)
    report = build_report(stats, metadata=metadata)
    report["promotion_gates"] = gates
    report_path = output_root / "reports" / f"{report_prefix}audit.json"
    write_json_atomic(report_path, report)
    return manifest_path, report_path


def _run_parallel_generate(
    config: dict[str, Any],
    output_root: Path,
    requested_records: int,
    workers: int,
) -> list[WorkerResult]:
    shard_size = int(config["shard_size"])
    tasks = []
    for shard_index, start in enumerate(range(0, requested_records, shard_size)):
        end = min(requested_records, start + shard_size)
        path = output_root / "canonical" / f"part-{shard_index:05d}.jsonl.gz"
        tasks.append((config, str(path), start, end, int(config["gzip_compresslevel"])))
    results: list[WorkerResult] = []
    if workers == 1:
        for shard_index, task in enumerate(tasks, 1):
            result = _generate_shard(*task)
            results.append(result)
            print(f"generated {shard_index}/{len(tasks)} {result.shard.path.name}", flush=True)
        return results
    with ProcessPoolExecutor(max_workers=workers) as executor:
        futures = {executor.submit(_generate_shard, *task): task[1] for task in tasks}
        completed = 0
        for future in as_completed(futures):
            path = futures.pop(future)
            result = future.result()
            results.append(result)
            completed += 1
            print(f"generated {completed}/{len(tasks)} {Path(path).name}", flush=True)
    return results


def command_generate(args: argparse.Namespace) -> int:
    config = _load_config(args.config)
    requested_records = int(args.limit or config["total_records"])
    if not 1 <= requested_records <= int(config["total_records"]):
        raise ValueError("--limit must be between 1 and config.total_records")
    output_root = Path(args.output).resolve()
    if (output_root / "_SUCCESS.json").exists():
        raise FileExistsError(f"completed dataset already exists: {output_root}")
    canonical = output_root / "canonical"
    if canonical.exists() and any(canonical.iterdir()):
        raise FileExistsError(
            f"output canonical directory is not empty: {canonical}; choose a new output path"
        )
    output_root.mkdir(parents=True, exist_ok=True)
    write_json_atomic(output_root / "config.snapshot.json", config)
    workers = max(1, min(int(args.workers), (requested_records + config["shard_size"] - 1) // config["shard_size"]))
    results = _run_parallel_generate(config, output_root, requested_records, workers)
    stats, split_conflicts, invalid_examples = _merge_worker_results(results)
    gates = _promotion_gates(
        config,
        stats,
        requested_records=requested_records,
        split_conflicts=split_conflicts,
        invalid_examples=invalid_examples,
    )
    manifest_path, report_path = _publish_reports(
        output_root,
        config,
        results,
        stats,
        gates,
        requested_records=requested_records,
        report_prefix="",
    )
    success = {
        "dataset_name": config["dataset_name"],
        "records": requested_records,
        "shards": len(results),
        "manifest": str(manifest_path),
        "manifest_sha256": sha256_file(manifest_path),
        "audit": str(report_path),
        "audit_sha256": sha256_file(report_path),
        "all_evaluated_gates_passed": gates["all_evaluated_gates_passed"],
    }
    if not gates["all_evaluated_gates_passed"]:
        write_json_atomic(output_root / "_FAILED_GATES.json", success | {"gates": gates})
        raise RuntimeError(f"generation gates failed; inspect {report_path}")
    write_json_atomic(output_root / "_SUCCESS.json", success)
    print(json.dumps(success, ensure_ascii=False, indent=2, sort_keys=True))
    return 0


def _run_parallel_audit(manifest: dict[str, Any], workers: int) -> list[WorkerResult]:
    shards = manifest.get("shards")
    if not isinstance(shards, list) or not shards:
        raise ValueError("manifest has no shards")
    results: list[WorkerResult] = []
    if workers == 1:
        for index, shard in enumerate(shards, 1):
            result = _audit_shard(shard)
            results.append(result)
            print(f"audited {index}/{len(shards)} {Path(shard['path']).name}", flush=True)
        return results
    with ProcessPoolExecutor(max_workers=workers) as executor:
        futures = {executor.submit(_audit_shard, shard): shard for shard in shards}
        completed = 0
        for future in as_completed(futures):
            shard = futures.pop(future)
            results.append(future.result())
            completed += 1
            print(f"audited {completed}/{len(shards)} {Path(shard['path']).name}", flush=True)
    return results


def command_audit(args: argparse.Namespace) -> int:
    output_root = Path(args.output).resolve()
    config = _load_config(args.config or output_root / "config.snapshot.json")
    manifest_path = Path(args.manifest or output_root / "manifest.json")
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    requested_records = int(manifest["metadata"]["requested_records"])
    workers = max(1, min(int(args.workers), len(manifest["shards"])))
    results = _run_parallel_audit(manifest, workers)
    stats, split_conflicts, invalid_examples = _merge_worker_results(results)
    gates = _promotion_gates(
        config,
        stats,
        requested_records=requested_records,
        split_conflicts=split_conflicts,
        invalid_examples=invalid_examples,
    )
    _, report_path = _publish_reports(
        output_root,
        config,
        results,
        stats,
        gates,
        requested_records=requested_records,
        report_prefix="postwrite-",
    )
    verified = {
        "dataset_name": config["dataset_name"],
        "records": stats.total_records,
        "shards": len(results),
        "source_manifest": str(manifest_path),
        "source_manifest_sha256": sha256_file(manifest_path),
        "audit": str(report_path),
        "audit_sha256": sha256_file(report_path),
        "all_evaluated_gates_passed": gates["all_evaluated_gates_passed"],
    }
    if not gates["all_evaluated_gates_passed"]:
        write_json_atomic(output_root / "_POSTWRITE_FAILED.json", verified | {"gates": gates})
        raise RuntimeError(f"post-write audit failed; inspect {report_path}")
    write_json_atomic(output_root / "_VERIFIED.json", verified)
    print(json.dumps(verified, ensure_ascii=False, indent=2, sort_keys=True))
    return 0


def command_build(args: argparse.Namespace) -> int:
    """Generate and then independently re-read every published shard."""

    generate_args = argparse.Namespace(
        config=args.config,
        output=args.output,
        limit=args.limit,
        workers=args.workers,
    )
    generated = command_generate(generate_args)
    if generated:
        return generated
    audit_args = argparse.Namespace(
        output=args.output,
        config=None,
        manifest=None,
        workers=args.workers,
    )
    return command_audit(audit_args)


def command_show_plan(args: argparse.Namespace) -> int:
    config = _load_config(args.config)
    plan = GenerationPlan(config)
    summary = {
        "dataset_name": config["dataset_name"],
        "total_records": config["total_records"],
        "primitive_per_100": dict(sorted(Counter(plan.primitive_cycle).items())),
        "mixture_per_100": dict(sorted(Counter(plan.mixture_cycle).items())),
        "serializer_per_100": dict(sorted(Counter(plan.serializer_cycle).items())),
        "long_slots": [
            {
                "offset": offset,
                "primitive": plan.primitive_cycle[offset],
                "mixture": plan.mixture_cycle[offset],
            }
            for offset in plan.long_slots
        ],
    }
    print(json.dumps(summary, ensure_ascii=False, indent=2, sort_keys=True))
    return 0


def command_render_sample(args: argparse.Namespace) -> int:
    config = _load_config(args.config)
    plan = GenerationPlan(config)
    record = generate_record(config, plan, int(args.index))
    print(
        json.dumps(
            {"record": record, "messages": build_messages(record)},
            ensure_ascii=False,
            indent=2,
            sort_keys=True,
        )
    )
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Barbet BGD-SFT deterministic dataset builder")
    subparsers = parser.add_subparsers(dest="command", required=True)

    generate = subparsers.add_parser("generate", help="generate validated canonical shards")
    generate.add_argument("--config", default=str(DEFAULT_CONFIG))
    generate.add_argument("--output", required=True)
    generate.add_argument("--limit", type=int)
    generate.add_argument("--workers", type=int, default=1)
    generate.set_defaults(func=command_generate)

    audit = subparsers.add_parser("audit", help="re-read, hash and semantically validate shards")
    audit.add_argument("--output", required=True)
    audit.add_argument("--config")
    audit.add_argument("--manifest")
    audit.add_argument("--workers", type=int, default=1)
    audit.set_defaults(func=command_audit)

    build = subparsers.add_parser(
        "build", help="generate the dataset and independently post-write audit every shard"
    )
    build.add_argument("--config", default=str(DEFAULT_CONFIG))
    build.add_argument("--output", required=True)
    build.add_argument("--limit", type=int)
    build.add_argument("--workers", type=int, default=1)
    build.set_defaults(func=command_build)

    show_plan = subparsers.add_parser("show-plan", help="print exact per-100 mixture")
    show_plan.add_argument("--config", default=str(DEFAULT_CONFIG))
    show_plan.set_defaults(func=command_show_plan)

    render = subparsers.add_parser("render-sample", help="render one canonical record as SFT messages")
    render.add_argument("--config", default=str(DEFAULT_CONFIG))
    render.add_argument("--index", type=int, default=0)
    render.set_defaults(func=command_render_sample)
    return parser


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    try:
        return int(args.func(args))
    except Exception as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1


if __name__ == "__main__":
    raise SystemExit(main())