File size: 5,880 Bytes
97b4103
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Audit one Stack v3 TRAIN shard using only nested metadata columns."""

from __future__ import annotations

import argparse
import hashlib
import json
from collections import Counter, defaultdict
from pathlib import Path

import pyarrow.parquet as pq


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--input", type=Path, required=True)
    parser.add_argument("--panel", type=Path, required=True)
    parser.add_argument("--revision", required=True)
    parser.add_argument("--generated-at", required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()

    panel = set(json.loads(args.panel.read_text())["matrix_languages"])
    counts: dict[str, Counter[str]] = defaultdict(Counter)
    eligible_repos: dict[str, set[str]] = defaultdict(set)
    license_counts: dict[str, Counter[str]] = defaultdict(Counter)
    license_combo_counts: dict[str, Counter[tuple[str, ...]]] = defaultdict(Counter)
    content_ids: Counter[str] = Counter()
    repo_rows = 0
    mixed_panel_language_repos = 0
    declared_files = 0
    observed_files = 0
    inconsistent_num_files_rows = 0

    parquet = pq.ParquetFile(args.input)
    columns = [
        "repo_path",
        "num_files",
        "files.list.element.content_id",
        "files.list.element.size_bytes",
        "files.list.element.language",
        "files.list.element.is_vendor",
        "files.list.element.license_type",
        "files.list.element.detected_licenses",
    ]
    for batch in parquet.iter_batches(batch_size=128, columns=columns):
        for repo in batch.to_pylist():
            repo_rows += 1
            files = repo["files"] or []
            declared_files += repo["num_files"]
            observed_files += len(files)
            if repo["num_files"] != len(files):
                inconsistent_num_files_rows += 1
            repo_panel_languages = set()
            for file in files:
                language = file["language"]
                size = file["size_bytes"] or 0
                if language not in panel:
                    continue
                repo_panel_languages.add(language)
                counts[language]["files"] += 1
                counts[language]["bytes"] += size
                license_type = file["license_type"] or "null"
                counts[language][f"license_type_{license_type}_files"] += 1
                counts[language][f"license_type_{license_type}_bytes"] += size
                if file["is_vendor"]:
                    counts[language]["vendor_files"] += 1
                    counts[language]["vendor_bytes"] += size
                licenses = tuple(sorted(file["detected_licenses"] or []))
                for license_id in licenses:
                    license_counts[language][license_id] += 1
                license_combo_counts[language][licenses] += 1
                if license_type == "permissive" and not file["is_vendor"]:
                    counts[language]["eligible_files"] += 1
                    counts[language]["eligible_bytes"] += size
                    eligible_repos[language].add(repo["repo_path"])
                    if file["content_id"]:
                        content_ids[file["content_id"]] += 1
            if len(repo_panel_languages) > 1:
                mixed_panel_language_repos += 1

    language_rows = {}
    for language in sorted(panel):
        row = dict(sorted(counts[language].items()))
        row["eligible_repositories"] = len(eligible_repos[language])
        row["detected_license_counts"] = dict(
            sorted(license_counts[language].items(), key=lambda item: (-item[1], item[0]))
        )
        row["detected_license_combination_counts"] = {
            ";".join(combo) if combo else "<none>": count
            for combo, count in sorted(
                license_combo_counts[language].items(),
                key=lambda item: (-item[1], item[0]),
            )
        }
        language_rows[language] = row

    result = {
        "schema_version": "1.0.0",
        "source_id": "hf_stack_v3_train",
        "artifact_revision": args.revision,
        "generated_at": args.generated_at,
        "input": {
            "filename": args.input.name,
            "size_bytes": args.input.stat().st_size,
            "sha256": sha256(args.input),
            "parquet_rows": parquet.metadata.num_rows,
            "parquet_row_groups": parquet.metadata.num_row_groups,
        },
        "audit_scope": "metadata-only pilot; file content was not read or republished",
        "warning": "A single shard is a pipeline validation artifact, not a statistically guaranteed representative sample and must not be extrapolated to final corpus totals.",
        "repository_rows": repo_rows,
        "declared_files": declared_files,
        "observed_files": observed_files,
        "rows_with_num_files_mismatch": inconsistent_num_files_rows,
        "repositories_with_multiple_panel_languages": mixed_panel_language_repos,
        "eligible_definition": "matrix language AND license_type=permissive AND is_vendor=false; detected-license allowlist and other project filters are still pending",
        "eligible_content_ids": len(content_ids),
        "repeated_eligible_content_ids": sum(count > 1 for count in content_ids.values()),
        "maximum_eligible_content_id_multiplicity": max(content_ids.values(), default=0),
        "languages": language_rows,
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")


if __name__ == "__main__":
    main()