Implement approved S3-B exact events and guarded fixed-ten measurement

This commit is contained in:
Frank14f committed 2026-11-15 19:31:07 +08:00
1 parent 95ab07dcd6
commit 2934ac16c1
15 files changed
+1502

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
"""Metadata-only preparation of the already fixed ten, no label/data decode."""
import csv
import json
from pathlib import Path
import numpy as np
import scipy
from s2_recovery_supervisor import save
from s3b_runtime import ROOT, RULE, sha, read
from s3b_graph import SOLVER
def main():
if ROOT.exists(): raise FileExistsError('Never replace a S3-B batch')
roster_path=Path('artifacts/s2-main-preparation-2026-11-15/final-roster.json')
roster=read(roster_path)
rows={r['case']:r for r in roster['parts'] if r['included']}
if len(rows)!=617: raise ValueError('Roster changed')
plan_path=Path('artifacts/s2-e1-2026-11-14/preflight/ten_part_plan.csv')
plans=list(csv.DictReader(plan_path.open()))
if [int(v['numeric_prefix']) for v in plans]!=[1130,1324,842,367,746,777,1552,1379,610,666]:
raise ValueError('Fixed ten changed')
parts=[]
for plan in plans:
row=rows[plan['case']];p=row['preparation'];source=Path(p['preparation_root'])
inputs={str(source/name):p['output_sha256'][name] for name in ['geometry.npz','boundary_distance_raw.npy','base.npy']}
inputs[str(source/'result.json')]=p['result_sha256']
parts.append(dict(case=row['case'],nodes=row['nodes'],component_id=row['component_id'],
preparation_root=str(source),inputs=inputs))
accepted=Path('artifacts/s3b-a-synthetic-2026-11-15')
receipts=list(accepted.glob('attempt-*/synthetic.receipt.json'))
if not receipts or read(sorted(receipts)[-1])['status']!='PASS': raise ValueError('Synthetic acceptance missing')
tests_cpu=sum(read(p)['cpu_seconds'] for p in receipts)
source_paths=[roster_path,plan_path,Path('docs/s3b-a-contract-2026-11-15.md'),*receipts]
code=[*Path('tools').glob('*s3b*.py'),Path('tools/boundary_distance.py'),
Path('tools/s2_recovery_supervisor.py'),Path('tools/s2_recovery_monitoring.py')]
c=dict(version='S3B-a-exact-event-ten-v1',authorizing_ruling=RULE,
contract_review_commit='95ab07dcd6104e8cbb7afdcdd7ea1e18cdcaf9d2',
roster=str(roster_path),roster_sha256=sha(roster_path),ten_parts=parts,
all_cases=sorted(rows),total_nodes=sum(r['nodes'] for r in rows.values()),
solver=SOLVER,worker_cpu=16,coordinator_cpus=[30,31],
prior_synthetic_worker_CPU_s=tests_cpu,
limits=dict(total_worker_CPU_s=72000,postfit_reserve_CPU_s=7200,ten_CPU_s=10800,
part_CPU_s=1800,part_wall_s=1800,part_RSS_bytes=4*2**30,
ten_disk_bytes=5*2**30,total_disk_bytes=20*2**30,workers=1,processes_per_worker=1),
numpy_version=np.__version__,scipy_version=scipy.__version__,
label_policy='Exact geometry/base/distance/result file allowlist; audit-denied label/archive/cache reads',
stage='TEN_ONLY; after cost evidence continue already authorized preparation without restarting this queue',
source_sha256={str(p):sha(p) for p in source_paths},code_sha256={str(p):sha(p) for p in sorted(set(code))})
ROOT.mkdir();save(ROOT/'contract.json',c)
print(json.dumps(dict(root=str(ROOT),contract_sha256=sha(ROOT/'contract.json'),synthetic_CPU_s=tests_cpu)))
if __name__=='__main__':main()
+97
View File
@@ -0,0 +1,97 @@
"""One immutable geometry-only exact-event measurement. Never reads labels."""
import argparse
import json
import os
from pathlib import Path
import time
import traceback
import numpy as np
from s2_recovery_supervisor import save
from s3b_runtime import contract, checked, read, sha, restrict_prediction_io
from s3b_graph import SOLVER, edge_geometry, distal_regions, fill_events
def run(root, index):
c = contract(root); spec = c['ten_parts'][index]
dest = root/'parts'/f'part-{index:02d}'/'output'; dest.mkdir(exist_ok=False)
save(dest/'started.json', dict(pid=os.getpid(), case=spec['case'], index=index, unix=time.time(),
solver=SOLVER, authorizing_ruling=c['authorizing_ruling'], labels_read=False))
allowed = list(spec['inputs'])
restrict_prediction_io(allowed, dest)
start = time.monotonic(); cpu = time.process_time(); latest = None
cost = {}; geometry = None
def progress(stage, **kw):
save(dest/'progress.json', dict(stage=stage, case=spec['case'], pid=os.getpid(), unix=time.time(),
worker_CPU_s=time.process_time()-cpu, wall_s=time.monotonic()-start, **kw))
try:
progress('VERIFY_GEOMETRY_ALLOWLIST')
for p, h in spec['inputs'].items(): checked(p, h)
source = Path(spec['preparation_root'])
metadata = read(source/'result.json')
if metadata['base_columns'][5] != 'geodesic_over_Rg':
raise ValueError('Not the original unrestricted geodesic column')
with np.load(source/'geometry.npz', allow_pickle=False) as z:
x=z['points_raw']; tetra=z['tetra']; faces=z['boundary_triangles']
edges=z['edges']; mass=z['node_volume_raw']; raw=z['raw_node_ids']; gate=z['gate_location_raw']
dw = np.load(source/'boundary_distance_raw.npy', allow_pickle=False)
base = np.load(source/'base.npy', allow_pickle=False)
distance = base[:, 5]*metadata['scales']['Rg']; del base
if np.any(np.diff(raw) <= 0): raise ValueError('Original IDs must be increasing')
seed = int(np.argmin(np.linalg.norm(x-gate, axis=1)))
if seed != metadata['base_gate_node']: raise ValueError('Gate source identity differs')
branch_start = time.process_time()
regions = distal_regions(distance, mass, edges, raw)
save(dest/'regions.json', dict(case=spec['case'], definition='strict-geodesic-distal-v0.3',
total_volume=float(mass.sum()), geometry_inputs=spec['inputs'], **regions))
cost['regions_CPU_s'] = time.process_time()-branch_start
def midpoint_progress(done, total):
progress('EXACT_MIDPOINTS', completed=done, total=total)
progress('GEOMETRY_EDGE_CAPACITY')
geometry = edge_geometry(x, tetra, faces, dw, edges, mass, midpoint_progress)
cost.update({k:geometry[k] for k in ['geometry_CPU_s','midpoint_CPU_s']})
np.savez_compressed(dest/'conductance.npz', edges=edges, edge_volume=geometry['edge_volume'],
midpoint_distance=geometry['midpoint'], g=geometry['conductance'],
exact_query_edge_ids=geometry['exact_query_edge_ids'], boundary_edges=geometry['boundary_edges'])
save(dest/'geometry-freeze.json', dict(case=spec['case'], nodes=len(x), total_volume=float(mass.sum()),
exact_midpoint_queries=len(geometry['exact_query_edge_ids']), seed=seed, raw_seed=int(raw[seed]),
boundary_edges=int(geometry['boundary_edges'].sum()), positive_edges=int((geometry['conductance']>0).sum()),
regions_sha256=sha(dest/'regions.json'), conductance_sha256=sha(dest/'conductance.npz'), costs=cost))
progress('EXACT_EVENTS', nodes=len(x), events=0, wetted_nodes=1)
last_progress = -1.
event_start = time.process_time()
with (dest/'events.jsonl').open('x', buffering=1) as stream:
def event(row):
stream.write(json.dumps(row, allow_nan=False)+'\n')
def state(row, remaining, arrival):
nonlocal latest, last_progress
latest = (row, remaining, arrival)
now = time.monotonic()
if row['events'] <= 2 or now-last_progress >= 1:
progress('EXACT_EVENTS', event_state=row)
last_progress = now
arrival, remaining, result = fill_events(edges, geometry['conductance'], mass, seed, event, state)
cost['events_CPU_s'] = time.process_time()-event_start
np.savez_compressed(dest/'event-field.npz', raw_ids=raw, arrival=arrival, remaining=remaining, mass=mass)
save(dest/'result.json', dict(case=spec['case'], index=index, nodes=len(x),
exact_midpoint_queries=len(geometry['exact_query_edge_ids']), **result, costs=cost,
labels_read=False, GPU=False, new_fits=0, event_batching=False, solver=SOLVER,
worker_CPU_s=time.process_time()-cpu, wall_s=time.monotonic()-start,
output_sha256={p.name:sha(p) for p in dest.iterdir() if p.is_file() and p.name!='progress.json'}))
progress(result['status'], event_state=result)
return 0
except Exception as exc:
if latest is not None:
state, remaining, arrival = latest
np.savez_compressed(dest/'last-trusted-state.npz', remaining=remaining, arrival=arrival)
else: state = None
save(dest/'failure.json', dict(status='NUMERICAL_OR_INPUT_FAILURE', case=spec['case'],
type=type(exc).__name__, message=str(exc), traceback=traceback.format_exc(),
last_trusted_state=state, remaining_volume=state['remaining_volume'] if state else None,
remaining_state='KNOWN_LAST_STATE' if state else 'UNKNOWN', costs=cost,
worker_CPU_s=time.process_time()-cpu, wall_s=time.monotonic()-start, retry=False))
raise
if __name__ == '__main__':
parser=argparse.ArgumentParser();parser.add_argument('root', type=Path);parser.add_argument('index', type=int)
args=parser.parse_args();raise SystemExit(run(args.root,args.index))
+73
View File
@@ -0,0 +1,73 @@
"""Sole sequential fixed-ten cost measurement, never retries or batches events."""
import argparse
import fcntl
import os
from pathlib import Path
import resource
import signal
import sys
import time
import psutil
from s2_recovery_supervisor import save, supervise, stop_group
from s2_recovery_monitoring import disk_usage
from s3b_runtime import contract, read, sha, reserve_ok
def run(root):
lock=(root/'batch.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
c=contract(root);lim=c['limits']
if (root/'started.json').exists(): raise FileExistsError('Never restart this ten-part attempt')
os.sched_setaffinity(0,c['coordinator_cpus'])
save(root/'started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json'),
code_freeze=read(root/'code-freeze.json'),stage='FIXED_TEN',label_reads=0))
interrupted=False
def stop(*_):
nonlocal interrupted
interrupted=True
for child in psutil.Process(os.getpid()).children(): stop_group(child.pid)
signal.signal(signal.SIGTERM,stop);signal.signal(signal.SIGINT,stop)
start=time.monotonic();done=[];reason=None;active=None
try:
for index,spec in enumerate(c['ten_parts']):
contract(root)
spent=c['prior_synthetic_worker_CPU_s']+sum(r['worker']['cpu_seconds'] for r in done)
if interrupted: reason='COORDINATOR_INTERRUPTED';break
if not reserve_ok(spent,lim['part_CPU_s'],lim['ten_CPU_s']):reason='TEN_FULL_JOB_RESERVATION';break
if disk_usage(root)>=lim['ten_disk_bytes']:reason='TEN_DISK_LIMIT';break
dest=root/'parts'/f'part-{index:02d}';dest.mkdir(parents=True,exist_ok=False)
active=index
save(root/'progress.json',dict(stage='FIXED_TEN_RUNNING',active_index=index,case=spec['case'],
completed=len(done),settled_worker_CPU_s=spent,elapsed_s=time.monotonic()-start))
w=supervise(['taskset','-c',str(c['worker_cpu']),sys.executable,'tools/run_s3b_part.py',str(root),str(index)],
dest,'worker',dict(total_cpu_seconds=lim['part_CPU_s']+1,job_cpu_seconds=lim['part_CPU_s'],
job_wall_seconds=lim['part_wall_s'],tree_rss_bytes=lim['part_RSS_bytes'],
disk_bytes=lim['ten_disk_bytes']-disk_usage(root),max_processes=1),poll=.2)
result=dest/'output/result.json';failure=dest/'output/failure.json'
receipt=dict(index=index,case=spec['case'],worker=w,
result_path=str(result) if result.exists() else None,result_sha256=sha(result) if result.exists() else None,
failure_path=str(failure) if failure.exists() else None,failure_sha256=sha(failure) if failure.exists() else None)
save(dest/'guard-result.json',receipt);done.append(receipt);active=None
print(f'S3B_TEN_TERMINAL index={index} case={spec["case"]} status={w["status"]}',flush=True)
if w['monitor_errors']:reason='MONITOR_ERRORS';break
if w['status']!='PASS':reason=w['stop_reason'] or 'WORKER_NUMERICAL_OR_INPUT_FAILURE';break
if not result.exists() or read(result)['status'] not in ('COMPLETE','BLOCKED'):
reason='MISSING_TERMINAL_SCIENTIFIC_RESULT';break
if interrupted:reason='COORDINATOR_INTERRUPTED'
except Exception as exc:
reason='COORDINATOR_EXCEPTION'
save(root/'coordinator-failure.json',dict(type=type(exc).__name__,message=str(exc),active_index=active))
raise
finally:
report=dict(status='TEN_TERMINAL_AWAITING_COST_CENSUS' if reason is None and len(done)==10 else 'TEN_STOPPED',
stop_reason=reason,receipts=done,attempted=len(done),
not_run_cases=[r['case'] for i,r in enumerate(c['ten_parts']) if i not in {v['index'] for v in done}],
worker_CPU_s=c['prior_synthetic_worker_CPU_s']+sum(r['worker']['cpu_seconds'] for r in done),
coordinator_CPU_s=sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),wall_s=time.monotonic()-start,
account_complete=active is None,no_retries=True,labels_read=False,event_batching=False,
note='No full queue launched. A complete ten requires full-count cost census before continuation; no repeat user-go.')
save(root/'complete.json',report);save(root/'progress.json',report)
return 0 if reason is None else 1
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);a=p.parse_args();raise SystemExit(run(a.root))
+200
View File
@@ -0,0 +1,200 @@
"""Fixed S3-B(a) geometry and exact capacity events. No data or label I/O."""
from itertools import combinations
import time
import numpy as np
from scipy.sparse import coo_matrix, diags
from scipy.sparse.csgraph import connected_components
from scipy.sparse.linalg import cg
from boundary_distance import SurfaceDistance
SOLVER = dict(name='scipy.sparse.linalg.cg', preconditioner='Jacobi',
rtol=1e-11, atol=0., maxiter=2000, warm_start=True,
acceptance_residual=1e-8, flux_tolerance=1e-8,
negative_flux_tolerance=1e-10, mass_tolerance=1e-8,
tie_mass_tolerance=1e-12, event_batching=False)
class NumericalFailure(RuntimeError):
pass
def weighted_median(values, mass):
values, mass = np.asarray(values), np.asarray(mass)
if values.shape != mass.shape or not np.isfinite(values).all() or np.any(mass <= 0):
raise ValueError('Invalid weighted median domain')
order = np.argsort(values, kind='stable')
return float(values[order[np.searchsorted(np.cumsum(mass[order]), mass.sum()/2, side='left')]])
def distal_regions(distance, mass, edges, raw_ids):
"""Strict distal induced graph includes original zero-conductance edges."""
n = len(mass)
if not np.isfinite(distance).all():
return dict(status='INVALID_GEODESIC', threshold=None, regions=[])
threshold = weighted_median(distance, mass)
ids = np.flatnonzero(distance > threshold)
local = np.full(n, -1, dtype=np.int64); local[ids] = np.arange(len(ids))
e = edges[(local[edges] >= 0).all(axis=1)]
if not len(ids):
return dict(status='NO_USABLE_DISTAL_PAIR', threshold=threshold, regions=[])
graph = coo_matrix((np.ones(2*len(e)),
(np.r_[local[e[:, 0]], local[e[:, 1]]],
np.r_[local[e[:, 1]], local[e[:, 0]]])),
shape=(len(ids), len(ids))).tocsr()
count, labels = connected_components(graph, directed=False)
groups = [ids[labels == j] for j in range(count)]
groups.sort(key=lambda a: (-float(mass[a].sum()), int(raw_ids[a].min())))
selected = groups[:2]
valid = len(selected) == 2 and all(mass[a].sum() >= .05*mass.sum() for a in selected)
return dict(status='VALID' if valid else 'NO_USABLE_DISTAL_PAIR', threshold=threshold,
distal_volume=float(mass[ids].sum()), distal_components=count,
regions=[dict(local_ids=a.tolist(), raw_ids=raw_ids[a].tolist(),
volume=float(mass[a].sum())) for a in selected])
def edge_geometry(x, tetra, faces, dw, cached_edges, cached_mass, query_progress=None):
if (not np.isfinite(x).all() or not np.isfinite(dw).all() or np.any(dw < 0)
or len(dw) != len(x)):
raise ValueError('Invalid geometry/distance')
start = time.process_time()
cells = x[tetra]
volumes = np.abs(np.linalg.det(cells[:, 1:] - cells[:, :1]))/6
if not np.isfinite(volumes).all() or np.any(volumes <= 0):
raise ValueError('Nonpositive tetrahedron')
mass = np.bincount(tetra.ravel(), weights=np.repeat(volumes/4, 4), minlength=len(x))
if np.any(mass <= 0) or not np.allclose(mass, cached_mass, rtol=1e-12, atol=0):
raise ValueError('Original node capacity differs')
all_edges = np.sort(np.concatenate([tetra[:, [i, j]] for i, j in combinations(range(4), 2)]), axis=1)
edges, inverse = np.unique(all_edges, axis=0, return_inverse=True)
if not np.array_equal(edges, cached_edges):
raise ValueError('Original edge identity differs')
edge_volume = np.bincount(inverse, weights=np.tile(volumes/6, 6), minlength=len(edges))
length = np.linalg.norm(x[edges[:, 1]] - x[edges[:, 0]], axis=1)
if np.any(length <= 0) or not np.isfinite(length).all():
raise ValueError('Invalid edge length')
n = len(x)
wall_edges = np.sort(np.concatenate([faces[:, [0, 1]], faces[:, [0, 2]], faces[:, [1, 2]]]), axis=1)
keys = edges[:, 0].astype(np.int64)*n + edges[:, 1]
wall_keys = np.unique(wall_edges[:, 0].astype(np.int64)*n + wall_edges[:, 1])
is_wall = np.isin(keys, wall_keys)
both_wall = (dw[edges] == 0).all(axis=1)
if not both_wall[is_wall].all():
raise ValueError('Surface edge endpoints not original zero-distance nodes')
midpoint = dw[edges].mean(axis=1)
midpoint[is_wall] = 0.
queries = np.flatnonzero(both_wall & ~is_wall)
geometry_cpu = time.process_time()-start
start = time.process_time()
if len(queries):
surface = SurfaceDistance(x[faces])
for k in range(0, len(queries), 256):
ids = queries[k:k+256]
midpoint[ids] = surface.query(x[edges[ids]].mean(axis=1))
if query_progress:
query_progress(min(k+256, len(queries)), len(queries))
midpoint_cpu = time.process_time()-start
if not np.isfinite(midpoint).all() or np.any(midpoint < 0):
raise NumericalFailure('Invalid midpoint distance')
g = edge_volume/length**2*midpoint**2
if not np.isfinite(g).all() or np.any((midpoint > 0) & (g <= 0)):
raise NumericalFailure('Positive conductance underflow/invalid value')
return dict(mass=mass, edges=edges, edge_volume=edge_volume, midpoint=midpoint, conductance=g,
exact_query_edge_ids=queries, boundary_edges=is_wall,
geometry_CPU_s=geometry_cpu, midpoint_CPU_s=midpoint_cpu)
def pressure_step(adjacency, laplacian, wet, seed, previous, Q=1., solver=cg):
ids = np.flatnonzero(wet)
a = laplacian[ids][:, ids].tocsr()
diagonal = a.diagonal()
if np.any(diagonal <= 0):
raise NumericalFailure('Positive-source pressure matrix is singular')
b = np.zeros(len(ids)); b[np.searchsorted(ids, seed)] = Q
iterations = 0
def callback(_):
nonlocal iterations
iterations += 1
start = time.process_time(); wall = time.monotonic()
p, info = solver(a, b, x0=previous[ids], M=diags(1/diagonal),
rtol=SOLVER['rtol'], atol=SOLVER['atol'],
maxiter=SOLVER['maxiter'], callback=callback)
cpu, elapsed = time.process_time()-start, time.monotonic()-wall
residual = float(np.linalg.norm(a@p-b)/Q)
if info != 0 or not np.isfinite(p).all() or not np.isfinite(residual) or residual > SOLVER['acceptance_residual']:
raise NumericalFailure(f'CG failed: info={info}, iterations={iterations}, residual={residual}')
pressure = np.zeros(len(wet)); pressure[ids] = p
rates = np.asarray(adjacency @ pressure); rates[wet] = 0.
if np.any(rates < -SOLVER['negative_flux_tolerance']*Q):
raise NumericalFailure('Negative front flux exceeds accepted tolerance')
negative_roundoff = float(-rates[rates < 0].sum())
rates[rates < 0] = 0.
imbalance = float(abs(rates.sum()-Q)/Q)
if imbalance > SOLVER['flux_tolerance']:
raise NumericalFailure(f'Flux balance {imbalance} exceeds tolerance')
return pressure, rates, dict(iterations=iterations, pressure_residual=residual,
flux_imbalance=imbalance, negative_flux_roundoff=negative_roundoff,
solve_CPU_s=cpu, solve_wall_s=elapsed, wetted_nodes=len(ids), matrix_nnz=a.nnz)
def fill_events(edges, g, mass, seed, event_callback=None, state_callback=None, Q=1., solver=cg):
"""One pressure solve per exact event; simultaneous capacity ties only."""
n = len(mass); M = float(mass.sum())
if not np.isfinite(mass).all() or np.any(mass <= 0) or not np.isfinite(g).all() or np.any(g < 0) or Q <= 0:
raise ValueError('Invalid event domain')
positive = g > 0
scale = float(g.max()) if positive.any() else 1.
gn = g[positive]/scale
if np.any(gn <= 0):
raise NumericalFailure('Conductance normalization underflow')
e = edges[positive]
adj = coo_matrix((np.tile(gn, 2), (np.r_[e[:, 0], e[:, 1]], np.r_[e[:, 1], e[:, 0]])), shape=(n, n)).tocsr()
lap = diags(np.asarray(adj.sum(axis=1)).ravel()) - adj
remaining = np.asarray(mass, float).copy(); remaining[seed] = 0.
wet = np.zeros(n, bool); wet[seed] = True
arrival = np.full(n, np.nan); arrival[seed] = 0.
pressure = np.zeros(n); clock = 0.; rounding = 0.; events = 0
initial = float(mass[seed]); total_solve = 0.
def state(status):
return dict(status=status, remaining_volume=float(remaining.sum()), total_volume=M,
initial_seed_volume=initial, filled_nodes=int(wet.sum()), events=events,
graph_time=clock, cumulative_rounding_volume=rounding,
conductance_normalization=scale, solve_CPU_s=total_solve)
if state_callback: state_callback(state('INITIALIZED'), remaining, arrival)
while not wet.all():
front_counts = np.asarray(adj @ wet.astype(float)); front_counts[wet] = 0.
if not (front_counts > 0).any():
return arrival, remaining, state('BLOCKED')
event_cpu = time.process_time()
pressure, rates, diagnostic = pressure_step(adj, lap, wet, seed, pressure, Q, solver)
active = rates > 0
if not active.any():
raise NumericalFailure('Positive graph frontier but no positive numerical flow')
dt = float(np.min(remaining[active]/rates[active]))
if not np.isfinite(dt) or dt <= 0 or clock+dt <= clock:
raise NumericalFailure('Nonpositive/unrepresentable exact event time')
before = float(remaining.sum())
new = remaining - dt*rates
tolerance = SOLVER['tie_mass_tolerance']*M
if np.min(new) < -tolerance:
raise NumericalFailure('Capacity overshoot')
exhausted = (~wet) & active & (new <= tolerance)
if not exhausted.any():
raise NumericalFailure('No capacity exhausted in exact event')
correction = float(np.abs(new[exhausted]).sum())
new[exhausted] = 0.
if abs((before-new.sum())-Q*dt) > SOLVER['mass_tolerance']*M:
raise NumericalFailure('Per-event volume conservation failed')
next_clock = clock+dt
if rounding+correction > SOLVER['mass_tolerance']*M or abs((M-new.sum()-initial)-Q*next_clock) > SOLVER['mass_tolerance']*M:
raise NumericalFailure('Cumulative volume conservation failed')
remaining = new; clock = next_clock; rounding += correction
wet[exhausted] = True; arrival[exhausted] = clock; events += 1
total_solve += diagnostic['solve_CPU_s']
diagnostic.update(event=events, graph_time=clock, delta_time=dt, newly_wet=int(exhausted.sum()),
remaining_volume=float(remaining.sum()), rounding_volume=correction,
front_count=int(active.sum()), split_concentration=float(np.sum((rates/Q)**2)),
event_CPU_s=time.process_time()-event_cpu)
if event_callback: event_callback(diagnostic)
if state_callback: state_callback(state('RUNNING'), remaining, arrival)
if events > n: raise NumericalFailure('Event count exceeds node count')
return arrival, remaining, state('COMPLETE')
+65
View File
@@ -0,0 +1,65 @@
"""Pinned S3-B(a) geometry-only inputs and fail-closed I/O for prediction."""
import hashlib
import json
import os
from pathlib import Path
import sys
ROOT = Path('artifacts/s3b-a-ten-part-2026-11-15')
RULE = '1794741236.468009'
def sha(path):
h = hashlib.sha256()
with open(path, 'rb') as f:
for b in iter(lambda: f.read(1024*1024), b''): h.update(b)
return h.hexdigest()
def read(path):
return json.loads(Path(path).read_text())
def checked(path, expected):
if sha(path) != expected: raise ValueError('Pinned file changed: '+str(path))
return Path(path)
def contract(root):
c = read(Path(root)/'contract.json')
for p, h in {**c['code_sha256'], **c['source_sha256']}.items(): checked(p, h)
freeze = read(Path(root)/'code-freeze.json')
if freeze['contract_sha256'] != sha(Path(root)/'contract.json') or not freeze.get('git_commit'):
raise ValueError('Implementation/contract not Git-frozen')
if c['authorizing_ruling'] != RULE or c['limits']['total_worker_CPU_s'] != 72000:
raise ValueError('Wrong scope/budget')
return c
def restrict_prediction_io(allowed_files, output_root):
"""Python audit guard: exact data-file allowlist, no truth/cache/VTU access.
This is an audited-worker I/O barrier, not a hostile-code OS sandbox. The
pinned code neither invokes subprocesses nor accesses files via ctypes.
"""
allowed = {str(Path(p).resolve()) for p in allowed_files}
output = str(Path(output_root).resolve())
runtimes = [str(Path(sys.prefix).resolve()), str(Path(__file__).resolve().parent)]
def inside(path, directory): return path == directory or path.startswith(directory+os.sep)
def audit(event, args):
if event == 'open':
name, mode, flags = args
if isinstance(name, int): return
path = str(Path(os.fsdecode(name)).resolve())
writing = bool(flags & (os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND))
if writing:
if not inside(path, output): raise PermissionError('Prediction output outside own directory')
elif path not in allowed and not inside(path, output) and not any(inside(path, v) for v in runtimes):
raise PermissionError('Prediction input outside geometry allowlist: '+path)
elif event in ('subprocess.Popen', 'os.system', 'os.exec', 'socket.connect'):
raise PermissionError('Prediction subprocess/network forbidden')
sys.addaudithook(audit)
def reserve_ok(spent, part_cap, stage_cap):
return spent >= 0 and spent+part_cap <= stage_cap
+128
View File
@@ -0,0 +1,128 @@
"""Analytical conservation, symmetry, geometric boundaries and I/O tests."""
from itertools import permutations
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
import numpy as np
from scipy.sparse.linalg import cg
from s3b_graph import fill_events, edge_geometry, distal_regions, NumericalFailure
from s3b_runtime import reserve_ok
class GraphTests(unittest.TestCase):
def test_chain_analytical_times_and_conservation(self):
a,r,s=fill_events(np.array([[0,1],[1,2]]),np.array([2.,3.]),np.array([2.,3.,5.]),0)
np.testing.assert_allclose(a,[0,3,8],rtol=1e-10,atol=1e-12)
self.assertEqual(s['status'],'COMPLETE');self.assertEqual(r.sum(),0)
def test_symmetric_fork_keeps_ties(self):
a,_,s=fill_events(np.array([[0,1],[0,2]]),np.ones(2),np.ones(3),0)
np.testing.assert_allclose(a,[0,2,2]);self.assertEqual(s['events'],1)
def test_asymmetric_fork_and_multiple_wet_inflows(self):
# First branch (g=3) fills at4/3, then remaining1/3 fills underQ=1.
a,_,_=fill_events(np.array([[0,1],[0,2]]),np.array([3.,1.]),np.ones(3),0)
np.testing.assert_allclose(a,[0,4/3,2])
# Diamond: two tied unit-capacity branches, then jointly feed last node.
a,_,_=fill_events(np.array([[0,1],[0,2],[1,3],[2,3]]),np.ones(4),np.ones(4),0)
np.testing.assert_allclose(a,[0,2,2,3])
def test_Q_and_uniform_conductance_scaling(self):
e=np.array([[0,1],[0,2],[1,3],[2,3]]);g=np.array([1.,2.,3.,4.]);m=np.ones(4)
a,_,_=fill_events(e,g,m,0)
b,_,_=fill_events(e,g*7,m,0)
c,_,_=fill_events(e,g,m,0,Q=5)
np.testing.assert_allclose(a,b,rtol=1e-10)
np.testing.assert_allclose(a,5*c,rtol=1e-10)
def test_permutation_and_edge_order(self):
e=np.array([[0,1],[0,2],[1,3],[2,3]]);g=np.ones(4);m=np.ones(4)
a,_,_=fill_events(e,g,m,0)
old_to_new=np.array([2,3,1,0]);nm=np.empty_like(m);nm[old_to_new]=m
b,_,_=fill_events(old_to_new[e[::-1]],g[::-1],nm,int(old_to_new[0]))
np.testing.assert_allclose(a,b[old_to_new],atol=1e-12)
def test_blocked_is_not_full_and_zero_mass_not_removed(self):
a,r,s=fill_events(np.array([[0,1],[1,2]]),np.array([1.,0.]),np.array([1.,2.,4.]),0)
self.assertEqual(s['status'],'BLOCKED');self.assertEqual(s['remaining_volume'],4)
self.assertTrue(np.isnan(a[2]));self.assertEqual(r[2],4)
_,r,s=fill_events(np.array([[0,1]]),np.array([0.]),np.ones(2),0)
self.assertEqual(s['events'],0);self.assertEqual(r.sum(),1)
def test_bad_pressure_is_numerical_not_blocked(self):
def broken(a,b,**kw):return np.zeros_like(b),1
with self.assertRaises(NumericalFailure):
fill_events(np.array([[0,1]]),np.ones(1),np.ones(2),0,solver=broken)
def test_solver_tolerance_not_silently_repaired(self):
def biased(a,b,**kw):
p,info=cg(a,b,**kw);return p*1.01,info
with self.assertRaises(NumericalFailure):
fill_events(np.array([[0,1]]),np.ones(1),np.ones(2),0,solver=biased)
def test_single_all_wall_tet_stays_zero(self):
x=np.array([[0.,0,0],[1,0,0],[0,1,0],[0,0,1]])
t=np.array([[0,1,2,3]]);f=np.array([[0,1,2],[0,1,3],[0,2,3],[1,2,3]])
e=np.array([[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]])
v=edge_geometry(x,t,f,np.zeros(4),e,np.ones(4)/24)
np.testing.assert_array_equal(v['conductance'],0)
self.assertAlmostEqual(v['edge_volume'].sum(),1/6)
_,_,s=fill_events(e,v['conductance'],v['mass'],0)
self.assertEqual(s['status'],'BLOCKED');self.assertAlmostEqual(s['remaining_volume'],1/8)
def test_cross_cube_midpoint_positive_wall_edges_exact_zero(self):
x=np.array([[i&1,(i>>1)&1,(i>>2)&1] for i in range(8)],float)
t=[]
for p in permutations([1,2,4]): t.append([0,p[0],p[0]+p[1],7])
t=np.array(t)
from s2_models.features import mesh_geometry
_,_,_,vol,m,e,_=mesh_geometry(x,t)
fs=np.sort(np.concatenate([t[:,[0,1,2]],t[:,[0,1,3]],t[:,[0,2,3]],t[:,[1,2,3]]]),axis=1)
unique,count=np.unique(fs,axis=0,return_counts=True);f=unique[count==1]
v=edge_geometry(x,t,f,np.zeros(8),e,m)
diagonal=np.flatnonzero((e==[0,7]).all(axis=1))[0]
self.assertAlmostEqual(v['midpoint'][diagonal],.5)
self.assertGreater(v['conductance'][diagonal],0)
np.testing.assert_array_equal(v['conductance'][v['boundary_edges']],0)
self.assertAlmostEqual(v['edge_volume'].sum(),1)
def test_strict_median_layer_and_original_graph(self):
d=np.array([0.,1.,1.,2.,2.]);m=np.ones(5);ids=np.arange(5)
e=np.array([[0,1],[0,2],[1,2],[1,3],[2,4]])
r=distal_regions(d,m,e,ids)
self.assertEqual(r['threshold'],1);self.assertEqual(r['status'],'VALID')
self.assertEqual([v['local_ids'] for v in r['regions']],[[3],[4]])
# Original edge3-4 must connect even if a future solver gives itg=0.
r=distal_regions(d,m,np.vstack([e,[3,4]]),ids)
self.assertEqual(r['status'],'NO_USABLE_DISTAL_PAIR')
def test_full_job_reservation(self):
self.assertTrue(reserve_ok(9000,1800,10800))
self.assertFalse(reserve_ok(9000.01,1800,10800))
def test_prediction_cannot_open_label_or_other_data(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);(root/'geometry').write_text('ok');(root/'full-node-labels.npz').write_text('secret')
(root/'out').mkdir()
script="""from pathlib import Path
from s3b_runtime import restrict_prediction_io
import sys
r=Path(sys.argv[1]);restrict_prediction_io([r/'geometry'],r/'out')
assert (r/'geometry').read_text()=='ok'
try:(r/'full-node-labels.npz').read_bytes()
except PermissionError:pass
else:raise AssertionError('label read permitted')
try:(r/'geometry').write_text('changed')
except PermissionError:pass
else:raise AssertionError('source write permitted')
(r/'out'/'receipt').write_text('barrier passed')
"""
env=dict(os.environ,PYTHONPATH=str(Path(__file__).resolve().parent))
subprocess.run([sys.executable,'-c',script,tmp],env=env,check=True)
self.assertEqual((root/'out'/'receipt').read_text(),'barrier passed')
if __name__=='__main__': unittest.main(verbosity=2)