Files
TheTree_mock/docs/plans/original-completion-2026-10-02/checkpoints/current-native-residual-r311-r312/p23-02-current-residual-diagnostic-r311.py

74 lines
7.1 KiB
Python

# coding: utf-8
"""One adjacent cold whole647 pair; equivalence and timing observation only."""
from pathlib import Path
import hashlib,importlib.util,json,os,shutil,subprocess,sys,uuid
sys.dont_write_bytecode=True
R=Path(__file__).resolve().parents[2];A=R/'artifacts/original-completion-2026-10-02'
O=A/'p23-02-current-residual-diagnostic-r311';D=R/'docs/plans/original-completion-2026-10-02'
NAMES=['IMPLEMENTATION_PLAN.md','PROGRESS_INTEGRATION.md','work_packages.json','progress_snapshot.json']
def mod(name,path):
s=importlib.util.spec_from_file_location(name,path);m=importlib.util.module_from_spec(s);s.loader.exec_module(m);return m
def unpack(path):return subprocess.run(['/opt/homebrew/bin/zstd','-d','-q','-c',str(path)],check=True,capture_output=True,timeout=10).stdout
def main():
r=mod('pair_runner',R/'tools/run_all_tests.py');outer=mod('pair_owned',r.SUPPORT/'owned_outer.py');plan=r.read(O/'input.json')
assert not (O/'execution.json').exists()
fixed=plan['pins'];source=r.source_refs(R);player=r.default_player(R);docs={n:r.sha(D/n) for n in NAMES}
pre_path=A/'p23-02-current-residual-diagnostic-preexecution-independent-review-r311.json'
pre=r.read(pre_path);assert pre['execution_allowed'] and not pre['blockers']
for group in ['evidence_sha256','canonical_doc4_context_pins']:
for q in pre[group].values():
p=Path(q['path']);assert p.stat().st_size==q['bytes'] and r.sha(p)==q['sha256']
root=r.read(O/'preexecution-root-verification.json');assert root['passed'] and root['review_sha256']==r.sha(pre_path)
assert source==plan['source_before'] and player==plan['default_before'] and docs==plan['doc4_before']
stages={k:Path(v) for k,v in plan['stages'].items()};public={k:(p/'project.godot').read_bytes() for k,p in stages.items()}
def protect():
assert r.source_refs(R)==source and r.default_player(R)==player and {n:r.sha(D/n) for n in NAMES}==docs
assert r.inventory(r.SUPPORT)==plan['support_inventory']
for k,p in stages.items():assert r.inventory(p,stage=True)==plan['stage_inventory']
for k,p in plan['parents'].items():assert r.inventory(Path(p),stage=True)==plan['inventories'][k]
for k,q in fixed.items():
p=Path(q['path']);assert p.stat().st_size==q['bytes'] and r.sha(p)==q['sha256'],k
protect()
assert r.read(Path(fixed['local_review']['path']))['finite_local_equivalence_accepted']
assert r.read(Path(fixed['whole_review']['path']))['finite_whole647_equivalence_accepted']
phases=[];samples=[];error=None;cleanup=[];cleanup_errors=[]
oracle=unpack(fixed['oracle']['path']);assert len(oracle)==11487732 and hashlib.sha256(oracle).hexdigest()=='9df3c1b6f65dfd8be944cd5cab8c631f7533530dfef3820d9fa5d74a5b1ac30f'
try:
for k in ['r274']:
protect();assert not outer.native.helper['live_engines']() and shutil.disk_usage(A).free>=plan['capacity_floor_bytes']
stage=stages[k];output=O/(k+'-measurement');output.mkdir();ident=uuid.uuid4().hex
startup='TheTree-PCK-tests-'+ident+'-whole-startup';profile='TheTree-PCK-tests-'+ident+'-whole-runtime'
assert not r.profile_path(startup).exists() and not r.profile_path(profile).exists()
env=r.fresh_environment(os.environ)
env.update(THE_TREE_PACK_PROFILE_NAME=profile,THE_TREE_PACK_PROFILE_EXPECTED=str(r.profile_path(profile)),THE_TREE_PACK_PROFILE_REPORT=str(O/(k+'-profile.json')),THE_TREE_RUNTIME_MONITOR_OUTPUT=str(output),THE_TREE_REPLAY_SNAPSHOT=fixed['fixture']['path'],THE_TREE_CANDIDATE_ORACLE=fixed['oracle']['path'],THE_TREE_PAIRED_CANDIDATE=k,THE_TREE_PAIRED_SAMPLE=k)
(stage/'project.godot').write_bytes(r.private_project(public[k],startup));phase=O/k
argv=[fixed['engine']['path'],'--headless','--path',str(stage),'--script',fixed['starter_'+k]['path'],'--verbose','--log-file',str(phase/'engine-native.log')]
result,capture=outer.run_phase(argv,phase,90,env,now_fn=r.now,dump_fn=r.write,sha_fn=r.sha,live_engines_fn=outer.native.helper['live_engines'])
row=dict(candidate=k,result=result,capture=capture);phases.append(row);r.write(O/(k+'-phase.json'),row)
report_path=output/'report.json';report=r.read(report_path) if report_path.exists() else None
if report is not None:samples.append(report)
assert result is not None and result['exit_code']==0 and not result['error_lines'] and not result['timed_out'] and capture['passed']
logs=''.join((phase/n).read_text() for n in ['stdout.log','stderr.log','engine-native.log'])
assert 'Orphan StringName:' not in logs and 'unclaimed string names' not in logs
assert report and report['passed'] and not report['failures'] and report['pid']==result['pid'] and report['candidate']==k and report['sample']==k and report['checks']==18
assert (phase/'stdout.log').read_text().count('Residual diagnostic whole647: 18 checks, 0 failures')==1 and (phase/'stdout.log').read_text().count('NATIVE_ADAPTER_LIBRARY_REGISTERED')==1
r.profile_gate(r.profile_path(profile),O/(k+'-profile.json'),profile)
ref=report['after647'];raw=unpack(ref['path']);assert raw==oracle and len(raw)==ref['uncompressed_bytes'] and hashlib.sha256(raw).hexdigest()==ref['uncompressed_sha256']
metric_ref=report['metrics'];metric_raw=unpack(metric_ref['path']);assert len(metric_raw)==metric_ref['uncompressed_bytes'] and hashlib.sha256(metric_raw).hexdigest()==metric_ref['uncompressed_sha256']
(stage/'project.godot').write_bytes(public[k]);protect()
except BaseException as caught:error=type(caught).__name__+': '+str(caught)
finally:
cleanup,cleanup_errors=outer.finish_captured(outer.OWNED)
if all(q['engine_ended'] is True for q in cleanup):
for k,p in stages.items():(p/'project.godot').write_bytes(public[k])
else:cleanup_errors.append('Project restoration refused while owned child remains live')
guard_errors=[]
try:protect()
except BaseException as caught:guard_errors.append(type(caught).__name__+': '+str(caught))
assert sum(p.stat().st_size for p in O.rglob('*') if p.is_file() and 'stage' not in p.relative_to(O).parts)<=16*1048576
pairs=[] # A diagnostic observation cannot support an uninstrumented speed comparison.
passed=error is None and not guard_errors and not cleanup_errors and len(samples)==1 and len(phases)==1
r.write(O/'execution.json',dict(passed=passed,error=error,guard_errors=guard_errors,phases=phases,samples=samples,diagnostic_only=True,cleanup=cleanup,cleanup_errors=cleanup_errors,input_source_default_doc4_preserved=not guard_errors,candidate_adopted=False,unit_accepted=False,performance_accepted=False,normal_OS_accepted=False,Windows_accepted=False,limitations=['One instrumented whole647 equivalence and nested inclusive residual metrics only. No sums/subtractions as pure CPU, no uninstrumented speed comparisons. Stable gain, P95, budget, final regression, realtime x3/Main/render/OS/Windows remain unaccepted.']))
print(json.dumps(dict(passed=passed,error=error,guard_errors=guard_errors,samples=len(samples))),flush=True);return 0 if passed else 1
if __name__=='__main__':raise SystemExit(main())