#!/usr/bin/env python3 """Independently reconcile every exported value to retained publisher inputs. This validator never imports or executes the dataset builder. Raw identifiers remain in process memory and never appear in its report or diagnostics. Downloaded-package usage (original source snapshots must match manifest hashes): python tests/validate_export.py --dataset-dir . \ --posts-csv /path/to/posts.csv --comments-csv /path/to/comments.csv \ --cnn-json /path/to/truth_archive.json The optional --source-project supplies those raw paths from the visualization checkout and adds its frozen comparison checks. Alternatively, add only --comparison-json /path/to/comparison.json to the explicit-input command. """ from __future__ import annotations import argparse import ast from bisect import bisect_right from collections import Counter, defaultdict import csv from datetime import datetime, timezone import hashlib import html from html.parser import HTMLParser import json from pathlib import Path import re import struct import sys import time from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode import pyarrow as pa import pyarrow.csv as pc import pyarrow.parquet as pq COUNTS = { 'reply_features': 377622, 'posts': 97, 'topics': 12, 'phrases': 16, 'delay_bands': 11, 'post_topics': 1164, 'post_phrases': 1552, 'post_delays': 1067, 'post_topic_delays': 12804, 'post_phrase_delays': 17072, 'participation_daily': 52, 'cohorts': 52, 'cohort_activity': 1310, 'cohort_last_observed': 1261, 'feed_daily': 1646, 'feed_monthly': 57, 'feed_topics': 684, } EDGES = [0., 1 / 60, 5 / 60, .25, 1., 3., 6., 12., 24., 72., 168., None] def digest(path): with path.open('rb') as stream: return hashlib.file_digest(stream, 'sha256').hexdigest() def csv_rows(path): with path.open(encoding='utf-8-sig', newline='') as stream: yield from csv.DictReader(stream) def dt(value): parsed = datetime.fromisoformat(value.replace('Z', '+00:00')) if parsed.tzinfo is None: raise ValueError('Source timestamp has no explicit timezone') return parsed.astimezone(timezone.utc) def natural(value): try: return max(int(value or '0'), 0) except ValueError: return 0 def source_wording(value): """Independently remove only the publisher-sharing query parameter.""" def strip(match): parsed = urlsplit(match.group()) before = parse_qsl(parsed.query, keep_blank_values=True) after = [(key, val) for key, val in before if key.lower() != 'pwapi_token'] if before == after: return match.group() return urlunsplit(parsed._replace(query=urlencode(after))) return re.sub(r'https?://[^\s<>]+', strip, value) class FeedText(HTMLParser): """Use a native HTML parser, independently of the builder's tag regex.""" def __init__(self): super().__init__(convert_charrefs=True) self.parts = [] def handle_data(self, value): self.parts.append(value) def handle_starttag(self, tag, attrs): self.parts.append(' ') def handle_endtag(self, tag): self.parts.append(' ') def feed_text(value): parser = FeedText() parser.feed(value or '') parser.close() return ''.join(parser.parts).strip() class Audit: def __init__(self): self.checks = 0 self.failures = [] self.failed_checks = 0 self.cells = 0 def check(self, name, actual, expected=True): self.checks += 1 if actual != expected: self.failed_checks += 1 if len(self.failures) < 60: # Intentionally record labels only: never raw IDs or text. self.failures.append(name) def table(self, name, actual, expected): self.check(name + ' source-derived row count', actual.num_rows, len(expected)) errors = Counter() fields = actual.column_names rows = actual.to_pylist() for got, want in zip(rows, expected): for field in fields: self.cells += 1 if got.get(field) != want.get(field): errors[field] += 1 for field in fields: self.check(name + ' source-derived field ' + field, errors[field], 0) def source_definitions(dataset): """Read the packaged declared feature definitions without running code.""" module = ast.parse((dataset / 'src/build_dataset.py').read_text()) values = {} for node in module.body: if isinstance(node, ast.Assign): for target in node.targets: if isinstance(target, ast.Name) and target.id in {'TOPICS', 'PHRASES'}: values[target.id] = ast.literal_eval(node.value) topics = [(key.replace('-', '_'), label, pattern) for key, label, pattern in values['TOPICS']] phrases = values['PHRASES'] return topics, phrases def schemas(topics, phrases): I, S, D, B = pa.int64(), pa.string(), pa.float64(), pa.bool_() def spec(*pairs): return pa.schema([pa.field(name, kind) for name, kind in pairs]) post = ('post_id', S) topic = ('topic_id', S) phrase = ('phrase_id', S) band = ('delay_band', I) capture = ('captured_replies', I) matching = ('matching_replies', I) return { 'reply_features': spec(('observation_id', I), post, ('reply_day_utc', S), ('delay_hours', pa.float32()), ('delay_band', pa.int8()), ('likes_at_collection', I), ('has_captured_text', B), *[('topic_' + key, B) for key, _, _ in topics], *[('phrase_' + phrase.replace(' ', '_'), B) for phrase in phrases]), 'posts': spec(post, ('posted_at_utc', S), ('source_url', S), capture, ('nonempty_reply_records', I), ('likes_at_collection', I), ('reposts_at_collection', I), ('reported_replies_at_collection', I)), 'topics': spec(topic, ('label', S), ('pattern', S)), 'phrases': spec(phrase, ('phrase', S), ('pattern', S)), 'delay_bands': spec(band, ('lower_hours_inclusive', D), ('upper_hours_exclusive', D)), 'post_topics': spec(post, topic, ('source_contains_topic', B), matching, capture, ('reply_share', D)), 'post_phrases': spec(post, phrase, ('source_occurrences', I), matching, capture, ('reply_share', D)), 'post_delays': spec(post, band, capture), 'post_topic_delays': spec(post, topic, band, matching, ('captured_replies_in_band', I)), 'post_phrase_delays': spec(post, phrase, band, matching, ('captured_replies_in_band', I)), 'participation_daily': spec(('date', S), capture, ('active_accounts', I), ('first_observed_accounts', I), ('returning_accounts', I), ('last_observed_accounts', I)), 'cohorts': spec(('first_day_utc', S), ('accounts', I), capture), 'cohort_activity': spec(('first_day_utc', S), ('active_day_utc', S), ('active_accounts', I)), 'cohort_last_observed': spec(('first_day_utc', S), ('last_day_utc', S), ('accounts', I)), 'feed_daily': spec(('date', S), ('records', I), ('nonempty_records', I), *[('topic_' + key, I) for key, _, _ in topics]), 'feed_monthly': spec(('month', S), ('records', I), ('nonempty_records', I)), 'feed_topics': spec(('month', S), topic, ('matching_records', I), ('records', I), ('share', D)), } def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source-project', type=Path, help='Optional visualization checkout; supplies default raw paths and frozen comparison') parser.add_argument('--posts-csv', type=Path, help='Pinned publisher posts CSV') parser.add_argument('--comments-csv', type=Path, help='Pinned publisher replies CSV') parser.add_argument('--cnn-json', type=Path, help='Pinned CNN feed JSON snapshot') parser.add_argument('--comparison-json', type=Path, help='Optional frozen visualization comparison JSON for secondary checks') parser.add_argument('--dataset-dir', type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument('--report', type=Path) args = parser.parse_args() started = time.monotonic() out = args.dataset_dir.resolve() source = args.source_project.resolve() if args.source_project else None if source is None and not all((args.posts_csv, args.comments_csv, args.cnn_json)): parser.error('Provide --posts-csv, --comments-csv and --cnn-json, or --source-project') comparison_path = args.comparison_json if comparison_path is None and source is not None: comparison_path = source / 'site/supporters-data/comparison.json' report_path = args.report or out / 'docs/validation.json' audit = Audit() manifest = json.loads((out / 'manifest.json').read_text()) dictionary = json.loads((out / 'data_dictionary.json').read_text()) topics, phrases = source_definitions(out) tp = [re.compile(pattern, re.IGNORECASE) for _, _, pattern in topics] phrase_patterns = [r'(?= 80: long_text_hashes.add(hashlib.sha256(text.encode()).digest()) day = at.date().isoformat() likes = natural(raw['favourites_count']) tm, pm = [bool(p.search(text)) for p in tp], [bool(p.search(text)) for p in pp] want = dict(observation_id=retained, post_id=pid, reply_day_utc=day, delay_hours=delay, delay_band=band, likes_at_collection=likes, has_captured_text=bool(text)) want.update({'topic_' + key: tm[j] for j, (key, _, _) in enumerate(topics)}) want.update({'phrase_' + value.replace(' ', '_'): pm[j] for j, value in enumerate(phrases)}) got = next(feature_iterator, {}) for field in feature_columns: audit.cells += 1 if got.get(field) != want[field]: errors[field] += 1 retained += 1 totals[pid] += 1 text_counts[pid] += bool(text) like_counts[pid] += likes lag_counts[pid, band] += 1 for j, matched in enumerate(tm): topic_counts[pid, j] += matched topic_lags[pid, j, band] += matched for j, matched in enumerate(pm): phrase_counts[pid, j] += matched phrase_lags[pid, j, band] += matched account = raw['account_id'] if not account: errors['empty_raw_account'] += 1 account_ids.add(account) account_days[account][day] += 1 daily_accounts[day].add(account) reply_days[day] += 1 first_reply = min(first_reply or raw['created_at'], raw['created_at']) last_reply = max(last_reply or raw['created_at'], raw['created_at']) audit.check('no trailing feature rows', next(feature_iterator, None), None) for field in feature_columns + ['invalid_raw_parent', 'negative_raw_delay', 'empty_raw_account']: audit.check('all raw reply values: ' + field, errors[field], 0) audit.check('raw CSV rows', raw_count, 377624) audit.check('first-ID duplicates removed', duplicate_count, 2) audit.check('retained raw rows', retained, 377622) recurrent = sum(sum(days.values()) > 1 for days in account_days.values()) audit.check('raw accounts', len(account_days), 123271) audit.check('raw recurrent accounts', recurrent, 50622) print('Checked every raw reply value and account aggregate basis', flush=True) expected = {name: [] for name in ['posts', 'post_topics', 'post_phrases', 'post_delays', 'post_topic_delays', 'post_phrase_delays']} comparison = json.loads(comparison_path.read_text()) if comparison_path else None secondary_checks = 0 if comparison is not None: audit.check('secondary comparison definitions', [(row['id'].replace('-', '_'), row['label'], row['pattern']) for row in comparison['topics']], topics) secondary_checks += 1 for index, p in enumerate(posts): pid = p['post_id'] plain = source_wording(p['content_clean']) source_topics = [bool(pat.search(plain)) for pat in tp] source_phrases = [len(pat.findall(plain)) for pat in pp] url = urlsplit(p['url']) expected['posts'].append(dict(post_id=pid, posted_at_utc=p['created_at'], source_url=urlunsplit((url.scheme, url.netloc, url.path, '', '')), captured_replies=totals[pid], nonempty_reply_records=text_counts[pid], likes_at_collection=natural(p['favourites_count']), reposts_at_collection=natural(p['reblogs_count']), reported_replies_at_collection=natural(p['replies_count']))) for j, (key, _, _) in enumerate(topics): expected['post_topics'].append(dict(post_id=pid, topic_id=key, source_contains_topic=source_topics[j], matching_replies=topic_counts[pid, j], captured_replies=totals[pid], reply_share=topic_counts[pid, j] / totals[pid])) for k in range(11): expected['post_topic_delays'].append(dict(post_id=pid, topic_id=key, delay_band=k, matching_replies=topic_lags[pid, j, k], captured_replies_in_band=lag_counts[pid, k])) for j, value in enumerate(phrases): key = value.replace(' ', '_') expected['post_phrases'].append(dict(post_id=pid, phrase_id=key, source_occurrences=source_phrases[j], matching_replies=phrase_counts[pid, j], captured_replies=totals[pid], reply_share=phrase_counts[pid, j] / totals[pid])) for k in range(11): expected['post_phrase_delays'].append(dict(post_id=pid, phrase_id=key, delay_band=k, matching_replies=phrase_lags[pid, j, k], captured_replies_in_band=lag_counts[pid, k])) expected['post_delays'].extend(dict(post_id=pid, delay_band=k, captured_replies=lag_counts[pid, k]) for k in range(11)) if comparison is not None: reference = comparison['posts'][index] # Independent raw counters must also reproduce frozen visualization data. audit.check('secondary post counts ' + str(index), [totals[pid], text_counts[pid]], [reference['replies'], reference['nonemptyReplies']]) audit.check('secondary source topic flags ' + str(index), source_topics, reference['sourceTopics']) audit.check('secondary source phrase occurrences ' + str(index), source_phrases, reference['sourcePhraseOccurrences']) audit.check('secondary reply topic counts ' + str(index), [topic_counts[pid, j] for j in range(12)], reference['replyTopics']) audit.check('secondary reply phrase counts ' + str(index), [phrase_counts[pid, j] for j in range(16)], reference['replyPhrases']) audit.check('secondary post lag counts ' + str(index), [lag_counts[pid, k] for k in range(11)], reference['replyLag']) audit.check('secondary topic lag counts ' + str(index), [[topic_lags[pid, j, k] for k in range(11)] for j in range(12)], reference['topicLag']) audit.check('secondary phrase lag counts ' + str(index), [[phrase_lags[pid, j, k] for k in range(11)] for j in range(16)], reference['phraseLag']) secondary_checks += 8 for name, rows in expected.items(): audit.table(name, tables[name], rows) first_days = Counter() last_days = Counter() cohort_accounts, cohort_replies, activity, last_cohort = Counter(), Counter(), Counter(), Counter() for days in account_days.values(): first, last = min(days), max(days) first_days[first] += 1 last_days[last] += 1 cohort_accounts[first] += 1 cohort_replies[first] += sum(days.values()) last_cohort[first, last] += 1 for active in days: activity[first, active] += 1 audit.table('participation_daily', tables['participation_daily'], [dict(date=day, captured_replies=reply_days[day], active_accounts=len(daily_accounts[day]), first_observed_accounts=first_days[day], returning_accounts=len(daily_accounts[day]) - first_days[day], last_observed_accounts=last_days[day]) for day in sorted(reply_days)]) audit.table('cohorts', tables['cohorts'], [dict(first_day_utc=day, accounts=cohort_accounts[day], captured_replies=cohort_replies[day]) for day in sorted(cohort_accounts)]) audit.table('cohort_activity', tables['cohort_activity'], [dict(first_day_utc=first, active_day_utc=active, active_accounts=count) for (first, active), count in sorted(activity.items())]) audit.table('cohort_last_observed', tables['cohort_last_observed'], [dict(first_day_utc=first, last_day_utc=last, accounts=count) for (first, last), count in sorted(last_cohort.items())]) audit.check('cohort activity sparse cells', len(activity), 1310) audit.check('cohort last-observed sparse cells', len(last_cohort), 1261) print('Checked post, lag, daily participation and all cohort cells', flush=True) feed = json.loads(inputs['cnn-truth-archive.json'].read_text()) feed_unique = {} for row in sorted(feed, key=lambda r: r.get('created_at', '')): at = row.get('created_at', '') if at and at[:10] <= '2026-11-04': feed_unique.setdefault(str(row['id']), row) feed_records, feed_nonempty, feed_topics = Counter(), Counter(), Counter() feed_months, feed_month_nonempty, feed_month_topics = Counter(), Counter(), Counter() for row in feed_unique.values(): text = feed_text(row.get('content', '')) day = dt(row['created_at']).date().isoformat() month = day[:7] feed_records[day] += 1 feed_nonempty[day] += bool(text) feed_months[month] += 1 feed_month_nonempty[month] += bool(text) for j, pattern in enumerate(tp): matched = bool(pattern.search(text)) feed_topics[day, j] += matched feed_month_topics[month, j] += matched audit.check('deduplicated raw feed records', len(feed_unique), 37951) audit.table('feed_daily', tables['feed_daily'], [dict(date=day, records=count, nonempty_records=feed_nonempty[day], **{'topic_' + key: feed_topics[day, j] for j, (key, _, _) in enumerate(topics)}) for day, count in sorted(feed_records.items())]) audit.table('feed_monthly', tables['feed_monthly'], [dict(month=month, records=count, nonempty_records=feed_month_nonempty[month]) for month, count in sorted(feed_months.items())]) audit.table('feed_topics', tables['feed_topics'], [dict(month=month, topic_id=key, matching_records=feed_month_topics[month, j], records=count, share=feed_month_topics[month, j] / count) for month, count in sorted(feed_months.items()) for j, (key, _, _) in enumerate(topics)]) if comparison is not None: for j, reference in enumerate(comparison['topics']): audit.check('secondary feed topic total ' + str(j), sum(feed_month_topics[month, j] for month in feed_months), reference['feedRecords']) audit.check('secondary reply topic total ' + str(j), sum(topic_counts[pid, j] for pid in parent), reference['replyRecords']) secondary_checks += 2 for j, reference in enumerate(comparison['phrases']): audit.check('secondary reply phrase total ' + str(j), sum(phrase_counts[pid, j] for pid in parent), reference['replyRecords']) own = sum(phrase_counts[p['post_id'], j] for p in posts if pp[j].search(source_wording(p['content_clean']))) audit.check('secondary own-thread phrase recurrence ' + str(j), own, reference['ownThreadReplyRecords']) secondary_checks += 2 print('Checked every feed daily/monthly/topic cell from native HTML parser', flush=True) # Scan only planned public data plus human-readable package artifacts. # The independently fixed schemas and value checks already exclude arbitrary # text from every data cell. This separate pass catches raw IDs and source # full-text values without serializing them into diagnostics. leaks = Counter() scanned_cells = 0 for name in COUNTS: for row in csv_rows(out / 'data' / (name + '.csv')): for value in row.values(): scanned_cells += 1 if value in account_ids: leaks['account_id_cells'] += 1 if value in raw_ids and value not in parent: leaks['reply_id_cells'] += 1 if len(value) >= 80 and hashlib.sha256(value.encode()).digest() in long_text_hashes: leaks['full_source_text_cells'] += 1 selected_docs = [p for p in out.rglob('*') if p.is_file() and not any(part in {'.private', '.venv', '__pycache__', '.git', 'data'} for part in p.relative_to(out).parts) and p.suffix in {'.md', '.json', '.txt', '.py', '.yml', '.yaml', '.ipynb'}] secret_pattern = re.compile(r'hf_[A-Za-z0-9]{20,}|(?:sk-proj-|sk_live_)[A-Za-z0-9_-]{15,}|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----') number_pattern = re.compile(r'(?