]> dreyeck.freedombox.rocks Git - topic-maps.git/blob - scripts/validate-slice-22m.py
feat(tmdm): readers for the TMDM 7.2/7.3 relationships; tests for both default name...
[topic-maps.git] / scripts / validate-slice-22m.py
1 #!/usr/bin/env python3
2 """Slice 22M offline execution and acceptance audit using the existing collector.
3 Use an unused --output outside the repository; --audit-only rechecks saved runs.
4 """
5 import argparse,datetime,hashlib,importlib.util,json,re,subprocess,sys
6 from pathlib import Path
7 sys.dont_write_bytecode=True
8 ROOT=Path(__file__).resolve().parents[1]
9 D=ROOT/'reports/slice-22m';PRIOR=ROOT/'reports/slice-22l/after'
10 BASE='27bf0dc4e2ab1e5afefcc616df8afdd73f815607'
11 ALLOWED={'src/xtm/reader.lisp','topic-maps.asd','tests/xtm-identity.lisp','tests/xtm-name-scopes.lisp','tests/xtm-associations.lisp','tests/xtm-occurrence-reification.lisp','tests/ctm-xtm-equivalence.lisp'}
12 SOURCES=ALLOWED|{'tests/xtm-association-reifier-native.lisp','tests/xtm-association-reification.lisp','reports/slice-22m/api-preflight.lisp','scripts/validate-slice-22d.py','reports/slice-22d/failure-controls.lisp'}
13 def read(p):return json.loads(p.read_text())
14 def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
15 def save(p,x):p.write_text(json.dumps(x,indent=2,ensure_ascii=False)+'\n')
16 def git(*args):return subprocess.check_output(['git',*args],cwd=ROOT,text=True).strip()
17 def diff(a,b,path=''):
18 if a==b:return []
19 if isinstance(a,dict) and isinstance(b,dict):return [d for k in sorted(a.keys()|b.keys()) for d in diff(a.get(k),b.get(k),path+'/'+k)]
20 if isinstance(a,list) and isinstance(b,list) and len(a)==len(b):return [d for i,(x,y) in enumerate(zip(a,b)) for d in diff(x,y,path+'/'+str(i))]
21 return [{'path':path,'before':a,'after':b}]
22 def audit(out):
23 initial=read(D/'initial-state.json');assert initial['baseCommit']==BASE and initial['initialIndexAndWorktreeClean']
24 assert set(git('diff','--name-only',BASE).splitlines())&set(initial['trackedFileSHA256'])<=ALLOWED
25 protected={p:h for p,h in initial['trackedFileSHA256'].items() if p not in ALLOWED}
26 assert protected=={p:sha(ROOT/p) for p in protected}
27 run=read(out/'runs.json');assert len(run['runs'])==119
28 assert all(x['exitCode']==x['expectedExitCode'] and x['network']==x['repositoryWrites']=='denied' and sha(out/(x['label']+'.log'))==x['logSHA256'] for x in run['runs'])
29 assert run['executionSourcesSHA256']=={p:sha(ROOT/p) for p in run['executionSourcesSHA256']}
30 assert run['rawReportSHA256']=={p:sha(out/p) for p in run['rawReportSHA256']}
31 old=read(PRIOR/'xtm.json');new=read(out/'xtm.json');before={x['id']:x for x in old['cases']};after={x['id']:x for x in new['cases']}
32 inputs={x['id']:x for x in read(D/'originals-before.json')};targets=set(inputs)
33 assert old['statuses']=={'pass':110,'fail':0,'unsupported':0,'not-run':0}
34 assert new['statuses']=={'pass':115,'fail':0,'unsupported':0,'not-run':0} and new['otherCorpusInputs']=={'positiveUnexecuted':8,'negativeUnregisteredUnexecuted':1}
35 assert old['cases']==new['cases'][:len(old['cases'])] and set(after)-set(before)==targets
36 assert len(after)==len(new['cases']) and all(after[id]['status']=='pass' for id in targets)
37 assert [c for c in new['checks'] if c in set(old['checks'])]==old['checks']
38 labels=re.findall(r'^XTM-CHECK-PASS (.+)$',(out/'xtm.log').read_text(),re.M)
39 assert labels==new['checks'] and len(labels)==len(set(labels))==3587
40 permitted={'scope','statuses','otherCorpusInputs','checks','cases','scopeControls','mapReifierControls','associationControls','occurrenceReifierControls','mergemapControls'}
41 for key in old:
42 if key not in permitted:assert old[key]==new[key],key
43 retargets=[]
44 for key,count in {'scopeControls':1,'mapReifierControls':1,'associationControls':2,'occurrenceReifierControls':1}.items():
45 assert len(old[key])==len(new[key]);changed=[(a,b) for a,b in zip(old[key],new[key]) if a!=b];assert len(changed)==count,(key,changed)
46 for a,b in changed:
47 assert a['label']==b['label'] and a['condition']['class']==b['condition']['class']=='XTM-UNSUPPORTED'
48 assert a['condition']['code']==b['condition']['code']=='unsupported-construct'
49 assert a['condition']['detail']=='XTM association reification is not implemented in this subset.'
50 assert b['condition']['detail']=='XTM role reification is not implemented in this subset.'
51 assert '<role reifier=' in b['sourceText']
52 assert b['sourceText']==a['sourceText'] or b['sourceText']==a['sourceText'].replace('<role>',"<role reifier='#excluded-role'>",1)
53 for k in ['sourceKey','documentIRI','line']:assert a['condition'][k]==b['condition'][k]
54 retargets.append({'reportKey':key,'label':a['label'],'before':a,'after':b,'differences':diff(a,b)})
55 assert new['mergemapControls'][1:]==old['mergemapControls']
56 imported=new['mergemapControls'][0];assert imported['label']=='Association-Reification-import' and imported['sourceMapsPreserved'] and imported['qualifiedParserCalls']==2
57 assert len(imported['resolverCalls'])==1 and imported['model']['canonicalNativeReferencesEQ']
58 for fixture in read(D/'retargetings.json'):
59 if 'afterSource' in fixture:assert fixture['afterSource'] in (ROOT/fixture['file']).read_text()
60 save(out/'retargeted-control-observations.json',retargets)
61 originals=[];(out/'actual').mkdir(exist_ok=True)
62 assert {x['id'] for x in new['associationReifierOriginals']}==targets
63 for row in new['associationReifierOriginals']:
64 source=inputs[row['id']];raw=bytes.fromhex(row['sourceHex'])
65 assert raw==(ROOT/'vendor/cxtm'/row['id']).read_bytes() and hashlib.sha256(raw).hexdigest()==source['sourceSHA256']
66 assert row['status']=='pass' and row['condition'] is None and row['firstDifferentByte'] is None
67 assert row['originalOctetsEQ'] and row['qualifiedParserCalls']==1 and row['oldHandlesCanonicalAndLive']
68 assert row['model']['canonicalAssociationReifierInverseEQ']
69 actual=row['actualCXTM'].encode();expected=(ROOT/'vendor/cxtm/xtm2/baseline'/(Path(row['id']).name+'.cxtm')).read_bytes()
70 assert actual==expected==row['expectedCXTM'].encode() and len(actual)==row['actualBytes']==row['expectedBytes']==source['baselineBytes']
71 assert hashlib.sha256(expected).hexdigest()==source['baselineSHA256'] and after[row['id']]['actualOutcome']=='cxtm-match'
72 p=out/'actual'/(Path(row['id']).name+'.cxtm');p.write_bytes(actual)
73 originals.append(dict(row,actualSHA256=sha(p),completeByteExact=True,sourceSHA256=source['sourceSHA256'],baselineSHA256=source['baselineSHA256']))
74 save(out/'original-contracts.json',originals)
75 # All original reader diagnoses, including a later reached excluded Role boundary.
76 oldd={x['id']:x for x in read(PRIOR/'after-diagnostics.json')};newd={x['id']:x for x in read(out/'after-diagnostics.json')}
77 inventory=sorted('xtm2/'+sub+'/'+p.name for sub in ['in','invalid'] for p in (ROOT/'vendor/cxtm/xtm2'/sub).glob('*.xtm'))
78 assert len(inventory)==124 and set(inventory)==set(oldd)==set(newd)
79 changes=[];matrix=[];excluded='xtm2/invalid/role-duplicate-reified.xtm'
80 for id in inventory:
81 a,b=oldd[id],newd[id];ds=diff(a,b)
82 if ds:
83 assert id in targets,id
84 if id in targets:assert b['byteExact'] and b['condition'] is None
85 else:
86 assert a['condition']['class']==b['condition']['class']=='XTM-UNSUPPORTED' and a['condition']['code']==b['condition']['code']=='unsupported-construct'
87 assert 'association reification' in a['condition']['detail'] and 'role reification' in b['condition']['detail']
88 changes.append({'id':id,'reason':'new Association Reification original result' if id in targets else 'Excluded Role-Reification reached after supported Association; remains NOT-RUN','differences':ds})
89 elif id in targets:raise AssertionError(id)
90 bs=before.get(id,{}).get('status','not-run');ns=after.get(id,{}).get('status','not-run');assert (bs!=ns)==(id in targets)
91 matrix.append({'id':id,'before':bs,'after':ns,'registeredStatusChanged':bs!=ns,'diagnosisChanged':bool(ds),'beforeDiagnosis':a,'afterDiagnosis':b})
92 assert all(newd[id]==oldd[id] for id in before)
93 assert targets=={x['id'] for x in changes} and excluded not in after and oldd[excluded]==newd[excluded]
94 save(out/'diagnostic-changes.json',{'originalDiagnoses':124,'changed':len(changes),'unchanged':124-len(changes),'changes':changes})
95 save(out/'all-124-original-statuses.json',{'cases':matrix,'registeredChanges':5,'previous110OriginalPASSUnchanged':True})
96 faults=[]
97 for x in run['runs']:
98 if '-control-' not in x['label']:continue
99 a=read(PRIOR/(x['label']+'.json'));b=read(out/(x['label']+'.json'));ds=diff(a,b)
100 assert a['cases']==b['cases'] and a['statuses']==b['statuses'] and a['checks']==b['checks'] and x['exitCode']==1
101 aa=dict(a);bb=dict(b)
102 for k in ['scope','associationReifierNative','associationReifierOriginals','associationReifierControls']:aa.pop(k,None);bb.pop(k,None)
103 for rt in retargets:
104 key=rt['reportKey'];aa[key]=[rt['after'] if row==rt['before'] else row for row in aa[key]]
105 assert aa==bb,(x['label'],diff(aa,bb))
106 assert not b['associationReifierNative'] and not b['associationReifierOriginals'] and not b['associationReifierControls']
107 faults.append({'label':x['label'],'expectedASDFFailureObserved':True,'exitCode':1,'caseRecordsOutcomesAndChecksIdentical':True,'faultCountedAsOriginalPASS':False,'reportDifferences':ds})
108 assert len(faults)==113
109 save(out/'failure-controls.json',{'retained':113,'new':0,'controls':faults,'allTargetCasesAndChecksUnchanged':True,'failureDriverUnchanged':True})
110 retained=[]
111 for p in sorted((PRIOR/'retained').glob('*.json')):
112 rel=p.relative_to(PRIOR)
113 if p.name.endswith('.equivalence.json'):continue
114 assert p.read_bytes()==(out/rel).read_bytes(),str(rel)
115 retained.append({'report':str(rel),'sha256':sha(p),'byteIdentical':True})
116 for name in ['ctm.validation.json','ctm.cxtm.json','ctm.encoding.json']:
117 assert (out/name).read_bytes()==(PRIOR/name).read_bytes();retained.append({'report':name,'sha256':sha(out/name),'byteIdentical':True})
118 assert len(retained)==48;save(out/'retained-reports.json',retained)
119 eqpath=next((out/'retained').glob('*.equivalence.json'));eqa=read(PRIOR/eqpath.relative_to(out));eqb=read(eqpath)
120 assert eqa['checks']==eqb['checks'] and len(eqb['checks'])==515
121 oldpairs={x['id']:x for x in eqa['pairs']};pairs={x['id']:x for x in eqb['pairs']};gap='association-role-scope-reifiers'
122 assert oldpairs.keys()==pairs.keys() and all(oldpairs[id]==pairs[id] for id in oldpairs if id!=gap)
123 a,b=oldpairs[gap],pairs[gap];ds=diff(a,b)
124 assert b['kind']=='reader-capability-gap-not-equivalence-PASS' and not b['successfulReaderPair']
125 assert b['missingCapability']=='XTM role deserialization' and b['xtmCondition']['class']=='XTM-UNSUPPORTED'
126 assert b['xtmCondition']['code']=='unsupported-construct' and 'role reification' in b['xtmCondition']['message']
127 assert all(x['path'].startswith('/xtmCondition/') or x['path']=='/missingCapability' for x in ds)
128 assert sum(x['kind']=='direct-reader-equivalence-pair' for x in eqb['pairs'])==29
129 save(out/'equivalence-boundary.json',{'all29PairsAnd3ContrastsUnchanged':True,'remainingGapIsRoleReification':True,'checks':515,'differences':ds,'before':a,'after':b})
130 # Native gate really executed on the original Reader, before its edit.
131 gate=read(D/'native-before-execution.json');native=read(D/'native-before/report.json')
132 assert gate['exitCode']==0 and gate['beforeAnyProductionChange'] and gate['network']==gate['repositoryWrites']=='denied'
133 assert gate['executionSourceSHA256']['src/xtm/reader.lisp']==initial['trackedFileSHA256']['src/xtm/reader.lisp']
134 for p,h in gate['executionSourceSHA256'].items():
135 if p!='src/xtm/reader.lisp':assert sha(ROOT/p)==h
136 assert sha(D/'native-before/run.log')==gate['logSHA256'] and sha(D/'native-before/report.json')==gate['reportSHA256']
137 assert len(native['checks'])==12 and not native['ReaderInvoked'] and native['originalRegistrationsAdded']==0
138 assert native['observations']==new['associationReifierNative'] and all(c in new['checks'] for c in native['checks'])
139 assert len(new['associationReifierControls'])==34
140 save(out/'native-preflight-confirmation.json',{'executedBeforeReaderChange':True,'nativeChecksBefore':12,'sameNativeChecksAndObservationsRepeatedInASDF':True,'nativeExecution':gate})
141 prior=read(PRIOR/'execution.json');log=(out/'regression.log').read_text()
142 for marker,count in dict(prior['retainedChecks'],**prior['stageChecks']).items():assert int(re.search(r'(?m)^'+marker+r'-PASS: (\d+)',log).group(1))==count
143 assert 'CTM-XTM-EQUIVALENCE-PASS: 515 checks; 29 actual reader pairs;' in log
144 assert 'Ran 2 tests' in log and 'NFC-ORACLE-PASS: 16294' in log and 'CXML-SUMMARY 146 PASS 0 FAIL' in (out/'xml.log').read_text()
145 lock=read(ROOT/'references/corpus-lock.json')
146 for f in lock['files']:
147 p=ROOT/'vendor/cxtm'/f['path'];assert p.stat().st_size==f['size'] and sha(p)==f['sha256']
148 assert protected=={p:sha(ROOT/p) for p in protected}
149 save(out/'integrity.json',{'protectedBaseFilesSHA256':protected,'pinnedCorpusFilesVerified':len(lock['files']),'historicalReportFilesVerified':sum(p.startswith('reports/') for p in protected),
150 'originalsBaselinesHistoricalReportsAndCorpusLockUnchanged':True,'productionChanges':['src/xtm/reader.lisp'],'TMDM_CTM_CXTM_XMLUnchanged':True})
151 save(out/'execution.json',{'kind':'slice-22m-XTM-association-reification','baseCommit':BASE,'branch':git('branch','--show-current'),'runtime':'SBCL 2.5.4',
152 'startedAtUTC':run['startedAtUTC'],'finishedAtUTC':run['finishedAtUTC'],'auditedAtUTC':datetime.datetime.now(datetime.timezone.utc).isoformat(),'runs':run['runs'],
153 'collector':'scripts/validate-slice-22d.py::collect (unchanged)','auditToolSHA256':sha(Path(__file__)),'standaloneXTMChecks':len(labels),'retainedStandaloneXTMChecks':len(old['checks']),
154 'newXTMChecks':len(labels)-len(old['checks']),'retainedLispChecks':12100,'retainedChecks':prior['retainedChecks'],'stageChecks':prior['stageChecks'],
155 'equivalenceChecks':515,'equivalenceReaderPairs':29,'faultControls':113,'allOriginalStatusesCompared':124,'diagnosticChanges':len(changes),'registeredStatusChanges':5,
156 'statusesBefore':prior['statusesAfter'],'statusesAfter':{'XTM':{'pass':115,'fail':0,'not-run':9},'CTM':{'pass':262,'fail':4,'not-run':7},'total':{'pass':377,'fail':4,'not-run':16}},
157 'originalRegistrationsAdded':5,'xmlQualificationChecks':146,'pythonUnitTests':2,'nfcOracleComparisons':16294,'pinnedCorpusFilesVerified':len(lock['files']),
158 'historicalReportFilesVerified':sum(p.startswith('reports/') for p in protected),'knownCTMFailuresUnchanged':prior['knownCTMFailuresUnchanged'],
159 'productionChanges':['src/xtm/reader.lisp'],'nativePreflightBeforeReaderChange':gate,'nativeGateChecks':12,'totalFreshProcessesIncludingBeforeGate':120,'newDependencyDownloads':0,'persistentImagesTouched':False,'acceptancePassed':True})
160 print(json.dumps({'acceptancePassed':True,'XTMChecks':len(labels),'newOriginalPASS':5,'allOriginalStatusesCompared':124,'diagnosticChanges':len(changes),'faultControls':113}))
161 def main():
162 ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--output',type=Path,required=True);ap.add_argument('--audit-only',action='store_true');a=ap.parse_args();out=a.output.resolve();assert not out.is_relative_to(ROOT);out.mkdir(parents=True,exist_ok=True)
163 if not a.audit_only:
164 spec=importlib.util.spec_from_file_location('v22d',ROOT/'scripts/validate-slice-22d.py');v=importlib.util.module_from_spec(spec);spec.loader.exec_module(v);v.EXECUTION_FILES=SOURCES;v.collect(out,ROOT/'reports/slice-22d/baseline')
165 audit(out)
166 if __name__=='__main__':main()