if extra_name == "rank_islet1_stacks" and getattr(extra_mod, "PROJECT_ROOT", None) != resolved_root: raise RuntimeError("Transitive rank_islet1_stacks PROJECT_ROOT mismatch against requested repo_root") resolved_origins = {} resolved_relpaths = {} for mod_name, mod_obj in sorted(loaded_solver_mods.items()): mod_file = getattr(mod_obj, "__file__", None) if not mod_file: raise RuntimeError(f"Solver module {mod_name!r} has no __file__ provenance") mod_path = Path(mod_file).resolve() if not mod_path.is_relative_to(resolved_root) or not mod_path.is_relative_to(scripts_dir): raise RuntimeError( f"Solver module {mod_name!r} resolved outside requested repo_root: " f"{mod_path} not under {resolved_root}" ) resolved_origins[mod_name] = str(mod_path) resolved_relpaths[mod_name] = mod_path.relative_to(resolved_root).as_posix() sig_params = inspect.signature(fn).parameters if "bed_po2_mmhg" in solve_kwargs and "bed_po2_mmhg" not in sig_params: raise ValueError( f"Route operator {operator_name!r} does not accept boundary-pressure override 'bed_po2_mmhg'" ) source_solver = layer4._solve_3d_oxygen_strict_iip_0019 source_fv_stats = layer4._compute_exact_fv_interface_stats_iip_0019 captured_mins = [] captured_p_beds = [] operand_audits = [] def _fv_spy(*a, **kw): fv_out = source_fv_stats(*a, **kw) captured_mins.append(float(fv_out["fv_harmonic_face_min_mmhg"])) return fv_out def _solve_spy(perm, vmax, *a, **kw): raw_pb = kw.get("p_bed", a[5] if len(a) > 5 else None) if raw_pb is None or isinstance(raw_pb, bool) or not math.isfinite(float(raw_pb)): raise RuntimeError(f"3D FVM solver received invalid p_bed={raw_pb!r}") captured_p_beds.append(float(raw_pb)) if vasc_scale is None: active_u = vmax > 0 if np.any(active_u): smallest_u = np.min(perm[active_u]) islet_u = active_u & (perm == smallest_u) vascular_u = active_u & ~islet_u if np.any(islet_u) and np.any(vascular_u): base_u_list = [float(x) for x in np.unique(vmax[vascular_u])] operand_audits.append({ "scaled": False, "islet_vmax_unchanged": True, "all_vascular_vmax_strictly_greater_than_base": False, "all_vascular_voxels_satisfy_min_exact_scale_ratio": True, "base_to_scaled_vascular_vmax_pairs_hex": [[x.hex(), x.hex()] for x in base_u_list], "islet_voxel_count": int(np.sum(islet_u)), "vascular_voxel_count": int(np.sum(vascular_u)), }) return source_solver(perm, vmax, *a, **kw) active = vmax > 0 smallest_active_perm = np.min(perm[active]) islet = active & (perm == smallest_active_perm) vascular = active & ~islet if not np.any(islet) or not np.any(vascular): raise ValueError("Expected distinct active islet and stromal/vascular voxels") scaled_vasc = vmax[vascular] * float(vasc_scale) if min_exact_scale_ratio is not None: for base_u in np.unique(vmax[vascular]): bf = float(base_u) sf = float(bf * float(vasc_scale)) req_v = Fraction(bf) * min_exact_scale_ratio bumped = sf while Fraction(bumped) < req_v: bumped = math.nextafter(bumped, math.inf) if bumped != sf: scaled_vasc = np.where(vmax[vascular] == base_u, bumped, scaled_vasc) scaled_vmax = vmax.copy() scaled_vmax[vascular] = scaled_vasc pairs_hex = [] ratio_ok = True for base_u in np.unique(vmax[vascular]): bf = float(base_u) s_vals = np.unique(scaled_vmax[vascular & (vmax == base_u)]) if len(s_vals) != 1: ratio_ok = False sf_actual = float(s_vals[0]) pairs_hex.append([bf.hex(), sf_actual.hex()]) if min_exact_scale_ratio is not None and Fraction(sf_actual) < Fraction(bf) * min_exact_scale_ratio: ratio_ok = False operand_audits.append({ "scaled": True, "islet_vmax_unchanged": bool(np.array_equal(scaled_vmax[islet], vmax[islet])), "all_vascular_vmax_strictly_greater_than_base": bool(np.all(scaled_vmax[vascular] > vmax[vascular])), "all_vascular_voxels_satisfy_min_exact_scale_ratio": bool(ratio_ok), "base_to_scaled_vascular_vmax_pairs_hex": pairs_hex, "islet_voxel_count": int(np.sum(islet)), "vascular_voxel_count": int(np.sum(vascular)), }) return source_solver(perm, scaled_vmax, *a, **kw) layer4._compute_exact_fv_interface_stats_iip_0019 = _fv_spy layer4._solve_3d_oxygen_strict_iip_0019 = _solve_spy try: res_obj = fn(**solve_kwargs) finally: layer4._compute_exact_fv_interface_stats_iip_0019 = source_fv_stats layer4._solve_3d_oxygen_strict_iip_0019 = source_solver if not captured_mins: raise RuntimeError("Native FV interface statistics callback was not invoked during 3D FVM solve") if not captured_p_beds: raise RuntimeError("3D FVM oxygen solver callback was not invoked during solve") if any(pb != expected_p_bed for pb in captured_p_beds): raise RuntimeError( f"3D FVM solver p_bed mismatch: expected {expected_p_bed!r}, observed {captured_p_beds!r}" ) min_face = float(min(captured_mins)) verified_pb = float(captured_p_beds[-1]) out = { "ok": True, "res_obj": res_obj, "face_min_raw_hex": min_face.hex(), "verified_p_bed_hex": verified_pb.hex(), "d_o2_islet_tissue_cm2_s_hex": float(layer4.D_O2_ISLET_TISSUE_CM2_S).hex(), "resolved_solver_module_paths": resolved_origins, "resolved_solver_module_relpaths": resolved_relpaths, "vascular_operand_audit": operand_audits[-1] if operand_audits else None, "child_pid": os.getpid(), "child_optimize_flag": int(sys.flags.optimize), } finally: sys.stdout = _REAL_STDOUT _REAL_STDOUT.write(json.dumps(out, allow_nan=False)) _REAL_STDOUT.flush() return 0 if __name__ == "__main__": try: raise SystemExit(_run_worker()) except Exception as exc: err_payload = { "ok": False, "error_type": type(exc).__name__, "error_message": str(exc), } _REAL_STDOUT.write(json.dumps(err_payload, allow_nan=False)) _REAL_STDOUT.flush() raise SystemExit(1) """ def _execute_single_3d_fvm_vascular_scaled_solve_with_meta( openislet_root: Path, route_spec: Dict[str, Any], *, vasc_scale: float | None = None, min_exact_scale_ratio: Fraction | None = None, ) -> Tuple[Dict[str, Any], float, float]: """ Invoke the exact read-only OpenIslet 3D FVM operator for `route_spec` with optional vascular-voxel-only OCR scaling and explicit boundary-pressure (`bed_po2_mmhg`) enforcement inside an **isolated child Python subprocess** bound strictly to `openislet_root.resolve() / "scripts"`. NEVER mutates parent `sys.path`, `sys.modules`, or `run_layer4_tissue_and_metabolic_twin` callbacks so concurrent raw native Layer-4 callers AND sequential cross-root calls against distinct repo copies remain 100% isolated (R18-B1 + R18-B2). Returns `(res_obj, native_unrounded_face_min_mmhg, verified_solver_p_bed_mmhg)` with verified isolated solver provenance attached under `res_obj["_nw08_isolated_solver_meta"]`. """ resolved_root = Path(openislet_root).resolve() scripts_dir = (resolved_root / "scripts").resolve() if not scripts_dir.is_dir(): raise ValueError(f"Requested openislet_root scripts directory does not exist: {scripts_dir}") fam = str(route_spec["route_family"]) if fam not in ("R1", "R2", "R3P"): raise ValueError(f"Unknown route_family: {fam!r}") solve_kwargs = dict(route_spec["kwargs"]) expected_p_bed = float(solve_kwargs.get("bed_po2_mmhg", route_spec["p_bed_mmhg"])) float_hex_map = { k: float(v).hex() for k, v in solve_kwargs.items() if isinstance(v, float) and not isinstance(v, bool) } child_req = { "repo_root": str(resolved_root), "route_family": fam, "operator_name": str(route_spec.get("operator_name") or ""), "solve_kwargs": solve_kwargs, "solve_kwargs_float_hex": float_hex_map, "expected_p_bed_hex": expected_p_bed.hex(), "vasc_scale_hex": None if vasc_scale is None else float(vasc_scale).hex(), "min_exact_scale_ratio": ( None if min_exact_scale_ratio is None else [int(min_exact_scale_ratio.numerator), int(min_exact_scale_ratio.denominator)] ), } child_env = dict(os.environ) child_env["PYTHONDONTWRITEBYTECODE"] = "1" child_env.pop("PYTHONPATH", None) child_env.pop("PYTHONSTARTUP", None) cmd = [ sys.executable, *(["-O"] if sys.flags.optimize else []), "-B", "-c", _NW08_ISOLATED_FVM_WORKER_SRC, ] proc = subprocess.run( cmd, input=json.dumps(child_req, allow_nan=False), cwd=str(resolved_root), env=child_env, capture_output=True, text=True, check=False, ) parsed: Dict[str, Any] | None = None if proc.stdout.strip(): try: loaded = json.loads(proc.stdout) if isinstance(loaded, dict): parsed = loaded except json.JSONDecodeError: parsed = None if proc.returncode != 0 or not isinstance(parsed, dict) or parsed.get("ok") is not True: if isinstance(parsed, dict) and parsed.get("ok") is False: err_type = str(parsed.get("error_type") or "RuntimeError") err_msg = str(parsed.get("error_message") or "Isolated 3D FVM solver worker failed") if err_type == "ValueError": raise ValueError(err_msg) raise RuntimeError(f"Isolated 3D FVM solver subprocess error ({err_type}): {err_msg}") raise RuntimeError( f"Isolated 3D FVM solver subprocess failed (rc={proc.returncode}): {proc.stderr.strip() or proc.stdout.strip()}" ) raw_origins = parsed.get("resolved_solver_module_paths") raw_relpaths = parsed.get("resolved_solver_module_relpaths") if not isinstance(raw_origins, dict) or not raw_origins or "run_layer4_tissue_and_metabolic_twin" not in raw_origins: