File size: 31,190 Bytes
b005fa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
#!/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'(?<!\w)' + re.escape(value).replace(r'\ ', r'\s+') + r'(?!\w)'
                       for value in phrases]
    pp = [re.compile(pattern, re.IGNORECASE) for pattern in phrase_patterns]
    expected_schemas = schemas(topics, phrases)
    audit.check('17 planned tables', set(manifest['row_counts']), set(COUNTS))
    audit.check('planned row counts', manifest['row_counts'], COUNTS)
    allowed_data = {name + ext for name in COUNTS for ext in ('.csv', '.parquet')}
    audit.check('data directory exact file allowlist',
                {p.name for p in (out / 'data').iterdir()}, allowed_data)
    audit.check('manifest data file allowlist', set(manifest['files']),
                {'data/' + name for name in allowed_data})
    inputs = {
        'posts.csv': args.posts_csv or source / 'data/raw/posts.csv',
        'comments.csv': args.comments_csv or source / 'data/raw/comments.csv',
        'cnn-truth-archive.json': args.cnn_json or source / 'data/enrichment-raw/cnn-trump-archive.json',
    }
    input_receipts = {}
    for name, path in inputs.items():
        sha = digest(path)
        input_receipts[name] = {'sha256': sha, 'bytes': path.stat().st_size}
        audit.check('pinned source hash ' + name, sha, manifest['inputs'][name]['sha256'])
    tables = {}
    for name, expected_schema in expected_schemas.items():
        path = out / 'data' / (name + '.parquet')
        table = pq.read_table(path)
        audit.check(name + ' exact public column/type schema', table.schema, expected_schema)
        schema_json = [{'name': f.name, 'type': str(f.type), 'nullable': f.nullable}
                       for f in expected_schema]
        audit.check(name + ' manifest schema', manifest['schemas'][name], schema_json)
        audit.check(name + ' dictionary schema', dictionary['tables'][name], schema_json)
        audit.check(name + ' row count', table.num_rows, COUNTS[name])
        audit.check(name + ' null count',
                    sum(column.null_count for column in table.columns),
                    1 if name == 'delay_bands' else 0)
        csv_table = pc.read_csv(out / 'data' / (name + '.csv'),
            convert_options=pc.ConvertOptions(column_types=expected_schema,
                true_values=['true'], false_values=['false']))
        audit.check(name + ' CSV/Parquet exact typed cell parity', table.equals(csv_table))
        audit.cells += table.num_rows * table.num_columns
        for ext in ('.csv', '.parquet'):
            file = out / 'data' / (name + ext)
            receipt = manifest['files']['data/' + file.name]
            audit.check(file.name + ' byte count', file.stat().st_size, receipt['bytes'])
            audit.check(file.name + ' SHA256', digest(file), receipt['sha256'])
        if name != 'reply_features':
            tables[name] = table
        print('Checked format/schema: ' + name, flush=True)

    audit.table('topics', tables['topics'], [dict(topic_id=key, label=label, pattern=pattern)
                for key, label, pattern in topics])
    audit.table('phrases', tables['phrases'], [dict(phrase_id=value.replace(' ', '_'),
                phrase=value, pattern=phrase_patterns[j]) for j, value in enumerate(phrases)])
    audit.table('delay_bands', tables['delay_bands'], [dict(delay_band=j,
                lower_hours_inclusive=EDGES[j], upper_hours_exclusive=EDGES[j + 1])
                for j in range(11)])

    posts = sorted(csv_rows(inputs['posts.csv']), key=lambda p: (p['created_at'], p['post_id']))
    parent = {p['post_id']: p for p in posts}
    audit.check('raw unique selected posts', len(parent), 97)
    # Independent counters keyed by captured observations and transient IDs.
    totals = Counter()
    text_counts, like_counts = Counter(), Counter()
    topic_counts, phrase_counts, lag_counts = Counter(), Counter(), Counter()
    topic_lags, phrase_lags = Counter(), Counter()
    account_days = defaultdict(Counter)
    daily_accounts = defaultdict(set)
    reply_days = Counter()
    raw_ids, account_ids = set(), set()
    long_text_hashes = set()
    errors = Counter()
    raw_count = duplicate_count = retained = 0
    first_reply = last_reply = None
    feature_iterator = (row for batch in pq.ParquetFile(out / 'data/reply_features.parquet')
                        .iter_batches(batch_size=10000) for row in batch.to_pylist())
    feature_columns = expected_schemas['reply_features'].names
    for raw in csv_rows(inputs['comments.csv']):
        raw_count += 1
        key = raw['comment_id']
        if key in raw_ids:
            duplicate_count += 1
            continue
        raw_ids.add(key)
        pid = raw['parent_post_id']
        if pid not in parent:
            errors['invalid_raw_parent'] += 1
            continue
        at = dt(raw['created_at'])
        # Use independent datetime conversion, then cast only for frozen bins.
        elapsed = (at.timestamp() - dt(parent[pid]['created_at']).timestamp()) / 3600
        delay = struct.unpack('f', struct.pack('f', elapsed))[0]
        band = bisect_right(EDGES[1:-1], delay)
        if elapsed < 0:
            errors['negative_raw_delay'] += 1
        text = html.unescape(raw['content_clean']).strip()
        if len(text) >= 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'(?<!\d)\d{12,25}(?!\d)')
    for path in selected_docs:
        value = path.read_text()
        if secret_pattern.search(value):
            leaks['credential_like_public_files'] += 1
        if any(token in account_ids or (token in raw_ids and token not in parent)
               for token in number_pattern.findall(value)):
            leaks['raw_identifier_public_files'] += 1
        if path.name == 'alias-salt.bin':
            leaks['salt_files'] += 1
    for label in ['account_id_cells', 'reply_id_cells', 'full_source_text_cells',
                  'credential_like_public_files', 'raw_identifier_public_files', 'salt_files']:
        audit.check('public release scan: ' + label, leaks[label], 0)
    current_manifest = json.loads((out / 'manifest.json').read_text())
    summary_expected = dict(raw_reply_rows=raw_count, duplicates_removed=duplicate_count,
        captured_replies=retained, source_posts=len(posts), accounts_in_aggregates=len(account_days),
        accounts_with_multiple_replies=recurrent, reply_start_utc=first_reply,
        reply_end_utc=last_reply, feed_records=len(feed_unique))
    for key, value in summary_expected.items():
        audit.check('manifest computed summary ' + key, current_manifest['summary'][key], value)
    audit.check('data hashes remained stable during audit', current_manifest['files'], manifest['files'])
    # Source-backed zeros are legitimate. Exact source reconciliation above,
    # rather than a zero-frequency heuristic, detects fabricated/filler rows.
    synthetic = {
        'method': 'Every exported reply value and all aggregate cells reconciled to retained raw sources; no random generation or interpolation used.',
        'source_backed_zero_post_topic_lag_cells': sum(row['matching_replies'] == 0 for row in expected['post_topic_delays']),
        'source_backed_zero_post_phrase_lag_cells': sum(row['matching_replies'] == 0 for row in expected['post_phrase_delays']),
        'empty_text_reply_records': retained - sum(text_counts.values()),
        'no_fabricated_rows_detected': audit.failed_checks == 0,
    }
    report = {
        'status': 'passed' if audit.failed_checks == 0 else 'failed',
        'checked_at_utc': datetime.now(timezone.utc).isoformat(),
        'validator': 'tests/validate_export.py', 'validator_sha256': digest(Path(__file__)),
        'independence': 'No dataset-builder imports or execution; first-ID raw CSV reconciliation, AST-read packaged declared patterns, native HTML parser, independent counters and UTC timestamps.',
        'checks': audit.checks, 'failed_checks': audit.failed_checks,
        'compared_cells': audit.cells, 'failures': audit.failures,
        'row_counts': COUNTS, 'source_inputs': input_receipts,
        'computed_summary': summary_expected,
        'source_comparison_secondary': {
            'status': 'run' if comparison is not None else 'not_run',
            'checks': secondary_checks,
            'description': ('All 97 frozen comparison posts, topic/phrase/lag distributions and totals checked after primary raw-source verification.'
                if comparison is not None else 'Not run; optional frozen visualization comparison was not provided. All primary raw-source checks still ran.'),
        },
        'public_scan': {'data_cells_scanned': scanned_cells,
            'human_readable_files_scanned': len(selected_docs),
            'leak_counts': dict(leaks),
            'scope': '17 allowlisted CSV/Parquet pairs and readable public package artifacts; excludes .private, .venv, .git and __pycache__. Exact schemas/value checks prevent undeclared text fields. Not an anonymity guarantee.'},
        'synthetic_data_scan': synthetic,
        'duration_seconds': round(time.monotonic() - started, 2),
        'limitations': ['No claim that publisher capture represents all replies or people.',
            'No inference of supporter status, political stance, emotion or follow/unfollow events.',
            'Platform upload/download checks are separate from this local validation.'],
    }
    report_path.parent.mkdir(parents=True, exist_ok=True)
    report_path.write_text(json.dumps(report, indent=2, allow_nan=False) + '\n')
    print(json.dumps({key: report[key] for key in ['status', 'checks', 'failed_checks', 'compared_cells', 'duration_seconds']}))
    if audit.failures:
        print(json.dumps({'failures': audit.failures}))
    return 0 if audit.failed_checks == 0 else 1


if __name__ == '__main__':
    sys.exit(main())