verify-industry-policy-runtime.py 3.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """Run the frozen release in a real interpreter without changing installed runtimes."""
  2. import argparse
  3. from datetime import datetime, timezone
  4. import hashlib
  5. import json
  6. from pathlib import Path
  7. import subprocess
  8. def main():
  9. parser = argparse.ArgumentParser(description=__doc__)
  10. parser.add_argument('--python', type=Path, required=True)
  11. parser.add_argument('--package', type=Path, required=True)
  12. parser.add_argument('--snapshot', type=Path, required=True)
  13. parser.add_argument('--out', type=Path, required=True)
  14. args = parser.parse_args()
  15. package, snapshot = args.package.resolve(), args.snapshot.resolve()
  16. generation = json.loads(snapshot.read_bytes())['generation']
  17. directory = args.out.resolve()
  18. directory.mkdir(parents=True, exist_ok=True)
  19. report = {'ok': False, 'checkedAt': datetime.now(timezone.utc).isoformat(),
  20. 'generation': generation, 'productionVerified': False, 'productionWrites': 0, 'paidCalls': 0}
  21. def run(name, source):
  22. result = subprocess.run([str(args.python.resolve()), '-B', '-X', 'utf8', '-c', source],
  23. cwd=package, capture_output=True, encoding='utf-8', timeout=180)
  24. (directory / (name + '.stdout.txt')).write_text(result.stdout, 'utf-8')
  25. (directory / (name + '.stderr.txt')).write_text(result.stderr, 'utf-8')
  26. if result.returncode:
  27. raise RuntimeError(name + ' failed; inspect saved stderr')
  28. return result.stdout
  29. prefix = 'import sys;sys.path.insert(0,' + repr(str(package / 'server/voc-library')) + ');'
  30. try:
  31. report['runtime'] = json.loads(run('interpreter', 'import sys,platform,sqlite3,json;print(json.dumps({"python":platform.python_version(),"platform":platform.platform(),"sqlite":sqlite3.sqlite_version,"nativePython39Verified":sys.version_info[:2]==(3,9)}))'))
  32. tests = prefix + '''import unittest,json
  33. suite=unittest.defaultTestLoader.discover('server/voc-library',pattern='test_*.py')
  34. result=unittest.TextTestRunner(verbosity=2).run(suite)
  35. print(json.dumps({'testsRun':result.testsRun,'failures':len(result.failures),'errors':len(result.errors),'ok':result.wasSuccessful()}))
  36. sys.exit(0 if result.wasSuccessful() else 1)
  37. '''
  38. report['unitTests'] = json.loads(run('python-tests', tests))
  39. argv = ['verify-industry-install.py', '--snapshot', str(snapshot), '--monitoring-store',
  40. str(package / 'data/monitoring-registry'), '--expected-generation', generation]
  41. report['preflight'] = json.loads(run('preflight', prefix + 'import runpy;sys.argv=' + repr(argv) + ';runpy.run_path("scripts/verify-industry-install.py",run_name="__main__")'))
  42. report['policyProbe'] = json.loads(run('policy-probe', prefix + 'import json;from industry_monitor import run;r=run(' + repr({'snapshot': str(snapshot), 'monitoringStore': str(package/'data/monitoring-registry')}) + ',' + repr({'op': 'policies', 'generation': generation, 'policyQuery': {'application': 'sodium-claims', 'asOf': '2026-11-07', 'perServingMg': '2414', 'servingGrams': '96'}}) + ');a=r["applications"];assert a["calculation"]["mgPer100g"]=="2514.58";assert a["calculation"]["productVerdict"] is None;assert a["officialChecks"]["verifiedDocuments"]==9;print(json.dumps({"workflows":len(a["workflows"]),"officialMetadata":a["officialChecks"]["verifiedDocuments"],"calculation":a["calculation"]},ensure_ascii=False))'))
  43. report['snapshotSha256'] = hashlib.sha256(snapshot.read_bytes()).hexdigest()
  44. report['ok'] = report['unitTests']['ok'] and report['preflight']['ok']
  45. finally:
  46. (directory/'verification.json').write_text(json.dumps(report, ensure_ascii=False, indent=2)+'\n', 'utf-8')
  47. print(json.dumps(report, ensure_ascii=False))
  48. if __name__ == '__main__':
  49. main()