File size: 8,697 Bytes
43b4299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
"""Validate all publication bundles, evidence counts and anonymous-safe data.

Reads at most one compressed episode at a time. Never prints source contents.
"""
from pathlib import Path
import argparse
import collections
import gzip
import json
import math
import resource

import numpy as np
import pandas as pd
import pyarrow.parquet as pq

from export_corpus import Builder, Redactor, digest, dumps, telemetry


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--check-originals", action="store_true")
    args = parser.parse_args()
    out = Path(__file__).resolve().parents[1]
    episodes = pd.concat([pd.read_parquet(out / f"data/{c}.parquet") for c in ["olmo", "qwen", "forest"]], ignore_index=True)
    sources = pd.read_parquet(out / "data/sources.parquet")
    coverage = pd.read_parquet(out / "data/coverage.parquet")
    examples = pd.read_parquet(out / "data/example_summary.parquet")
    tokens = pd.read_parquet(out / "data/token_diagnostics.parquet")
    joins = pd.read_parquet(out / "data/forest_joins.parquet")
    inventory = pd.read_csv(out / "provenance/recording_inventory.csv", keep_default_na=False)
    assert episodes.episode_id.is_unique
    assert episodes.groupby("collection").size().to_dict() == {"forest":371,"olmo":570,"qwen":510}
    assert examples.groupby("example_kind").size().to_dict() == {"experiment1_judge_packet":144,"final":218,"process":8633,"rejection":74}
    assert len(inventory) == 1958
    assert not inventory.path.str.match(r"(?:tmax|opd_exp)/").any()
    assert (inventory.archive_member == "").all()
    assert not sources.source_path.str.contains(r"codex-session-trajectories|(?:^|/)\.codex/|^tmax/").any()
    expected = {"invalid":3,"trajectory_missing_at_archive_time":368,"27b_summary_only":64,"original_raw_run_missing":1}
    assert coverage.status.value_counts().to_dict() == expected, coverage.status.value_counts().to_dict()
    assert len(episodes[episodes.retained_experiment2_id.notna()]) == 503
    assert set(tokens.episode_id).issubset(set(episodes.episode_id))
    verified = joins[joins.match_status == "verified_trial_uuid_and_branch"]
    assert (verified.candidate_count == 1).all()
    assert verified.episode_id.notna().all()
    assert set(verified.episode_id).issubset(set(episodes.loc[episodes.collection == "forest", "episode_id"]))
    assert joins.loc[joins.match_status != "verified_trial_uuid_and_branch", "episode_id"].isna().all()
    forest_keys = collections.defaultdict(set)
    for r in inventory[inventory.project == "forestOfAudits"].itertuples():
        key = Builder.forest_identity(None, r.path)
        if key:
            from export_corpus import identity
            forest_keys[key].add(identity(r.episode_key))
    for r in verified.itertuples():
        key = Builder.forest_identity(None, r.public_source_path)
        assert forest_keys[key] == {r.episode_id}
    redactor = Redactor()
    source_count, token_count, bundle_count = 0, 0, 0
    max_bundle_bytes = 0
    episode_events = collections.Counter()
    for i, row in enumerate(episodes.itertuples()):
        path = out / row.detail_path
        with gzip.open(path, "rb") as handle:
            raw = handle.read()
        max_bundle_bytes = max(max_bundle_bytes, len(raw))
        bundle = json.loads(raw)
        assert bundle["episode"]["episode_id"] == row.episode_id
        assert sum(e["canonical_view"] for e in bundle["events"]) == row.events
        episode_events[row.episode_id] = len(bundle["events"])
        raw_tokens = []
        for view in bundle["recordings"]:
            source = view["source"]
            payload = dumps(view["data"]).encode()
            assert digest(payload) == source["publication_sha256"], source["source_path"]
            if args.check_originals:
                original = out.parent / source["source_path"]
                assert digest(original.read_bytes()) == source["source_sha256"], source["source_path"]
            before = len(redactor.rows)
            redactor.clean(view["data"], source["source_path"])
            assert len(redactor.rows) == before, f"Credential pattern remains in {source['source_path']}"
            obj = view["data"]
            if isinstance(obj, dict):
                for s in obj.get("steps", []):
                    m = s.get("metrics") or {}
                    if isinstance(m.get("completion_token_ids"), list) and isinstance(m.get("logprobs"), list):
                        raw_tokens.append(telemetry(m))
                for batch in (obj.get("agent_result") or {}).get("rollout_details") or []:
                    ids, lps = batch.get("completion_token_ids", []), batch.get("logprobs", [])
                    if ids and isinstance(ids[0], list):
                        for j in range(max(len(ids), len(lps))):
                            raw_tokens.append(telemetry({"completion_token_ids":ids[j] if j<len(ids) else [],"logprobs":lps[j] if j<len(lps) else []}))
                    else:
                        raw_tokens.append(telemetry(batch))
            source_count += 1
        stored = bundle["token_diagnostics"]
        assert len(raw_tokens) == len(stored), row.episode_id
        for raw_t, stored_t in zip(raw_tokens, stored):
            assert raw_t["alignment"] == stored_t["alignment"]
            assert raw_t["token_count"] == stored_t["token_count"]
            if raw_t["alignment"] == "aligned":
                assert math.isclose(raw_t["nll_sum"], stored_t["nll_sum"], rel_tol=1e-10, abs_tol=1e-8)
        good = [t for t in stored if t["alignment"] == "aligned"]
        count = sum(t["token_count"] for t in good)
        if count:
            assert math.isclose(sum(t["nll_sum"] for t in good)/count, row.selected_token_surprisal_nats, rel_tol=1e-9)
        token_count += len(stored)
        bundle_count += 1
        if i % 200 == 0:
            print(f"Verified {i}/{len(episodes)} bundles", flush=True)
    assert token_count == len(tokens)
    parquet_counts = collections.Counter()
    for p in (out / "data/events").rglob("*.parquet"):
        for batch in pq.ParquetFile(p).iter_batches(batch_size=4096, columns=["episode_id"]):
            parquet_counts.update(batch.column(0).to_pylist())
    assert parquet_counts == episode_events
    # Derived/public source copies are checked without printing their data.
    for row in sources[sources.public_path.notna()].itertuples() if "public_path" in sources else []:
        p = out / row.public_path
        raw = gzip.decompress(p.read_bytes()) if p.suffix == ".gz" else p.read_bytes()
        assert digest(raw) == row.publication_sha256, row.source_path
        redactor.text(raw.decode(), row.source_path, "$")
    # Scan every remaining derived/auxiliary compressed copy and table payload.
    for p in out.rglob("*.gz"):
        if "recordings" in p.parts:
            continue
        raw = gzip.decompress(p.read_bytes())
        if p.name.endswith(".jsonl.gz"):
            values = [json.loads(line) for line in raw.splitlines() if line.strip()]
        else:
            values = json.loads(raw)
        before = len(redactor.rows)
        redactor.clean(values, str(p.relative_to(out)))
        assert len(redactor.rows) == before, f"Credential pattern in {p.name}"
    for name in ["annotations", "examples", "q09_transitions", "qwen27b_summary_only"]:
        frame = pd.read_parquet(out / f"data/{name}.parquet")
        for column in [c for c in frame if c.endswith("_json")]:
            for value in frame[column].dropna():
                before = len(redactor.rows)
                redactor.clean(json.loads(value), name)
                assert len(redactor.rows) == before, f"Credential pattern in table {name}"
    assert not redactor.rows
    report = {"status":"passed", "episode_counts":episodes.groupby("collection").size().to_dict(),
              "bundles_verified":bundle_count, "embedded_source_hashes_verified":source_count,
              "token_sequences_recomputed":token_count, "event_rows_verified":sum(parquet_counts.values()),
              "example_counts":examples.groupby("example_kind").size().to_dict(),
              "coverage":expected, "verified_forest_example_joins":len(verified),
              "max_uncompressed_bundle_bytes":max_bundle_bytes,
              "peak_validation_rss_mib":resource.getrusage(resource.RUSAGE_SELF).ru_maxrss/1024,
              "original_source_hashes_checked":args.check_originals,
              "credential_scan":"all publication recording views and derived public copies"}
    (out / "provenance/validation.json").write_text(json.dumps(report,indent=2)+"\n")
    print(json.dumps(report,indent=2))


if __name__ == "__main__":
    main()