| 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() |
|
|