#!/usr/bin/env python3 """ Validate the qmmit agent-commit index against its documented schema, invariants and adoption-pattern classifier. Run before every release: python validate_dataset.py data/train-00000-of-00001.parquet summary.json Exits non-zero on any failure. Add it to CI so the dataset card can never drift away from the data it describes. """ from __future__ import annotations import json import sys from pathlib import Path import pandas as pd EXPECTED_COLUMNS = { "rank": "int64", "repo": "object", "github_url": "object", "stars_at_collection": "int64", "language": "object", "ecosystem": "object", "window_since": "object", "window_label": "object", "agent_share_pct_floor": "float64", "human_share_pct_ceiling": "float64", "commits_in_history": "int64", "merge_commits_excluded": "int64", "ci_bot_commits_excluded": "int64", "commits_considered": "int64", "agent_attributed_commits": "int64", "human_attributed_commits": "int64", "assisted_commits": "int64", "autonomous_commits": "int64", "assisted_pct": "float64", "autonomous_pct": "float64", "distinct_agent_authors": "int64", "top_author_share_of_agent_commits": "float64", "adoption_pattern": "object", "low_activity": "bool", "agents_json": "object", "timeline_json": "object", "agent_commit_samples_json": "object", } STRING_COLUMNS = { "repo", "github_url", "language", "ecosystem", "window_since", "window_label", "adoption_pattern", "agents_json", "timeline_json", "agent_commit_samples_json", } PATTERNS = {"none", "individual", "team", "org-wide"} LOW_ACTIVITY_THRESHOLD = 100 TOLERANCE = 0.15 # one decimal place of rounding, plus slack failures: list[str] = [] def check(name: str, ok: bool, detail: str = "") -> None: if ok: print(f" PASS {name}") else: print(f" FAIL {name}{(' — ' + detail) if detail else ''}") failures.append(name) def classify(row) -> str: """The documented adoption-pattern rule. Keep in sync with the scanner.""" if row.agent_attributed_commits == 0: return "none" if row.distinct_agent_authors <= 3: return "individual" if row.top_author_share_of_agent_commits >= 80: return "individual" if row.distinct_agent_authors <= 8: return "team" if row.top_author_share_of_agent_commits >= 50: return "team" return "org-wide" def main(parquet_path: str, summary_path: str | None, resolution_path: str | None = None) -> int: df = pd.read_parquet(parquet_path) jsonl_path = Path(parquet_path).with_name("repositories.jsonl") if jsonl_path.exists(): print("\nJSONL mirror") jsonl_rows = [json.loads(line) for line in jsonl_path.read_text().splitlines()] check("JSONL row count", len(jsonl_rows) == len(df), f"{len(jsonl_rows)} vs {len(df)}") check("JSONL ranks and slugs match parquet", [(row["rank"], row["repo"]) for row in jsonl_rows] == list(zip(df["rank"].tolist(), df["repo"].tolist()))) print("\nSchema") check("column set matches the card", set(df.columns) == set(EXPECTED_COLUMNS), f"unexpected={sorted(set(df.columns) - set(EXPECTED_COLUMNS))} " f"missing={sorted(set(EXPECTED_COLUMNS) - set(df.columns))}") for col, dtype in EXPECTED_COLUMNS.items(): if col in df.columns: if col in STRING_COLUMNS: compatible = pd.api.types.is_string_dtype(df[col]) elif col == "stars_at_collection": compatible = pd.api.types.is_numeric_dtype(df[col]) else: compatible = str(df[col].dtype) == dtype check(f"dtype {col} is compatible with {dtype}", compatible, f"got {df[col].dtype}") print("\nIntegrity") allowed_nulls = {"stars_at_collection", "language"} null_columns = set(df.columns[df.isnull().any()]) check("no null values in measurement fields", null_columns <= allowed_nulls, f"unexpected={null_columns - allowed_nulls}") check("repo slugs unique", df.repo.is_unique) check("github_url unique", df.github_url.is_unique) check("single measurement window", df.window_since.nunique() == 1) check("adoption_pattern in vocabulary", set(df.adoption_pattern) <= PATTERNS, f"unknown={set(df.adoption_pattern) - PATTERNS}") print("\nCommit-accounting invariants") check("history == merges + ci_bots + considered", (df.commits_in_history == df.merge_commits_excluded + df.ci_bot_commits_excluded + df.commits_considered).all()) check("considered == agent + human", (df.commits_considered == df.agent_attributed_commits + df.human_attributed_commits).all()) check("agent == assisted + autonomous", (df.agent_attributed_commits == df.assisted_commits + df.autonomous_commits).all()) check("no negative counts", (df.select_dtypes("int64") >= 0).all().all()) check("considered >= 0", (df.commits_considered >= 0).all()) print("\nPercentage consistency") active = df[df.commits_considered > 0] recomputed = active.agent_attributed_commits / active.commits_considered * 100 check("agent_share_pct_floor matches the counts", (recomputed - active.agent_share_pct_floor).abs().max() < TOLERANCE, f"max delta {(recomputed - active.agent_share_pct_floor).abs().max():.3f}") check("floor + ceiling == 100 for active histories", ((active.agent_share_pct_floor + active.human_share_pct_ceiling) - 100) .abs().max() < TOLERANCE) check("assisted_pct + autonomous_pct == agent share for active histories", ((active.assisted_pct + active.autonomous_pct - active.agent_share_pct_floor) .abs().max() < TOLERANCE)) percentage_columns = ["agent_share_pct_floor", "human_share_pct_ceiling", "assisted_pct", "autonomous_pct", "top_author_share_of_agent_commits"] check("percentages within [0, 100]", active[percentage_columns].apply( lambda col: col.between(0, 100)).all().all()) print("\nConcentration and flags") check("low_activity == considered < 100", (df.low_activity == (df.commits_considered < LOW_ACTIVITY_THRESHOLD)).all()) check("distinct_agent_authors == 0 iff no agent commits", ((df.distinct_agent_authors == 0) == (df.agent_attributed_commits == 0)).all()) check("agent authors never exceed agent commits", (df.distinct_agent_authors <= df.agent_attributed_commits).all()) mismatched = df[df.apply(classify, axis=1) != df.adoption_pattern] check("adoption_pattern matches the documented classifier", mismatched.empty, f"{len(mismatched)} rows differ, e.g. " f"{mismatched.repo.head(3).tolist()}") print("\nNested JSON columns") for col in ("agents_json", "timeline_json", "agent_commit_samples_json"): try: parsed = df[col].map(json.loads) check(f"{col} parses as a JSON list", parsed.map(lambda v: isinstance(v, list)).all()) except Exception as exc: # noqa: BLE001 check(f"{col} parses as a JSON list", False, str(exc)) agent_totals = df.agents_json.map( lambda s: sum(a.get("commits", 0) for a in json.loads(s))) check("agents_json commits cover agent_attributed_commits", (agent_totals >= df.agent_attributed_commits).all(), f"{(agent_totals < df.agent_attributed_commits).sum()} rows differ") timeline_agent = df.timeline_json.map( lambda s: sum(m.get("agent", 0) for m in json.loads(s))) check("timeline_json agent commits sum to agent_attributed_commits", (timeline_agent == df.agent_attributed_commits).all(), f"{(timeline_agent != df.agent_attributed_commits).sum()} rows differ") if summary_path and Path(summary_path).exists(): print("\nsummary.json agreement") s = json.loads(Path(summary_path).read_text()) block = s["summary"] check("repository_count", s["repository_count"] == len(df), f"{s['repository_count']} vs {len(df)}") check("totalCommits", block["totalCommits"] == int(df.commits_considered.sum()), f"{block['totalCommits']} vs {int(df.commits_considered.sum())}") agg = df.agent_attributed_commits.sum() / df.commits_considered.sum() * 100 check("aggregateSharePct", abs(block["aggregateSharePct"] - agg) < TOLERANCE, f"{block['aggregateSharePct']} vs {agg:.2f}") check("medianSharePct", abs(block["medianSharePct"] - df.agent_share_pct_floor.median()) < TOLERANCE) check("zeroRepos", block["zeroRepos"] == int((df.agent_share_pct_floor == 0).sum()), f"{block['zeroRepos']} vs {int((df.agent_share_pct_floor == 0).sum())}") for pattern, n in block["patternCounts"].items(): check(f"patternCounts[{pattern}]", n == int((df.adoption_pattern == pattern).sum()), f"{n} vs {int((df.adoption_pattern == pattern).sum())}") if resolution_path and Path(resolution_path).exists(): print("\nrepository_resolution.json agreement") resolution = json.loads(Path(resolution_path).read_text()) rows = resolution["rows"] by_rank = {row["rank"]: row for row in rows} check("resolution row count", len(rows) == len(df), f"{len(rows)} vs {len(df)}") check("all repositories resolved", all(row["valid"] for row in rows)) check("all source slugs are valid", all(row["source_slug_valid"] for row in rows)) check("all URL slugs match source slugs", all(row["url_slug_matches_source"] for row in rows)) check("all canonical targets unique", not resolution["duplicate_canonical_repositories"]) check("resolution ranks unique", len(by_rank) == len(rows)) check("resolution slugs agree with parquet", all(by_rank.get(int(row["rank"]), {}).get("source_repo") == row["repo"] for _, row in df.iterrows())) check("resolution URLs agree with parquet", all(by_rank.get(int(row["rank"]), {}).get("source_github_url") == row["github_url"] for _, row in df.iterrows())) print(f"\n{'FAILED: ' + str(len(failures)) + ' check(s)' if failures else 'All checks passed.'}") return 1 if failures else 0 if __name__ == "__main__": if len(sys.argv) < 2: print(__doc__) sys.exit(2) sys.exit(main( sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None, sys.argv[3] if len(sys.argv) > 3 else None, ))