File size: 4,552 Bytes
14d6235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f5d257
 
 
14d6235
3f5d257
14d6235
3f5d257
14d6235
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Read every output record, validate its schemas and independently recompute its key."""
import argparse
from collections import Counter
import gzip
import hashlib
import json
from pathlib import Path
import re

import fastjsonschema
import xxhash

DOI_NAME = re.compile(r"\A10\.[0-9]+(?:\.[0-9]+)*/.+\Z")
CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]")


def is_lowercase_doi_name(value: str) -> bool:
    return (value.strip() == value and not CONTROL.search(value)
            and DOI_NAME.match(value) is not None and value == value.lower())


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("dataset_dir", type=Path)
    args = parser.parse_args()
    root = args.dataset_dir
    manifest = json.loads((root / "manifest.json").read_text())
    check_enrichment = fastjsonschema.compile(json.loads(
        (root / "provenance/enrichment_input_schema.json").read_text()))
    check_value = fastjsonschema.compile(json.loads(
        (root / "provenance/related_identifier_subset_schema.json").read_text()))
    expected = manifest["counts"]
    counts = Counter()
    keys = set()
    dois = set()
    files = manifest["data_files"]
    # Every file under data/, not only data/*.jsonl.gz, so a leftover
    # subdirectory that the default config would not load also fails.
    on_disk = {str(p.relative_to(root)) for p in (root / "data").rglob("*") if p.is_file()}
    listed = {item["path"] for item in files}
    assert on_disk == listed, f"unlisted {sorted(on_disk - listed)}, missing {sorted(listed - on_disk)}"
    for item in files:
        path = root / item["path"]
        with path.open("rb") as stream:
            digest = hashlib.file_digest(stream, "sha256").hexdigest()
        assert digest == item["sha256"], f"{item['path']}: sha256 {digest} != manifest {item['sha256']}"
        n = 0
        with gzip.open(path, "rt", encoding="utf-8") as stream:
            for line in stream:
                row = json.loads(line)
                check_enrichment(row)
                value = row["enrichedValue"]
                check_value(value)
                assert set(row) == {"doi", "action", "field", "enrichedValue", "sourceId", "contentKey"}
                assert row["action"] == "insert" and row["field"] == "relatedIdentifiers"
                assert row["sourceId"] == manifest["source_id"], f"sourceId {row['sourceId']!r}"
                assert is_lowercase_doi_name(row["doi"]), row["doi"]
                assert is_lowercase_doi_name(value["relatedIdentifier"]), value["relatedIdentifier"]
                # Every object key here is ASCII and every value is a string.
                # Sorted, compact UTF-8 JSON is therefore JCS for this domain.
                # This intentionally uses a different serializer than convert.py.
                canonical = json.dumps(
                    [manifest["method"]["name"], row["doi"], row["field"], row["action"], value],
                    ensure_ascii=False, sort_keys=True, separators=(",", ":"),
                ).encode("utf-8")
                expected_key = xxhash.xxh3_128_hexdigest(canonical)
                assert row["contentKey"] == expected_key, (
                    f"{item['path']}: contentKey {row['contentKey']} != recomputed {expected_key}")
                key = bytes.fromhex(expected_key)
                assert key not in keys, f"{item['path']}: duplicate contentKey {expected_key}"
                keys.add(key)
                dois.add(row["doi"])
                counts["enrichments"] += 1
                counts["to_arxiv_dois"] += row["doi"].startswith("10.48550/")
                n += 1
        assert n == item["rows"], f"{item['path']}: {n} records != manifest {item['rows']}"
        print(f"Validated {item['path']}: {n:,} records", flush=True)
    assert counts["enrichments"] == expected["enrichments"]
    assert len(dois) == expected["unique_enriched_dois"]
    assert counts["to_arxiv_dois"] == expected["enrichments_to_arxiv_dois"]
    report = {"status": "passed", "records_read_and_validated": counts["enrichments"],
              "unique_target_dois": len(dois), "data_shards": len(files),
              "enrichments_to_arxiv_dois": counts["to_arxiv_dois"],
              "schema_errors": 0, "content_key_mismatches": 0, "duplicate_content_keys": 0,
              "file_checksum_mismatches": 0}
    (root / "validation_report.json").write_text(json.dumps(report, indent=2) + "\n")
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()