"""Validate schema, relationships, numerical results, reproducibility and SHA-256.""" import argparse import hashlib import json from pathlib import Path from jsonschema import Draft202012Validator from generate import BASE, IDS, SNAPSHOT, build, classify, score def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest() def inventory(): # Reports are derived outputs and cannot recursively hash themselves. return sorted(p for p in BASE.rglob('*') if p.is_file() and not any(x in p.relative_to(BASE).parts for x in ['reports','__pycache__','.venv','.cache']) and p.name not in ['SHA256SUMS','VALIDATION.md']) def main(): parser = argparse.ArgumentParser() parser.add_argument('--write-hashes',action='store_true',help='Regenerate manifest only after reviewing intentional changes') args = parser.parse_args() schema = json.loads((BASE/'schema.json').read_text(encoding='utf-8')) expected = build() counts = {} for name, generated in expected.items(): validator = Draft202012Validator(schema['$defs'][name]) path = BASE/'data'/f'{name}.jsonl' assert path.read_bytes().endswith(b'\n') rows = [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()] for row in rows: validator.validate(row) assert len({r['id'] for r in rows}) == len(rows), name assert rows == generated, f'{name}: stale or non-reproducible data' counts[name] = len(rows) q = expected['questions'] assert len({x['text'] for x in q}) == 70 assert len(q) == 91 for mode, n, rev, minimum, version in [('quick',3,1,2,'quick-2'),('full',10,3,8,'full-1')]: items = [x for x in q if x['mode']==mode] assert [x['position'] for x in items] == list(range(1,len(items)+1)) for sid in IDS: group = [x for x in items if x['dimension_id']==sid] assert len(group)==n and sum(x['reverse'] for x in group)==rev rows = [x for x in expected['scoring_cases'] if x['mode']==mode] fingerprints = [] for row in rows: assert row['version']==version and row['minimum_per_dimension']==minimum answer = {a['question_id']:a['raw'] for a in row['answers']} assert len(answer)==len(row['answers']) assert set(answer)<=set(x['question_id'] for x in items) assert row['addressed_count']==len(answer) assert [s['id'] for s in row['scores']]==IDS assert row['result_eligible'] == (row['coverage_complete'] and (mode=='quick' or len(answer)==70)) assert row['sensitivity']['changed']<=row['sensitivity']['checked'] for r in row['possible_completed_ranges']: assert 0<=r['low']<=r['high']<=100 fingerprints.append(json.dumps(row['answers'],sort_keys=True)) assert len(set(fingerprints))==len(rows), f'{mode}: duplicate answer fixture' midpoint = next(x for x in rows if x['id']==f'{mode}:adjusted-uniform-2') assert all(s['value']==50 and s['count']==n for s in midpoint['scores']) assert midpoint['computed_profile']['title']=='An even constellation' assert midpoint['computed_character']['title']=='A glorious mix' assert midpoint['sensitivity']=={'checked':len(items)*2,'changed':0} skipped = next(x for x in rows if x['id']==f'{mode}:minimum-with-skips') assert skipped['result_eligible'] and all(s['count']==minimum for s in skipped['scores']) omitted = next(x for x in rows if x['id']==f'{mode}:unaddressed') assert omitted['coverage_complete'] and omitted['result_eligible']==(mode=='quick') # Hand-specified branch expectations independently guard strict/inclusive boundaries. boundary_expectations = { 'below-25':'A quieter side','at-25':'An even constellation', 'below-75':'An even constellation','at-75':'Many sides, strongly felt', 'spread-at-12-5':'An even constellation','spread-above-12-5':'Pride', 'top-below-50':'No strong leading side','top-at-50':'Pride', 'tie-at-6-25':'Pride + Envy','tie-outside-6-25':'Pride', 'stable-source-order':'Envy + Wrath','three-leaders':'A little more complex', 'quiet-before-even':'A quieter side','broad-before-even':'Many sides, strongly felt'} for row in expected['classification_cases']: assert row['expected_profile']['title']==boundary_expectations[row['id'].split(':')[1]] quick = {x['question_id']:x for x in q if x['mode']=='quick'} for x in (x for x in q if x['mode']=='full' and x['source_item_id'] in quick): for field in ['text','reverse','theme','dimension_id']: assert x[field]==quick[x['source_item_id']][field] manifest = BASE/'SHA256SUMS' if args.write_hashes: manifest.write_text(''.join(f'{sha(p)} {p.relative_to(BASE).as_posix()}\n' for p in inventory()),encoding='utf-8',newline='\n') entries = [line.split(' ',1) for line in manifest.read_text(encoding='utf-8').splitlines()] assert {name for _,name in entries}=={p.relative_to(BASE).as_posix() for p in inventory()}, 'Manifest file coverage mismatch' for digest, name in entries: assert sha(BASE/name)==digest, f'Hash mismatch: {name}' report = {'status':'PASS','schema_version':SNAPSHOT['schema_version'],'snapshot_date':SNAPSHOT['snapshot_date'], 'row_counts':counts,'total_rows':sum(counts.values()),'distinct_question_texts':70, 'hash_files_checked':len(entries),'manifest_exclusions':['reports/','__pycache__/','.venv/','.cache/','SHA256SUMS','VALIDATION.md'], 'checks':['JSON Schema types and required keys','unique IDs','no duplicate attempt inputs within modes', 'mode/version correspondence','ordered question positions','question reuse foreign keys', 'reverse counts','answer domain and joins','independent hand-specified boundary expectations', 'coverage versus addressed eligibility','ranges and sensitivity','deterministic regeneration','SHA-256 coverage and contents'], 'publication_status':'local_only','rights_status':'no_additional_license_granted_pending_owner_review'} (BASE/'reports').mkdir(exist_ok=True) (BASE/'reports/validation.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf-8',newline='\n') print(json.dumps(report,indent=2)) if __name__ == '__main__': main()