Download stackgo/tests/audit_repoinfo_stack_v2.py from s0duku/the-stack-go: direct link, hf CLI and curl.
- Browser
- Download file 9.44 kB
-
https://huggingface.co/datasets/s0duku/the-stack-go/resolve/main/stackgo/tests/audit_repoinfo_stack_v2.py
- Command line
-
hf download hf://datasets/s0duku/the-stack-go/stackgo/tests/audit_repoinfo_stack_v2.py
-
curl -L -o audit_repoinfo_stack_v2.py https://huggingface.co/datasets/s0duku/the-stack-go/resolve/main/stackgo/tests/audit_repoinfo_stack_v2.py
9.44 kB
| """Randomized read-only audit of repoinfo against local The Stack v2 data. | |
| The default run samples ten batches of ten repositories. It verifies source | |
| blob integrity, graph invariants, reference/edge consistency, SCC ordering and | |
| reports AST-vs-regex differences for manual review. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from collections import Counter, defaultdict | |
| from dataclasses import asdict | |
| import hashlib | |
| import json | |
| import os | |
| from pathlib import Path | |
| import random | |
| import time | |
| import pyarrow.parquet as pq | |
| from stackbuild import Repo, RepoFile, concatenation_dfs, scan | |
| ROOT = Path(__file__).resolve().parents[1] | |
| DATA_ROOT = Path(os.environ.get( | |
| "STACKGO_DATA_ROOT", "/home/ldj/tgai/data/pretrain-data" | |
| )) | |
| DEFAULT_DATA = DATA_ROOT / "the-stack-v2-contents-star-gt10" | |
| DEFAULT_REPORT = ROOT / "reports/repoinfo-stack-v2-audit.json" | |
| def sample_repositories(root: Path, batches: int, batch_size: int, seed: int): | |
| rng = random.Random(seed) | |
| shards = sorted((root / "shards").glob("*/repositories.parquet")) | |
| if not shards: | |
| raise FileNotFoundError(f"No repository metadata under {root}") | |
| selected = [] | |
| for batch_index in range(batches): | |
| metadata = shards[batch_index % len(shards)] | |
| parquet = pq.ParquetFile(metadata) | |
| indices = sorted(rng.sample(range(parquet.metadata.num_rows), batch_size)) | |
| wanted = set(indices) | |
| rows = [] | |
| offset = 0 | |
| for record_batch in parquet.iter_batches( | |
| columns=["repo_name", "revision_id", "files"], batch_size=256, use_threads=False | |
| ): | |
| for local_index, row in enumerate(record_batch.to_pylist()): | |
| if offset + local_index in wanted: | |
| rows.append(row) | |
| offset += record_batch.num_rows | |
| if len(rows) == batch_size: | |
| break | |
| selected.append((metadata.parent, rows)) | |
| return selected | |
| def load_bodies(shard: Path, rows: list[dict]) -> dict[str, bytes]: | |
| needed = {file["blob_id"] for row in rows for file in row.get("files") or []} | |
| bodies: dict[str, bytes] = {} | |
| for path in sorted((shard / "contents").glob("*.parquet")): | |
| for batch in pq.ParquetFile(path).iter_batches( | |
| columns=["blob_id", "content"], batch_size=2048, use_threads=False | |
| ): | |
| for item in batch.to_pylist(): | |
| if item["blob_id"] in needed: | |
| bodies[item["blob_id"]] = bytes(item["content"]) | |
| if len(bodies) == len(needed): | |
| break | |
| return bodies | |
| def make_repo(row: dict, bodies: dict[str, bytes]) -> tuple[Repo, list[str]]: | |
| files, errors = [], [] | |
| for item in row.get("files") or []: | |
| body = bodies.get(item["blob_id"]) | |
| if body is None: | |
| errors.append(f"missing body {item['blob_id']} {item['path']}") | |
| continue | |
| if hashlib.sha1(body).hexdigest() != item["blob_id"]: | |
| errors.append(f"sha1 mismatch {item['blob_id']} {item['path']}") | |
| continue | |
| files.append(RepoFile( | |
| item["path"], body, item.get("language"), item.get("src_encoding"), | |
| item["blob_id"], item.get("is_vendor"), item.get("is_generated"), | |
| )) | |
| return Repo(row["repo_name"], row["revision_id"], tuple(files)), errors | |
| def audit_info(repo: Repo, info) -> tuple[list[str], list[str]]: | |
| errors, warnings = [], [] | |
| paths = {file.path.lstrip("/") for file in repo.files} | |
| if len(paths) != len(repo.files): | |
| errors.append("duplicate normalized paths") | |
| components = {} | |
| for index, component in enumerate(info.strongly_connected_components): | |
| for path in component: | |
| components[path] = index | |
| positions = {path: index for index, path in enumerate(info.topological_order)} | |
| dfs_paths = concatenation_dfs(info) | |
| if dfs_paths != info.topological_order: | |
| errors.append("concatenation tree DFS differs from topological order") | |
| if len(dfs_paths) != len(set(dfs_paths)) or set(dfs_paths) != paths: | |
| errors.append("concatenation tree does not cover every file exactly once") | |
| if info.concatenation_tree is None or info.concatenation_tree.name != repo.repo_id: | |
| errors.append("concatenation tree repository root mismatch") | |
| edge_keys = {(edge.source, edge.target) for edge in info.edges if edge.status == "resolved"} | |
| for edge in info.edges: | |
| if edge.source not in paths or edge.target not in paths: | |
| errors.append(f"edge endpoint missing: {edge.source} -> {edge.target}") | |
| if edge.source == edge.target: | |
| errors.append(f"self edge: {edge.source}") | |
| if (components.get(edge.source) != components.get(edge.target) | |
| and positions.get(edge.target, -1) > positions.get(edge.source, -1)): | |
| errors.append(f"dependency ordered after source: {edge.source} -> {edge.target}") | |
| for reference in info.references: | |
| if reference.source_path not in paths: | |
| errors.append(f"reference source missing: {reference.source_path}") | |
| if reference.status == "internal": | |
| if not reference.target_path or reference.target_path not in paths: | |
| errors.append(f"internal target missing: {reference.source_path} {reference.name}") | |
| elif (reference.source_path, reference.target_path) not in edge_keys: | |
| errors.append(f"internal reference has no edge: {reference.source_path} -> {reference.target_path}") | |
| if reference.status == "external" and reference.candidates: | |
| errors.append(f"external reference has candidates: {reference.source_path} {reference.name}") | |
| if reference.status == "unresolved": | |
| tail = reference.name.replace("::", "/").replace(".", "/").rstrip("/").split("/")[-1] | |
| obvious = sorted(path for path in paths | |
| if path != reference.source_path | |
| and Path(path).stem.lower() == tail.lower())[:5] | |
| if obvious: | |
| warnings.append( | |
| f"unresolved with same-stem candidates: {reference.source_path} {reference.name} -> {obvious}" | |
| ) | |
| return errors, warnings | |
| def edge_set(info) -> set[tuple[str, str]]: | |
| return {(edge.source, edge.target) for edge in info.edges if edge.status == "resolved"} | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--data-root", type=Path, default=DEFAULT_DATA) | |
| parser.add_argument("--batches", type=int, default=10) | |
| parser.add_argument("--batch-size", type=int, default=10) | |
| parser.add_argument("--seed", type=int, default=20261030) | |
| parser.add_argument("--report", type=Path, default=DEFAULT_REPORT) | |
| args = parser.parse_args() | |
| sampled = sample_repositories(args.data_root, args.batches, args.batch_size, args.seed) | |
| report = {"seed": args.seed, "batches": [], "totals": {}} | |
| totals = Counter() | |
| started = time.perf_counter() | |
| for batch_index, (shard, rows) in enumerate(sampled, 1): | |
| bodies = load_bodies(shard, rows) | |
| batch_report = {"batch": batch_index, "shard": shard.name, "repositories": []} | |
| for row in rows: | |
| repo, source_errors = make_repo(row, bodies) | |
| start = time.perf_counter() | |
| info = scan(repo) | |
| regex_info = scan(repo, use_treesitter=False) | |
| errors, warnings = audit_info(repo, info) | |
| errors[:0] = source_errors | |
| ast_edges, regex_edges = edge_set(info), edge_set(regex_info) | |
| ast_only, regex_only = sorted(ast_edges - regex_edges), sorted(regex_edges - ast_edges) | |
| if ast_only or regex_only: | |
| warnings.append(f"backend edge delta ast_only={len(ast_only)} regex_only={len(regex_only)}") | |
| record = { | |
| "repo_id": repo.repo_id, | |
| "revision_id": repo.revision_id, | |
| "elapsed_seconds": time.perf_counter() - start, | |
| "stats": info.stats, | |
| "errors": errors, | |
| "warnings": warnings[:50], | |
| "ast_only_edges": ast_only[:20], | |
| "regex_only_edges": regex_only[:20], | |
| } | |
| batch_report["repositories"].append(record) | |
| totals.update(repositories=1, files=info.stats["files"], edges=info.stats["resolved_edges"], | |
| errors=len(errors), warnings=len(warnings), ast_only=len(ast_only), | |
| regex_only=len(regex_only), missing_bodies=len(source_errors)) | |
| report["batches"].append(batch_report) | |
| print(f"batch {batch_index}/{args.batches} {shard.name}: " | |
| f"repos={len(rows)} errors={sum(len(x['errors']) for x in batch_report['repositories'])} " | |
| f"warnings={sum(len(x['warnings']) for x in batch_report['repositories'])}", flush=True) | |
| totals["elapsed_seconds"] = round(time.perf_counter() - started, 3) | |
| report["totals"] = dict(totals) | |
| args.report.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = args.report.with_suffix(args.report.suffix + ".part") | |
| temporary.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") | |
| temporary.replace(args.report) | |
| print(json.dumps(report["totals"], indent=2), flush=True) | |
| print(f"report: {args.report}", flush=True) | |
| if totals["errors"]: | |
| raise SystemExit(1) | |
| if __name__ == "__main__": | |
| main() | |