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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
from __future__ import annotations

import argparse
import json
import re
import sys
import tempfile
import zipfile
from collections import Counter, defaultdict
from pathlib import Path, PurePosixPath
from typing import Any

import duckdb
import pyarrow.parquet as pq
import yaml

from common import find_secret_patterns, sha256_file


EXPECTED_CONFIGS = ("papers", "archive_only", "chunks", "archives")
EXPECTED_SCHEMAS = {
    "papers": {
        "paper_id",
        "doi",
        "title",
        "authors",
        "date_published",
        "abstract",
        "keywords",
        "language",
        "genre",
        "canonical_url",
        "works_url",
        "tex_source",
        "archive_path",
        "archive_sha256",
        "tex_entry",
        "tex_sha256",
        "source_archive_paths",
        "source_archive_sha256s",
        "source_tex_entries",
        "source_tex_sha256s",
        "mapping_status",
        "content_status",
        "quality_flags",
    },
    "archive_only": {
        "record_id",
        "title",
        "authors",
        "date_raw",
        "language",
        "tex_source",
        "archive_path",
        "archive_sha256",
        "tex_entry",
        "tex_sha256",
        "mapping_status",
        "candidate_dois",
        "content_status",
        "duplicate_of_archive",
        "quality_flags",
    },
    "chunks": {
        "chunk_id",
        "paper_id",
        "doi",
        "title",
        "partition",
        "source_id",
        "source_archive_path",
        "tex_entry",
        "section_path",
        "section_title",
        "chunk_index",
        "char_start",
        "char_end",
        "chunk_tex",
        "chunk_text",
        "char_count",
        "quality_flags",
    },
    "archives": {
        "archive_id",
        "archive_path",
        "archive_filename",
        "archive_size",
        "archive_sha256",
        "mapped_dois",
        "candidate_dois",
        "mapping_status",
        "mapping_method",
        "mapping_score",
        "content_status",
        "primary_tex_entry",
        "primary_tex_sha256",
        "duplicate_of_archive",
        "entries",
        "quality_flags",
    },
}


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Validate a built paper TeX corpus.")
    parser.add_argument("--dataset", type=Path, required=True)
    parser.add_argument(
        "--skip-datasets",
        action="store_true",
        help="Skip the optional local load_dataset checks.",
    )
    parser.add_argument(
        "--compare",
        type=Path,
        help="Compare generated artifact hashes with another build directory.",
    )
    return parser.parse_args()


class Validation:
    def __init__(self) -> None:
        self.errors: list[str] = []
        self.warnings: list[str] = []
        self.checks: Counter[str] = Counter()

    def require(self, condition: bool, message: str) -> None:
        self.checks["assertions"] += 1
        if not condition:
            self.errors.append(message)

    def warn(self, condition: bool, message: str) -> None:
        if not condition:
            self.warnings.append(message)


def parquet_path(root: Path, config: str) -> Path:
    return root / "data" / config / "train-00000-of-00001.parquet"


def load_rows(root: Path, config: str) -> list[dict[str, Any]]:
    return pq.read_table(parquet_path(root, config)).to_pylist()


def parse_card_metadata(readme: str) -> dict[str, Any]:
    if not readme.startswith("---\n"):
        raise ValueError("README does not start with YAML front matter.")
    _, yaml_text, _ = readme.split("---", 2)
    return yaml.safe_load(yaml_text)


def verify_checksums(root: Path, validation: Validation) -> None:
    checksum_file = root / "checksums.sha256"
    validation.require(checksum_file.is_file(), "checksums.sha256 is missing.")
    if not checksum_file.is_file():
        return
    listed: set[str] = set()
    for line in checksum_file.read_text(encoding="utf-8").splitlines():
        if not line.strip():
            continue
        match = re.match(r"^([0-9a-f]{64})  (.+)$", line)
        validation.require(bool(match), f"Malformed checksum line: {line}")
        if not match:
            continue
        expected, relative = match.groups()
        listed.add(relative)
        path = root / Path(relative)
        validation.require(path.is_file(), f"Checksummed file is missing: {relative}")
        if path.is_file():
            validation.require(
                sha256_file(path) == expected,
                f"Checksum mismatch: {relative}",
            )
    expected_files: set[str] = set()
    excluded_parts = {".git", ".venv", "__pycache__", ".pytest_cache"}
    excluded_names = {
        "checksums.sha256",
        "publish-report.json",
        ".paper-tex-corpus-build",
    }
    for path in root.rglob("*"):
        if not path.is_file():
            continue
        relative = path.relative_to(root)
        if any(part in excluded_parts for part in relative.parts):
            continue
        if relative.name in excluded_names:
            continue
        expected_files.add(relative.as_posix())
    validation.require(
        listed == expected_files,
        "checksums.sha256 file set does not match the publishable artifact set.",
    )


def verify_card(root: Path, validation: Validation) -> dict[str, Any]:
    readme_path = root / "README.md"
    validation.require(readme_path.is_file(), "README.md is missing.")
    if not readme_path.is_file():
        return {}
    readme = readme_path.read_text(encoding="utf-8")
    try:
        metadata = parse_card_metadata(readme)
    except Exception as error:
        validation.errors.append(f"README YAML parsing failed: {error}")
        return {}
    validation.require(metadata.get("license") == "cc-by-4.0", "Card license mismatch.")
    configs = metadata.get("configs") or []
    config_names = [config.get("config_name") for config in configs]
    validation.require(
        config_names == list(EXPECTED_CONFIGS),
        f"Unexpected README config order/names: {config_names}",
    )
    defaults = [config for config in configs if config.get("default")]
    validation.require(
        len(defaults) == 1 and defaults[0].get("config_name") == "papers",
        "papers must be the only default config.",
    )
    validation.require(
        "not an evaluation benchmark" in readme,
        "Dataset limitations must state that this is not an evaluation benchmark.",
    )
    validation.require(
        "CC BY 4.0" in readme and "CITATION.cff" in readme,
        "README license/citation documentation is incomplete.",
    )
    return metadata


def verify_parquet(root: Path, report: dict[str, Any], validation: Validation) -> dict[str, list[dict[str, Any]]]:
    rows: dict[str, list[dict[str, Any]]] = {}
    for config in EXPECTED_CONFIGS:
        path = parquet_path(root, config)
        validation.require(path.is_file(), f"Missing Parquet for config {config}.")
        if not path.is_file():
            rows[config] = []
            continue
        parquet = pq.ParquetFile(path)
        actual_columns = set(parquet.schema_arrow.names)
        validation.require(
            actual_columns == EXPECTED_SCHEMAS[config],
            f"Schema mismatch for {config}: {sorted(actual_columns)}",
        )
        expected_count = report["counts"][config]
        validation.require(
            parquet.metadata.num_rows == expected_count,
            f"{config} row count differs from build-report.json.",
        )
        validation.require(
            parquet.metadata.num_row_groups > 0,
            f"{config} has no Parquet row groups.",
        )
        rows[config] = parquet.read().to_pylist()
    return rows


def verify_relations(
    root: Path,
    rows: dict[str, list[dict[str, Any]]],
    validation: Validation,
) -> None:
    papers = rows["papers"]
    archive_only = rows["archive_only"]
    chunks = rows["chunks"]
    archives = rows["archives"]

    paper_dois = {row["doi"] for row in papers}
    validation.require(len(papers) == 227, "papers must contain 227 scholarly records.")
    validation.require(
        len(paper_dois) == 227,
        "papers DOI values must be unique and non-missing.",
    )
    validation.require(
        all(doi.startswith("10.") for doi in paper_dois),
        "Every papers row must contain a DOI.",
    )
    validation.require(
        len(archives) == 250,
        "archives must contain exactly 250 rows.",
    )
    archive_paths = {row["archive_path"] for row in archives}
    validation.require(
        len(archive_paths) == 250,
        "Archive paths must be unique.",
    )
    archive_by_path = {row["archive_path"]: row for row in archives}

    for row in archives:
        path = root / Path(row["archive_path"])
        validation.require(path.is_file(), f"Raw archive is missing: {row['archive_path']}")
        if path.is_file():
            validation.require(
                path.stat().st_size == row["archive_size"],
                f"Raw archive size mismatch: {row['archive_path']}",
            )
            validation.require(
                sha256_file(path) == row["archive_sha256"],
                f"Raw archive hash mismatch: {row['archive_path']}",
            )
        validation.require(
            set(row["mapped_dois"]).issubset(paper_dois),
            f"Archive maps outside the papers DOI set: {row['archive_path']}",
        )

    expected_archive_only = {
        row["archive_path"] for row in archives if not row["mapped_dois"]
    }
    actual_archive_only = {row["archive_path"] for row in archive_only}
    validation.require(
        expected_archive_only == actual_archive_only,
        "archive_only rows do not exactly cover unmapped archives.",
    )

    for row in papers:
        validation.require(
            row["paper_id"] == row["doi"],
            f"paper_id must equal DOI: {row['paper_id']}",
        )
        validation.require(
            len(row["source_archive_paths"])
            == len(row["source_archive_sha256s"])
            == len(row["source_tex_entries"])
            == len(row["source_tex_sha256s"]),
            f"Source arrays differ in length for {row['doi']}.",
        )
        for archive_path in row["source_archive_paths"]:
            validation.require(
                archive_path in archive_by_path,
                f"Paper references unknown archive: {archive_path}",
            )
        if row["content_status"] == "valid":
            validation.require(
                bool(row["tex_source"] and row["tex_sha256"]),
                f"Valid paper has no TeX source: {row['doi']}",
            )
        if row["content_status"] == "metadata_only":
            validation.require(
                not row["tex_source"] and not row["archive_path"],
                f"metadata_only paper unexpectedly has a source: {row['doi']}",
            )

    chunk_ids = [row["chunk_id"] for row in chunks]
    validation.require(
        len(chunk_ids) == len(set(chunk_ids)),
        "chunk_id values must be unique.",
    )
    chunk_sources = defaultdict(list)
    for row in chunks:
        chunk_sources[row["source_id"]].append(row)
        validation.require(
            row["source_archive_path"] in archive_by_path,
            f"Chunk references unknown archive: {row['chunk_id']}",
        )
        validation.require(
            row["char_end"] > row["char_start"],
            f"Chunk has invalid character span: {row['chunk_id']}",
        )
        validation.require(
            row["char_count"] == len(row["chunk_tex"]),
            f"Chunk char_count mismatch: {row['chunk_id']}",
        )
        validation.require(
            row["partition"] in {"papers", "archive_only"},
            f"Chunk partition is invalid: {row['chunk_id']}",
        )
        if row["doi"]:
            validation.require(
                row["doi"] in paper_dois,
                f"Chunk DOI is absent from papers: {row['chunk_id']}",
            )
    for source_id, source_rows in chunk_sources.items():
        indexes = [row["chunk_index"] for row in source_rows]
        validation.require(
            indexes == list(range(len(indexes))),
            f"Chunk indexes are not contiguous for {source_id}.",
        )


def verify_zip_security(root: Path, archive_rows: list[dict[str, Any]], validation: Validation) -> None:
    for row in archive_rows:
        path = root / Path(row["archive_path"])
        if not path.is_file():
            continue
        try:
            with zipfile.ZipFile(path) as archive:
                validation.require(
                    archive.testzip() is None,
                    f"ZIP CRC validation failed: {row['archive_path']}",
                )
                for info in archive.infolist():
                    member = PurePosixPath(info.filename.replace("\\", "/"))
                    validation.require(
                        not member.is_absolute()
                        and ".." not in member.parts
                        and not re.match(r"^[A-Za-z]:", info.filename),
                        f"Unsafe ZIP path: {row['archive_path']}::{info.filename}",
                    )
                    if info.is_dir() or not info.filename.lower().endswith(".tex"):
                        continue
                    text = archive.read(info).decode("utf-8", errors="replace")
                    validation.require(
                        "\ufffd" not in text,
                        f"UTF-8 replacement character in {row['archive_path']}::{info.filename}",
                    )
                    validation.require(
                        not find_secret_patterns(text),
                        f"Secret-like pattern in {row['archive_path']}::{info.filename}",
                    )
        except zipfile.BadZipFile as error:
            validation.errors.append(f"Broken ZIP {row['archive_path']}: {error}")


def verify_duckdb(root: Path, report: dict[str, Any], validation: Validation) -> None:
    connection = duckdb.connect(":memory:")
    try:
        for config in EXPECTED_CONFIGS:
            path = parquet_path(root, config).as_posix().replace("'", "''")
            result = connection.execute(
                f"SELECT count(*) FROM read_parquet('{path}')"
            ).fetchone()[0]
            validation.require(
                result == report["counts"][config],
                f"DuckDB count mismatch for {config}.",
            )
    finally:
        connection.close()


def verify_datasets(root: Path, report: dict[str, Any], validation: Validation) -> None:
    try:
        from datasets import load_dataset
    except ImportError:
        validation.errors.append("datasets package is unavailable.")
        return
    with tempfile.TemporaryDirectory(prefix="paper-tex-corpus-datasets-") as cache:
        for config in EXPECTED_CONFIGS:
            try:
                dataset = load_dataset(
                    str(root),
                    config,
                    split="train",
                    cache_dir=str(Path(cache) / config),
                    download_mode="force_redownload",
                )
            except Exception as error:
                validation.errors.append(
                    f"datasets.load_dataset failed for {config}: {error}"
                )
                continue
            validation.require(
                len(dataset) == report["counts"][config],
                f"datasets row count mismatch for {config}.",
            )


def artifact_hashes(root: Path) -> dict[str, str]:
    selected: dict[str, str] = {}
    for prefix in ("data", "raw", "metadata"):
        base = root / prefix
        for path in sorted(item for item in base.rglob("*") if item.is_file()):
            relative = path.relative_to(root).as_posix()
            selected[relative] = sha256_file(path)
    for name in ("README.md", "LICENSE", "CITATION.cff", "build-report.json"):
        selected[name] = sha256_file(root / name)
    return selected


def verify_comparison(root: Path, other: Path, validation: Validation) -> None:
    other = other.resolve()
    validation.require(other.is_dir(), f"Comparison build is missing: {other}")
    if not other.is_dir():
        return
    validation.require(
        artifact_hashes(root) == artifact_hashes(other),
        "Deterministic rebuild comparison failed.",
    )


def main() -> None:
    args = parse_args()
    root = args.dataset.resolve()
    validation = Validation()
    validation.require(root.is_dir(), f"Dataset directory is missing: {root}")
    validation.require(
        (root / ".paper-tex-corpus-build").is_file(),
        "Dataset build sentinel is missing.",
    )
    report_path = root / "build-report.json"
    validation.require(report_path.is_file(), "build-report.json is missing.")
    if not report_path.is_file():
        print(json.dumps({"status": "failed", "errors": validation.errors}, indent=2))
        raise SystemExit(1)
    report = json.loads(report_path.read_text(encoding="utf-8"))
    verify_checksums(root, validation)
    verify_card(root, validation)
    rows = verify_parquet(root, report, validation)
    verify_relations(root, rows, validation)
    verify_zip_security(root, rows["archives"], validation)
    verify_duckdb(root, report, validation)
    if not args.skip_datasets:
        verify_datasets(root, report, validation)
    if args.compare:
        verify_comparison(root, args.compare, validation)
    result = {
        "status": "passed" if not validation.errors else "failed",
        "assertions": validation.checks["assertions"],
        "errors": validation.errors,
        "warnings": validation.warnings,
        "counts": report["counts"],
    }
    print(json.dumps(result, ensure_ascii=False, indent=2, sort_keys=True))
    if validation.errors:
        raise SystemExit(1)


if __name__ == "__main__":
    main()