Inventory existing G1 material and validate virtual scheduler contract

This commit is contained in:
Frank14f committed 2026-11-14 19:11:38 +08:00
1 parent 07003020c5
commit 24d2da0fe7
14 files changed
+662

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
"""Inventory existing metadata and NPZ member names only; no geometry processing.
Identity-bearing output is for the designated custodian, never a blind view.
No original archive/VTU/LOG or NPZ payload is read. Historical mixed JSON is
parsed, but only pre-existing geometry fields are selected; process/results
fields are not exported or used. No parent identity is inferred from filenames.
"""
from pathlib import Path
from zipfile import ZipFile
from collections import Counter, defaultdict
import hashlib,json,re,resource,time
CASE=re.compile(r'\d{8}_[a-zA-Z0-9]+_step_\d{3}')
def write(path,data):
path.write_text(json.dumps(data,indent=2,ensure_ascii=False,allow_nan=False)+'\n')
def main():
start=time.monotonic();out=Path('artifacts/s2-g1-inventory-2026-11-14');out.mkdir(exist_ok=False)
private=out/'custodian';public=out/'public';private.mkdir();public.mkdir()
base=Path('artifacts/intake-2026-11-13')
inputs={n:base/n for n in ['source_groups.json','geometry_log_census.json','geometry_screening.json']}
groups=json.loads(inputs['source_groups.json'].read_text());cases=sorted(c for v in groups.values() for c in v);case_set=set(cases)
metadata=json.loads(inputs['geometry_log_census.json'].read_text())
allowed=['bbox_size_raw','covariance_eigenvalues','exact_sorted_points_sha256']
historic={r['case']:{k:r[k] for k in allowed if k in r} for r in metadata};del metadata
screening=json.loads(inputs['geometry_screening.json'].read_text());pairs=screening['candidate_pairs'];assert len(pairs)==30
exposed_old={p[k] for p in pairs for k in ['a','b']};assert exposed_old<=case_set
caches=defaultdict(list);exposure=defaultdict(set);npz_count=0
# Directory names are evidence of previous individual work, not independent truth.
diagnostic_prefixes=('s1-real-scoring','s1-sampled-o2','e6-','o2-rep','o2a-','capacity-projectors','physical-support','routes-')
for path in sorted(Path('artifacts').rglob('*')):
if not path.is_file() or out in path.parents:continue
ids=set(CASE.findall(str(path)))&case_set
stage=path.parts[1]
if stage.startswith(diagnostic_prefixes):
for case in ids:exposure[case].add(stage)
if path.suffix!='.npz':continue
npz_count+=1
with ZipFile(path) as z:keys=set(n.removesuffix('.npy') for n in z.namelist())
surface=({'points','boundary'}<=keys or {'points_raw','boundary_triangles'}<=keys)
if surface:
st=path.stat();entry={'path':str(path),'bytes':st.st_size,'mtime_ns':st.st_mtime_ns,'surface_coordinate_key':'points' if 'points' in keys else 'points_raw','surface_index_key':'boundary' if 'boundary' in keys else 'boundary_triangles','contains_field_labels':'fill_time_raw' in keys,'validation':'ZIP member-name availability only; no arrays read or geometry validity asserted','producer_version':'E1 contract' if stage=='s2-e1-2026-11-14' else 'existing stage source/receipt; not revalidated'}
for case in ids:caches[case].append(entry)
rows=[]
for case in cases:
events=sorted(exposure[case]);known=case in exposed_old or bool(events)
rows.append({'case':case,'source_key':case.split('_')[1],'source_key_evidence':str(inputs['source_groups.json']),
'verified_parent_geometry':None,'parent_provenance':None,'parent_gap':'No independently verified CAD parent/source relationship found in existing reviewed manifests; source key is not a verified parent',
'exposure_state':'KNOWN_DEVELOPMENT_EXPOSED' if known else 'UNKNOWN',
'old_30_pair_endpoint':case in exposed_old,'individual_diagnostic_stages':events,
'all_corpus_historical_screening':True,'unexposed_claim':False,'surface_caches':caches[case],
'historical_geometry_metadata':historic.get(case,{}),'historical_fingerprint_source':str(inputs['geometry_log_census.json']),
'historical_fingerprint_limit':'unweighted full point-cloud covariance/extent/hash; mesh-density dependent; mixed-cell cases not tet-only; not note16 area/volume weighted descriptor',
'note16_complete_fingerprint':False,'note16_fingerprint_path':None,'independent_holdout_eligible':False})
by_case={r['case']:r for r in rows};cluster_rows=[]
for key,members in sorted(groups.items()):
n=sum(by_case[c]['exposure_state']=='KNOWN_DEVELOPMENT_EXPOSED' for c in members)
cluster_rows.append({'source_key':key,'members':sorted(members),'known_exposed_members':n,'state':'EXPOSED_CLUSTER' if n else 'UNKNOWN_EXPOSURE_CLUSTER','verified_parent_cluster':False,'holdout_eligible':False})
old=[{'a':p['a'],'b':p['b'],'historical_rank':i+1,'discovery':'legacy covariance/extent nearest-neighbor screen','discovery_source':str(inputs['geometry_screening.json']),'development_exposed':True,'independent_discovery_evidence':None,'confirmed_relation':None,'natural_positive_truth':False} for i,p in enumerate(pairs)]
write(private/'parts.json',rows);write(private/'source_clusters.json',cluster_rows);write(private/'old_exposed_pairs.json',old)
write(private/'independent_natural_pairs.json',{'pairs':[],'status':'MISSING_INDEPENDENT_SOURCE_EVIDENCE','not_a_claim_of_absence_of_duplicates':True})
private_manifest=[{'file':p.name,'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'bytes':p.stat().st_size} for p in sorted(private.glob('*.json'))]
write(private/'manifest.json',private_manifest)
summary={'scope':'existing material inventory only; no new descriptors, candidates, pair extraction, labels from original source, LOG reread, registration, training or GPU',
'cases':len(rows),'source_keys':len(groups),'verified_parent_links':0,'verified_independent_natural_positive_pairs':0,
'old_exposed_pairs':len(old),'old_exposed_endpoint_cases':len(exposed_old),
'exposure_counts':dict(Counter(r['exposure_state'] for r in rows)),
'cluster_exposure_counts':dict(Counter(r['state'] for r in cluster_rows)),
'independent_holdout_eligibility_certified_cases':0,'surface_cache_cases':sum(bool(r['surface_caches']) for r in rows),
'surface_cache_records':sum(len(r['surface_caches']) for r in rows),'npz_member_directories_inspected':npz_count,
'legacy_geometry_metadata_cases':sum(bool(r['historical_geometry_metadata']) for r in rows),'note16_complete_fingerprint_cases':0,
'custody':'IDENTITY_TABLES_PREPARED_LOCALLY; designated custodian/interface pending Claude; no anonymous IDs or blind bundle generated',
'identity_manifest_sha256':hashlib.sha256((private/'manifest.json').read_bytes()).hexdigest(),
'input_sha256':{str(p):hashlib.sha256(p.read_bytes()).hexdigest() for p in inputs.values()},
'producer_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
'interpretation':'0 certified independent positives/eligible cases means missing proof, not zero true relatives; unknown exposure cannot be promoted to unexposed. Old geometry screening is not the proposed fingerprint. Source keys are not CAD ancestry.',
'mixed_metadata_disclosure':'Existing geometry_log_census JSON also stores historical process/output fields; parsed as a container, only bbox/covariance/point hash selected. Other fields not used or exported. NPZ access is ZIP member names only, no payload.',
'cpu_seconds':sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),'wall_seconds':time.monotonic()-start,'peak_rss_bytes':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*1024}
write(public/'summary.json',summary);print(json.dumps(summary,ensure_ascii=False,indent=2))
if __name__=='__main__':main()
+105
View File
@@ -0,0 +1,105 @@
"""Pure discrete-event contract model. NO subprocesses, data reads or real jobs.
Virtual process-tree inputs test accounting and barriers, not Linux enforcement.
A production adapter must supply sampled + final tree accounting, kill/reap,
locks and persisted recovery; none is claimed here.
"""
from dataclasses import dataclass, asdict
import math
@dataclass(frozen=True)
class Task:
pair_id: str
rank: int
duration: float = 1.
tree_cpu_rates: tuple = (1.,)
tree_rss_bytes: tuple = (1024,)
disk_rate: float = 0.
fails: bool = False
@dataclass(frozen=True)
class Limits:
workers: int = 16
worker_cpu: float = 80*3600
wall: float = 8*3600
disk: float = 20*1024**3
pair_wall: float = 1800.
pair_rss: int = 1342177280
checkpoint: int = 100
def simulate(tasks, limits=Limits(), *, supervisor_cpu_rate=.1):
"""Virtual seconds/bytes only. Each unique pair is attempted at most once."""
tasks=sorted(tasks,key=lambda t:(t.rank,t.pair_id))
if len({t.pair_id for t in tasks})!=len(tasks):raise ValueError('Duplicate pair cannot expand denominator')
if not 1<=limits.workers<=16 or limits.checkpoint!=100:raise ValueError('Contract worker/checkpoint bound')
if any(not math.isfinite(v) or v<=0 for v in asdict(limits).values()):raise ValueError('Invalid limit')
if not math.isfinite(supervisor_cpu_rate) or supervisor_cpu_rate<0:raise ValueError('Invalid supervisor rate')
for t in tasks:
values=(t.duration,*t.tree_cpu_rates,*t.tree_rss_bytes,t.disk_rate)
if not t.pair_id or not math.isfinite(t.rank) or any(not math.isfinite(v) or v<0 for v in values) or t.duration<=0 or not t.tree_cpu_rates or not t.tree_rss_bytes:
raise ValueError('Invalid virtual tree/task')
active={};records=[];events=[];checkpoints=[];index=0;end=min(100,len(tasks))
elapsed=worker_cpu=supervisor_cpu=disk=0.;peak_workers=peak_tree_processes=0
reason=None
def finish(pid,why=None):
a=active.pop(pid);t=a['task']
records.append({'pair_id':pid,'rank':t.rank,'status':'FAIL' if why or t.fails else 'PASS',
'reason':why or ('worker_exit' if t.fails else None),'worker_tree_cpu':a['cpu'],
'tree_rss':sum(t.tree_rss_bytes),'start':a['start'],'finish':elapsed})
events.append({'event':'finish','pair_id':pid,'time':elapsed,'reason':records[-1]['reason']})
def global_limit():
if worker_cpu>=limits.worker_cpu:return 'worker_cpu_cap'
if elapsed>=limits.wall:return 'global_wall_cap'
if disk>=limits.disk:return 'global_disk_cap'
while index<len(tasks) or active:
reason=global_limit()
if reason:break
# Barrier: never launch pair 101 while any of first 100 are in flight.
while index<end and len(active)<limits.workers:
t=tasks[index];index+=1
active[t.pair_id]={'task':t,'start':elapsed,'cpu':0.}
events.append({'event':'start','pair_id':t.pair_id,'time':elapsed,'attempt':index})
peak_workers=max(peak_workers,len(active))
peak_tree_processes=max(peak_tree_processes,sum(len(a['task'].tree_rss_bytes) for a in active.values()))
if sum(t.tree_rss_bytes)>limits.pair_rss:finish(t.pair_id,'pair_tree_rss_cap')
if not active and index==end:
failed=sum(r['status']=='FAIL' for r in records)
assert len(records)==index
checkpoint={'attempted':index,'terminal':len(records),'failed':failed,'time':elapsed,'stop':failed*50>index}
checkpoints.append(checkpoint);events.append({'event':'checkpoint',**checkpoint})
if checkpoint['stop']:reason='failure_fraction_gt_2_percent';break
if index==len(tasks):break
end=min(end+100,len(tasks));continue
rate=sum(sum(a['task'].tree_cpu_rates) for a in active.values())
disk_rate=sum(a['task'].disk_rate for a in active.values())
remaining=[min(a['task'].duration,limits.pair_wall)-(elapsed-a['start']) for a in active.values()]
remaining += [limits.wall-elapsed]
if rate:remaining.append((limits.worker_cpu-worker_cpu)/rate)
if disk_rate:remaining.append((limits.disk-disk)/disk_rate)
dt=max(0.,min(remaining))
if dt==0:raise RuntimeError('Zero-time event without stop/terminal transition')
elapsed+=dt;supervisor_cpu+=supervisor_cpu_rate*dt;disk+=disk_rate*dt
for a in active.values():
c=sum(a['task'].tree_cpu_rates)*dt;a['cpu']+=c;worker_cpu+=c
for pid,a in list(active.items()):
t=a['task'];age=elapsed-a['start']
if age>=min(t.duration,limits.pair_wall):
finish(pid,'pair_wall_cap' if t.duration>limits.pair_wall else None)
reason=reason or global_limit()
if reason:
for pid in list(active):finish(pid,reason)
# Stop/global cap still records an end checkpoint against every attempted pair.
if records and (not checkpoints or checkpoints[-1]['attempted']!=index):
failed=sum(r['status']=='FAIL' for r in records)
checkpoints.append({'attempted':index,'terminal':len(records),'failed':failed,'time':elapsed,'stop':failed*50>index,'trigger':'end/global stop'})
if reason is None and checkpoints and checkpoints[-1]['stop']:
reason='failure_fraction_gt_2_percent'
assert len(records)==index and abs(sum(r['worker_tree_cpu'] for r in records)-worker_cpu)<1e-6
return {'kind':'PURE_VIRTUAL_CONTRACT_SIMULATION_NOT_REAL_PROCESS_SUPERVISION',
'status':'STOPPED' if reason else 'COMPLETE','stop_reason':reason,'attempted':index,
'not_attempted':len(tasks)-index,'records':records,'events':events,'checkpoints':checkpoints,
'virtual_worker_cpu':worker_cpu,'virtual_supervisor_cpu':supervisor_cpu,
'virtual_wall':elapsed,'virtual_disk':disk,'peak_worker_trees':peak_workers,
'peak_virtual_process_count_including_descendants':peak_tree_processes,
'real_workers_started':0,'retry':False}
+55
View File
@@ -0,0 +1,55 @@
import unittest
from dataclasses import replace
from simulate_g1_scheduler import Task, Limits, simulate
def tasks(n, failures=()):
return [Task(f'sim-{i:04}',i,fails=i in failures) for i in range(n)]
class ContractTests(unittest.TestCase):
def test_exact_two_percent_continues_and_barrier(self):
ts=tasks(201,{0,1});ts[0]=replace(ts[0],duration=20)
r=simulate(ts)
self.assertEqual(r['status'],'COMPLETE');self.assertEqual([c['attempted'] for c in r['checkpoints']],[100,200,201])
first_end=max(x['finish'] for x in r['records'] if x['rank']<100)
self.assertGreaterEqual(next(x['start'] for x in r['records'] if x['rank']==100),first_end)
self.assertEqual(r['peak_worker_trees'],16)
def test_three_percent_stops_no_101(self):
r=simulate(tasks(250,{0,1,2}));self.assertEqual(r['attempted'],100);self.assertEqual(r['not_attempted'],150)
self.assertEqual(r['stop_reason'],'failure_fraction_gt_2_percent')
def test_final_short_batch_check(self):
self.assertEqual(simulate(tasks(49,{0}))['stop_reason'],'failure_fraction_gt_2_percent')
self.assertEqual(simulate(tasks(50,{0}))['status'],'COMPLETE')
self.assertEqual(simulate(tasks(100,{0,1,2}))['stop_reason'],'failure_fraction_gt_2_percent')
def test_duplicate_pair_rejected(self):
with self.assertRaises(ValueError):simulate([Task('same',1),Task('same',2)])
def test_tree_cpu_and_failed_cpu_separate_from_supervisor(self):
r=simulate([Task('a',0,2,(1.,2.),(10,20),fails=True)],supervisor_cpu_rate=5)
self.assertEqual(r['virtual_worker_cpu'],6);self.assertEqual(r['virtual_supervisor_cpu'],10)
self.assertEqual(r['records'][0]['worker_tree_cpu'],6)
def test_global_worker_cpu_stops_all(self):
r=simulate([Task('a',0,10),Task('b',1,10)],replace(Limits(),worker_cpu=3))
self.assertEqual(r['stop_reason'],'worker_cpu_cap');self.assertEqual(r['virtual_worker_cpu'],3)
self.assertEqual(len(r['records']),2);self.assertTrue(all(x['status']=='FAIL' for x in r['records']))
def test_global_wall(self):
r=simulate([Task('a',0,10)],replace(Limits(),wall=2))
self.assertEqual(r['stop_reason'],'global_wall_cap');self.assertEqual(r['virtual_wall'],2)
def test_global_disk_cumulative(self):
r=simulate([Task('a',0,1,disk_rate=6),Task('b',1,10,disk_rate=4)],replace(Limits(),disk=14))
self.assertEqual(r['stop_reason'],'global_disk_cap');self.assertEqual(r['virtual_disk'],14)
def test_child_rss_summed_and_failure_preserved(self):
ts=tasks(100);ts[0]=Task('sim-0000',0,1,(1,1),(70,70))
r=simulate(ts,replace(Limits(),pair_rss=100000))
self.assertEqual(r['records'][0]['tree_rss'],140)
r=simulate([Task('x',0,1,(1,1),(70,70))],replace(Limits(),pair_rss=100))
self.assertEqual(r['records'][0]['reason'],'pair_tree_rss_cap')
def test_pair_wall_failure_continues_to_checkpoint(self):
ts=tasks(100);ts[0]=replace(ts[0],duration=5)
r=simulate(ts,replace(Limits(),pair_wall=2))
self.assertEqual(r['status'],'COMPLETE');self.assertEqual(next(x for x in r['records'] if x['rank']==0)['reason'],'pair_wall_cap')
def test_stable_rank_and_worker_bound(self):
r=simulate([Task('z',1),Task('b',0),Task('a',0)],replace(Limits(),workers=1))
self.assertEqual([e['pair_id'] for e in r['events'] if e['event']=='start'],['a','b','z'])
with self.assertRaises(ValueError):simulate(tasks(2),replace(Limits(),workers=17))
if __name__=='__main__':unittest.main()