]> dreyeck.freedombox.rocks Git - topic-maps.git/blob - scripts/validate-slice-22l.py
Implement XTM role reification with native conformance evidence
[topic-maps.git] / scripts / validate-slice-22l.py
1 #!/usr/bin/env python3
2 """Slice 22L acceptance audit over the existing offline collector and case records.
3 --audit-only checks saved executions without rerunning tests. Output is outside Git.
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-22l';PRIOR=ROOT/'reports/slice-22k/after'
10 BASE='c02207856f1927302ea064bc901e07183242f2da'
11 ALLOWED={'tests/ctm-xtm-mergemap.lisp', 'tests/xtm-variant-reification.lisp', 'tests/xtm-identity.lisp', 'tests/ctm-xtm-equivalence.lisp', 'tests/xtm-name-scopes.lisp', 'topic-maps.asd', 'tests/xtm-map-reification.lisp', 'src/xtm/reader.lisp', 'tests/xtm-occurrences.lisp', 'tests/xtm-mergemap.lisp', 'tests/xtm-item-identities.lisp', 'tests/xtm-negative-originals.lisp', 'tests/xtm-resource-datatypes.lisp'}
12 SOURCES=ALLOWED|{'tests/xtm-occurrence-reifier-native.lisp','tests/xtm-occurrence-reification.lisp','reports/slice-22l/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':107,'fail':0,'unsupported':0,'not-run':0}
34 assert new['statuses']=={'pass':110,'fail':0,'unsupported':0,'not-run':0} and new['otherCorpusInputs']=={'positiveUnexecuted':13,'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))==3447
40 permitted={'scope','statuses','otherCorpusInputs','checks','cases','scopeControls','mapReifierControls','variantReifierControls','datatypeControls','occurrenceControls','itemIdentityControls','mergemapControls'}
41 for key in old:
42 if key not in permitted:assert old[key]==new[key],key
43 retargets=[]
44 expected={'scopeControls':1,'mapReifierControls':1,'variantReifierControls':1,'datatypeControls':1,'occurrenceControls':2,'itemIdentityControls':1,'mergemapControls':1}
45 for key,count in expected.items():
46 arows=old[key];brows=[row for row in new[key] if row['label']!='Occurrence-Reification-import']
47 assert len(arows)==len(brows)
48 changed=[(a,b) for a,b in zip(arows,brows) if a!=b];assert len(changed)==count,(key,changed)
49 for a,b in changed:
50 assert a['label']==b['label'] and a['condition']['class']==b['condition']['class']=='XTM-UNSUPPORTED'
51 assert a['condition']['code']=='unsupported-construct' and b['condition']['code']=='resource-data-datatype'
52 if key=='mergemapControls':
53 assert b['sourceText']==a['sourceText'] and "<mergeMap href='child.xtm'/>" in b['sourceText']
54 fixture=next(r for r in read(D/'retargetings.json') if r['file']=='tests/xtm-mergemap.lisp')
55 assert fixture['afterSource'] in (ROOT/fixture['file']).read_text()
56 assert run['executionSourcesSHA256'][fixture['file']]==sha(ROOT/fixture['file'])
57 else:assert 'http://www.w3.org/2001/XMLSchema#anyType' in b['sourceText']
58 retargets.append({'reportKey':key,'label':a['label'],'before':a,'after':b,'differences':diff(a,b)})
59 imported=new['mergemapControls'][0];assert imported['label']=='Occurrence-Reification-import' and imported['sourceMapsPreserved'] and imported['qualifiedParserCalls']==2
60 assert len(imported['resolverCalls'])==1 and imported['model']['canonicalNativeReferencesEQ']
61 save(out/'retargeted-control-observations.json',retargets)
62 originals=[];(out/'actual').mkdir(exist_ok=True)
63 assert {x['id'] for x in new['occurrenceReifierOriginals']}==targets
64 for row in new['occurrenceReifierOriginals']:
65 source=inputs[row['id']];raw=bytes.fromhex(row['sourceHex'])
66 assert raw==(ROOT/'vendor/cxtm'/row['id']).read_bytes() and hashlib.sha256(raw).hexdigest()==source['sourceSHA256']
67 assert row['status']=='pass'
68 if '/invalid/' in row['id']:
69 c=row['condition'];assert row['intendedCauseReached'] and c['class']=='REIFICATION-ERROR' and c['code']=='reifier-conflict'
70 assert c['detail']=='Topic already reifies a different information item.' and c['line'] is c['column'] is c['sourceKey'] is c['documentIRI'] is None
71 frames=row['actualNativeAssignments'];assert len(frames)==1 and frames[0]['assignedItemKind']=='OCCURRENCE' and frames[0]['priorReifiedItemKind']=='TOPIC-MAP' and frames[0]['nativeAssignmentUnchanged']
72 assert after[row['id']]['actualOutcome']=='ctm-rejection'
73 else:
74 assert row['condition'] is None and row['firstDifferentByte'] is None and row['originalOctetsEQ'] and row['qualifiedParserCalls']==1 and row['oldHandlesCanonicalAndLive']
75 assert row['model']['canonicalOccurrenceReifierInverseEQ']
76 actual=row['actualCXTM'].encode();expected=(ROOT/'vendor/cxtm/xtm2/baseline'/(Path(row['id']).name+'.cxtm')).read_bytes()
77 assert actual==expected==row['expectedCXTM'].encode() and len(actual)==row['actualBytes']==row['expectedBytes']==source['baselineBytes']
78 assert hashlib.sha256(expected).hexdigest()==source['baselineSHA256'] and after[row['id']]['actualOutcome']=='cxtm-match'
79 p=out/'actual'/(Path(row['id']).name+'.cxtm');p.write_bytes(actual)
80 row=dict(row,actualSHA256=sha(p),completeByteExact=True)
81 originals.append(dict(row,sourceSHA256=source['sourceSHA256'],baselineSHA256=source['baselineSHA256']))
82 save(out/'original-contracts.json',originals)
83 # Compare all original reader diagnoses, not only successful registrations.
84 oldd={x['id']:x for x in read(PRIOR/'after-diagnostics.json')};newd={x['id']:x for x in read(out/'after-diagnostics.json')}
85 inventory=sorted('xtm2/'+sub+'/'+p.name for sub in ['in','invalid'] for p in (ROOT/'vendor/cxtm/xtm2'/sub).glob('*.xtm'))
86 assert len(inventory)==124 and set(inventory)==set(oldd)==set(newd)
87 changed=[];matrix=[]
88 for id in inventory:
89 a,b=oldd[id],newd[id];ds=diff(a,b)
90 if ds:
91 assert id in targets
92 if '/in/' in id:assert b['byteExact'] and b['condition'] is None
93 else:assert b['condition']['class']=='REIFICATION-ERROR' and b['condition']['code']=='reifier-conflict'
94 changed.append({'id':id,'reason':'new Occurrence Reification reaches the intended original result','differences':ds})
95 elif id in targets:raise AssertionError(id)
96 bs=before.get(id,{}).get('status','not-run');ns=after.get(id,{}).get('status','not-run');assert (bs!=ns)==(id in targets)
97 matrix.append({'id':id,'before':bs,'after':ns,'registeredStatusChanged':bs!=ns,'diagnosisChanged':bool(ds),'beforeDiagnosis':a,'afterDiagnosis':b})
98 assert all(newd[id]==oldd[id] for id in before)
99 assert {x['id'] for x in changed}==targets
100 save(out/'diagnostic-changes.json',{'originalDiagnoses':124,'changed':len(changed),'unchanged':124-len(changed),'changes':changed})
101 save(out/'all-124-original-statuses.json',{'cases':matrix,'registeredChanges':3,'previous107OriginalPASSUnchanged':True})
102 faults=[]
103 for x in run['runs']:
104 if '-control-' not in x['label']:continue
105 a=read(PRIOR/(x['label']+'.json'));b=read(out/(x['label']+'.json'));changes=diff(a,b)
106 assert a['cases']==b['cases'] and a['statuses']==b['statuses'] and a['checks']==b['checks'] and x['exitCode']==1
107 aa=dict(a);bb=dict(b)
108 for k in ['scope','occurrenceReifierNative','occurrenceReifierOriginals','occurrenceReifierControls']:aa.pop(k,None);bb.pop(k,None)
109 for rt in retargets:
110 key=rt['reportKey'];aa[key]=[rt['after'] if row==rt['before'] else row for row in aa[key]]
111 assert aa==bb,(x['label'],diff(aa,bb))
112 assert not b['occurrenceReifierNative'] and not b['occurrenceReifierOriginals'] and not b['occurrenceReifierControls']
113 faults.append({'label':x['label'],'expectedASDFFailureObserved':True,'exitCode':1,'caseRecordsOutcomesAndChecksIdentical':True,'faultCountedAsOriginalPASS':False,'reportDifferences':changes})
114 assert len(faults)==113
115 save(out/'failure-controls.json',{'retained':113,'new':0,'controls':faults,'allTargetCasesAndChecksUnchanged':True,'failureDriverUnchanged':True})
116 retained=[]
117 for p in sorted((PRIOR/'retained').glob('*.json')):
118 rel=p.relative_to(PRIOR)
119 if p.name.endswith('.equivalence.json'):continue
120 if p.name=='xtm-mergemap.integration.json':
121 aa=read(p);bb=read(out/rel);ds=diff(aa,bb)
122 index=next(i for i,row in enumerate(aa['rejections']) if row['label']=='unsupported-occurrence-reification')
123 assert ds==[{'path':f'/rejections/{index}/code','before':'UNSUPPORTED-CONSTRUCT','after':'RESOURCE-DATA-DATATYPE'}]
124 save(out/'adapter-retargeting.json',{'report':str(rel),'onlyExpectedCodeChanged':True,'checksAndOuterClassAndCauseAndPositionsPreserved':True,'differences':ds,'before':aa['rejections'][index],'after':bb['rejections'][index]})
125 continue
126 assert p.read_bytes()==(out/rel).read_bytes(),str(rel)
127 retained.append({'report':str(rel),'sha256':sha(p),'byteIdentical':True})
128 for name in ['ctm.validation.json','ctm.cxtm.json','ctm.encoding.json']:
129 assert (out/name).read_bytes()==(PRIOR/name).read_bytes();retained.append({'report':name,'sha256':sha(out/name),'byteIdentical':True})
130 assert len(retained)==47;save(out/'retained-reports.json',retained)
131 eqpath=next((out/'retained').glob('*.equivalence.json'));eqa=read(PRIOR/eqpath.relative_to(out));eqb=read(eqpath)
132 oldpairs={x['id']:x for x in eqa['pairs']};pairs={x['id']:x for x in eqb['pairs']}
133 assert oldpairs.keys()==pairs.keys() and all(oldpairs[id]==pairs[id] for id in oldpairs if id!='occurrence-scope-reifier')
134 pair=pairs['occurrence-scope-reifier'];assert pair['byteExact'] and pair['nativePropertiesEqual'] and pair['ctmCanonicalEQ'] and pair['xtmCanonicalEQ']
135 assert pair['ctmBytes']==pair['xtmBytes'] and pair['firstDifferentByte'] is None and pair['ctmCondition'] is pair['xtmCondition'] is None
136 assert sum(x['kind']=='direct-reader-equivalence-pair' for x in eqb['pairs'])==29
137 assert sum(x['kind']=='reader-capability-gap-not-equivalence-PASS' for x in eqb['pairs'])==1
138 save(out/'equivalence-progress.json',{'previous28PairsAnd3ContrastsAndRemainingGapUnchanged':True,'resolvedCapabilityGap':pair,'checks':len(eqb['checks']),'pairs':29,'remainingGaps':1})
139 # The required native gate was really executed before the Reader was changed.
140 gate=read(D/'native-before-execution.json');native=read(D/'native-before/report.json')
141 assert gate['exitCode']==0 and gate['beforeAnyProductionChange'] and gate['network']==gate['repositoryWrites']=='denied'
142 assert gate['executionSourceSHA256']['src/xtm/reader.lisp']==initial['trackedFileSHA256']['src/xtm/reader.lisp']
143 for p,h in gate['executionSourceSHA256'].items():
144 if p!='src/xtm/reader.lisp':assert sha(ROOT/p)==h
145 assert sha(D/'native-before/run.log')==gate['logSHA256'] and sha(D/'native-before/report.json')==gate['reportSHA256']
146 assert len(native['checks'])==9 and not native['ReaderInvoked'] and native['originalRegistrationsAdded']==0
147 assert native['observations']==new['occurrenceReifierNative'] and all(c in new['checks'] for c in native['checks'])
148 save(out/'native-preflight-confirmation.json',{'executedBeforeReaderChange':True,'nativeChecksBefore':9,'sameNativeChecksAndObservationsRepeatedInASDF':True,'nativeExecution':gate})
149 prior=read(PRIOR/'execution.json');log=(out/'regression.log').read_text()
150 for marker,count in dict(prior['retainedChecks'],**prior['stageChecks']).items():assert int(re.search(r'(?m)^'+marker+r'-PASS: (\d+)',log).group(1))==count
151 assert f"CTM-XTM-EQUIVALENCE-PASS: {len(eqb['checks'])} checks; 29 actual reader pairs;" in log
152 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()
153 lock=read(ROOT/'references/corpus-lock.json')
154 for f in lock['files']:
155 p=ROOT/'vendor/cxtm'/f['path'];assert p.stat().st_size==f['size'] and sha(p)==f['sha256']
156 assert protected=={p:sha(ROOT/p) for p in protected}
157 save(out/'integrity.json',{'protectedBaseFilesSHA256':protected,'pinnedCorpusFilesVerified':len(lock['files']),'historicalReportFilesVerified':sum(p.startswith('reports/') for p in protected),
158 'originalsBaselinesHistoricalReportsAndCorpusLockUnchanged':True,'productionChanges':['src/xtm/reader.lisp'],'TMDM_CTM_CXTM_XMLUnchanged':True})
159 save(out/'execution.json',{'kind':'slice-22l-XTM-occurrence-reification','baseCommit':BASE,'branch':git('branch','--show-current'),'runtime':'SBCL 2.5.4',
160 'startedAtUTC':run['startedAtUTC'],'finishedAtUTC':run['finishedAtUTC'],'auditedAtUTC':datetime.datetime.now(datetime.timezone.utc).isoformat(),'runs':run['runs'],
161 'collector':'scripts/validate-slice-22d.py::collect (unchanged)','auditToolSHA256':sha(Path(__file__)),'standaloneXTMChecks':len(labels),'retainedStandaloneXTMChecks':len(old['checks']),
162 'newXTMChecks':len(labels)-len(old['checks']),'retainedLispChecks':12100,'retainedChecks':prior['retainedChecks'],'stageChecks':prior['stageChecks'],
163 'equivalenceChecks':len(eqb['checks']),'equivalenceReaderPairs':29,'faultControls':113,'allOriginalStatusesCompared':124,'diagnosticChanges':len(changed),'registeredStatusChanges':3,
164 'statusesBefore':prior['statusesAfter'],'statusesAfter':{'XTM':{'pass':110,'fail':0,'not-run':14},'CTM':{'pass':262,'fail':4,'not-run':7},'total':{'pass':372,'fail':4,'not-run':21}},
165 'originalRegistrationsAdded':3,'xmlQualificationChecks':146,'pythonUnitTests':2,'nfcOracleComparisons':16294,'pinnedCorpusFilesVerified':len(lock['files']),
166 'historicalReportFilesVerified':sum(p.startswith('reports/') for p in protected),'knownCTMFailuresUnchanged':prior['knownCTMFailuresUnchanged'],
167 'productionChanges':['src/xtm/reader.lisp'],'nativePreflightBeforeReaderChange':gate,'nativeGateChecks':9,'totalFreshProcessesIncludingBeforeGate':120,'newDependencyDownloads':0,'persistentImagesTouched':False,'acceptancePassed':True})
168 print(json.dumps({'acceptancePassed':True,'XTMChecks':len(labels),'newOriginalPASS':3,'allOriginalStatusesCompared':124,'diagnosticChanges':len(changed),'faultControls':113}))
169 def main():
170 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)
171 if not a.audit_only:
172 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')
173 audit(out)
174 if __name__=='__main__':main()