#!/usr/bin/env python3 """Independently check the portable tables against pinned financial packets.""" import argparse, gzip, hashlib, io, json, re, sys, zipfile from pathlib import Path, PurePosixPath sys.dont_write_bytecode=True import replay def read(path): return json.loads(path.read_bytes()) def sha(raw): return hashlib.sha256(raw).hexdigest() def check(ok, why): if not ok: raise ValueError(why) def jsonl(path): with gzip.open(path,'rt',encoding='utf-8') as f: yield from (json.loads(line) for line in f) def safe_name(name): p=PurePosixPath(name) check(not p.is_absolute() and '..' not in p.parts and '\\' not in name, 'Unsafe distribution path') roots={'README.md','catalog.json','releases.jsonl','releases.parquet','distribution.json','verify.py','replay.py','packet.py'} allowed=name in roots or re.fullmatch(r'packets/[a-f0-9]{64}\.json',name) or re.fullmatch(r'releases/[a-f0-9]{64}/(facts\.jsonl\.gz|companies\.jsonl\.gz|facts\.parquet|companies\.parquet|manifest\.json)',name) if name.startswith('upstream/releases/'): parts=p.parts allowed=len(parts)==4 and re.fullmatch(r'[a-f0-9]{64}',parts[2]) and parts[3] in replay.FILES|{'release.json','checksums.sha256','release-kit.zip'} check(bool(allowed),'Unapproved distribution file') def public_identity(raw): check(not re.search(rb'/(?:Users|home/runner|private/var/folders|var/folders)/',raw),'Personal machine path in publication') def check_parquet(path, records): import pyarrow.parquet as pq table=pq.read_table(path) check(table.num_rows==len(records), 'Parquet row count differs') check(set(table.column_names)==set(records[0]), 'Parquet columns differ') offset=0 for batch in table.to_batches(max_chunksize=10000): actual=batch.to_pylist() check(actual==records[offset:offset+len(actual)], 'Parquet rows differ from canonical JSON') offset+=len(actual) def verify(root, expected=None): root=Path(root); raw=(root/'distribution.json').read_bytes(); manifest=json.loads(raw) if expected: check(sha(raw)==expected,'Distribution manifest hash mismatch') check(manifest['publisher']=='AhaSignals' and manifest['version']=='1.0.0','Unknown distribution') for name,digest in manifest['files'].items(): safe_name(name); p=root/name raw=p.read_bytes() check(not p.is_symlink() and sha(raw)==digest,'Distribution file hash mismatch: '+name) public_identity(gzip.decompress(raw) if name.endswith('.gz') else raw) actual={str(p.relative_to(root)) for p in root.rglob('*') if p.is_file() and '.git' not in p.relative_to(root).parts and '.cache' not in p.relative_to(root).parts and p.name!='.gitattributes'} check(actual==set(manifest['files'])|{'distribution.json'},'Unexpected or missing distribution files') catalog=read(root/'catalog.json'); entries=catalog['releases']; check(bool(entries),'Empty catalog') replay.select(catalog,entries[-1]['frozenAt']) check(manifest['latestReleaseSha256']==entries[-1]['sha256'],'Wrong latest release') check((root/'releases.jsonl').read_bytes()==b''.join(replay.encode(e) for e in entries),'Release table mismatch') check_parquet(root/'releases.parquet',entries) total=0; previous=None for e in entries: s=e['sha256']; folder=root/'upstream/releases'/s r,index,c=replay.verify(folder,s) check(r['previousReleaseSha256']==previous,'Broken release chain'); previous=s check(e['frozenAt']==r['frozenAt'] and e['sourceAsOf']==r['sourceAsOf'] and e['sourceIndexSha256']==r['sourceIndexSha256'],'Catalog clock or source mismatch') kit=(folder/'release-kit.zip').read_bytes() check(sha(kit)==e['kitSha256'] and len(kit)==e['kitBytes'],'ZIP hash mismatch') with zipfile.ZipFile(io.BytesIO(kit)) as z: check(len(z.namelist())==len(set(z.namelist())) and set(z.namelist())==replay.FILES|{'release.json','checksums.sha256'},'Unexpected ZIP members') for name in z.namelist(): check(z.read(name)==(folder/name).read_bytes(),'ZIP member differs') public_identity(z.read(name)) table=root/'releases'/s; tm=read(table/'manifest.json') check(tm['releaseSha256']==s and tm['distributionVersion']=='1.0.0','Wrong table release') for name in ['facts.jsonl.gz','companies.jsonl.gz','facts.parquet','companies.parquet']: check(tm['tables'][name]==sha((table/name).read_bytes()),'Table hash mismatch') companies=list(jsonl(table/'companies.jsonl.gz')) check(len(companies)==len(index['companies'])==e['companyCount']==tm['companyCount'],'Company count mismatch') expected_facts={}; expected_companies={}; coverage={x['cik']:x for x in c['companies']} for x in index['companies']: ps=x['sha256']; p=replay.packet.verify((root/'packets'/(ps+'.json')).read_bytes(),ps) check(p['cik']==x['cik'] and p['recordedAt']==x['updatedAt'],'Issuer or packet mismatch') check(replay.packet.instant(p['recordedAt'])<=replay.packet.instant(r['frozenAt']),'Future packet') common={'release_sha256':s,'release_frozen_at':r['frozenAt'],'cik':x['cik'],'company_name':p['name'],'packet_sha256':ps,'packet_recorded_at':p['recordedAt'],'source_observed_at':p['factsSource']['observedAt'],'source_sha256':p['factsSource']['sha256'],'company_url':'https://ahasignals.com'+x['href']} ids=set(p['currentIds']); cv=coverage[x['cik']] expected_companies[x['cik']]={**common,'tickers_json':json.dumps(p['tickers']),'sector':x['sector'],'screen_status':x['status'],'collection_error_json':json.dumps(x['collectionError']),'last_checked_at':x['lastCheckedAt'],'selected_fact_count':len(ids),'stale_at_freeze':cv['staleAtFreeze'],'source_age_days_at_freeze':cv['financialSourceAgeDays'],'guidance_status':p['guidanceStatus'],'review_status':p['reviewStatus']} for f in p['facts']: if f['id'] in ids: expected_facts[(x['cik'],f['id'])]=(common,f) check(len({x['cik'] for x in companies})==len(companies),'Duplicate company') for x in companies: check(x==expected_companies[x['cik']],'Company table differs from source') seen=set() mapping={'fact_id':'id','concept':'concept','label':'label','unit':'unit','period_start':'start','period_end':'end','filed_date':'filedDate','first_observed_at':'firstObservedAt','first_source_sha256':'firstSourceSha256','accession':'accession','form':'form','source_url':'sourceUrl'} for row in jsonl(table/'facts.jsonl.gz'): key=(row['cik'],row['fact_id']); check(key not in seen and key in expected_facts,'Duplicate or unselected fact');seen.add(key) common,f=expected_facts[key] expected_row={**common,**{column:f[field] for column,field in mapping.items()},'value_json':json.dumps(f['value'],allow_nan=False,separators=(',',':'))} check(row==expected_row,'Fact table differs from source') check(len(seen)==len(expected_facts)==e['currentFactCount']==c['currentFactCount']==tm['selectedFactCount'],'Selected fact count mismatch') check_parquet(table/'facts.parquet',list(jsonl(table/'facts.jsonl.gz'))) check_parquet(table/'companies.parquet',companies) total+=len(seen) return {'verifiedReleases':len(entries),'selectedRowsAcrossReleases':total,'latestReleaseSha256':entries[-1]['sha256']} if __name__=='__main__': p=argparse.ArgumentParser(description=__doc__);p.add_argument('--root',type=Path,default=Path('.'));p.add_argument('--manifest-sha256');a=p.parse_args() try: print(json.dumps(verify(a.root,a.manifest_sha256))) except (ValueError,KeyError,FileNotFoundError) as e: p.exit(2,'Verification failed: '+str(e)+'\n')