"""Diagnostic live-boundary oracle, NOT a production/learned brain backend. Re-execute a fresh parent's exact inputs/old overlay, without calling restore. At the declared epoch boundary compare live state to the sealed parent, replace only existing candidate weights with base+delta-after, and continue the original reference loop. One whitelisted hook is independently removable from its AST. The diagnostic has an explicit within-run boundary switch; old C must NOT load its output as an unchanged-weight checkpoint. """ from __future__ import annotations import ast import copy import hashlib import importlib.util import json from pathlib import Path import sys import numpy as np LAB=Path(__file__).resolve().parent.parent/'olfactory-conditioning-lab-v1' C_SHA='0b8e8e0a6a23a079dc62a88355ce355d53b3ae22f6665519a8f6aef2dcfc5aba' HOOK="if tick == _oracle.boundary_tick:\n _oracle.switch(tick, weights, v, g, ref, counts, ring, apl_ring, apl, out_dir)" def require(ok,message): if not ok:raise ValueError(message) def digest(path): h=hashlib.sha256() with Path(path).open('rb') as stream: for b in iter(lambda:stream.read(8<<20),b''):h.update(b) return h.hexdigest() def load(name,path,sha): raw=Path(path).read_bytes() require(hashlib.sha256(raw).hexdigest()==sha and name not in sys.modules,'Unverified oracle source/module binding') spec=importlib.util.spec_from_file_location(name,path);module=importlib.util.module_from_spec(spec) sys.modules[name]=module;exec(compile(raw,str(path),'exec'),module.__dict__) return module def frozen(): return load('_conditioning_live_oracle_C',LAB/'runtime_continuation.py',C_SHA) def derive_oracle(c,source_bytes): tree,inherited=c.R.derive_ast(source_bytes,'reference');before=copy.deepcopy(tree) loops=[n for n in ast.walk(tree) if isinstance(n,ast.For) and isinstance(n.target,ast.Name) and n.target.id=='tick'] require(len(loops)==1,'Unique frozen timestep loop required') loops[0].body.insert(0,ast.parse(HOOK).body[0]);tree=ast.fix_missing_locations(tree) rollback=copy.deepcopy(tree) matches=[n for n in ast.walk(rollback) if isinstance(n,ast.For) and isinstance(n.target,ast.Name) and n.target.id=='tick'] require(ast.unparse(matches[0].body[0])==HOOK,'Oracle hook changed') del matches[0].body[0] require(c.R._dump(rollback)==c.R._dump(before),'Unlisted oracle mathematical AST edit') return tree,dict(base=inherited,explicit_boundary_hook=HOOK,full_AST_rollback_identical=True, frozen_within_epoch_math_unchanged=True,restore_called=False, diagnostic_live_weight_switch=True,production_backend=False, ast_sha256=hashlib.sha256(c.R._dump(tree).encode()).hexdigest()) def expected_candidate_values(base_si,edge_ids,after_delta): """Base+f32-mV delta with the frozen separate f64 multiply/add contract.""" require(base_si.dtype==np.float64 and base_si.ndim==1 and edge_ids.dtype==np.int64 and edge_ids.ndim==1 and after_delta.dtype==np.float32 and after_delta.shape==edge_ids.shape,'Wrong candidate bridge dtype/shape') require(np.all((edge_ids>=0)&(edge_idsedge_ids[:-1]),'Invalid existing edge IDs') require(np.isfinite(after_delta).all() and np.all(after_delta<=0),'Invalid depression delta') result=base_si[edge_ids].copy();nonzero=after_delta!=np.float32(0) result[nonzero]=np.add(result[nonzero],np.multiply(after_delta[nonzero].astype(np.float64),np.float64(.001))) require(np.isfinite(result).all() and np.all(result>0),'Candidate sign changed') return result def boundary_arrays(parent,tick,v,g,ref,counts,ring,apl_ring,apl_state): require(type(tick)is int and tick==parent['steps']==parent['global_next_tick'] and parent['fresh'] is True, 'Oracle needs the exact fresh-parent boundary') arrays=dict(v=v,g=g,ref=ref,counts=counts,spike_ring=ring,apl_state=apl_state, apl_pending=np.concatenate((apl_ring[tick%18:],apl_ring[:tick%18]),axis=0)) expected={**{k:parent['state'][k] for k in ('v','g','ref','counts')}, **{k:parent['terminal'][k] for k in ('spike_ring','apl_state','apl_pending')}} checks={k:(a.dtype==expected[k].dtype and a.shape==expected[k].shape and a.tobytes()==expected[k].tobytes()) for k,a in arrays.items()} require(all(checks.values()),'Live prefix differs from sealed parent: '+str([k for k,v in checks.items() if not v])) return arrays,checks def runtime_class(c): r=c.R class Oracle(r._Runtime): def __init__(self,*args,boundary,**kwargs): super().__init__(*args,**kwargs);self.boundary=boundary;self.parent=boundary['parent'] self.boundary_tick=self.parent['steps'];self.switches=0 def tensor_sha(self,value): h=hashlib.sha256() for start in range(0,value.numel(),1<<20):h.update(value[start:start+(1<<20)].cpu().numpy().astype('