"""Resume frozen P3 inference, tolerating transient locks on dashboard files only. This post-run operational adapter changes no registered source, protocol, checkpoint, prediction formula, or gate. The original WinError 5 is retained in the failed run log. Completed volume rows are checked for bytewise preservation. """ from __future__ import annotations import argparse import hashlib import json import os import sys import time from datetime import datetime from pathlib import Path for key in ('OMP_NUM_THREADS', 'MKL_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'NUMBA_NUM_THREADS'): os.environ.setdefault(key, '2') os.environ.setdefault('PYTHONUTF8', '1') os.environ.setdefault('CUBLAS_WORKSPACE_CONFIG', ':4096:8') def row_digest(root: Path, rows: list[int]) -> str: import numpy as np h = hashlib.sha256() for name in ('mean.npy', 'sigma.npy'): arr = np.load(root/name, mmap_mode='r') for i in rows: h.update(arr[i].tobytes()) return h.hexdigest() def main() -> None: from ml_porosity.f3 import progress from ml_porosity.f3.protocol import digest, freeze, load_protocol from ml_porosity.paths import outputs_dir parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--device', default='cuda:0') args = parser.parse_args() stamp = freeze(check=True) root = outputs_dir()/'p3' rows = json.loads((root/'volume/state.json').read_text(encoding='utf-8'))['completed_ilines'] before = row_digest(root/'volume', rows) gate_digest = digest(root/'summary/gate_gc.json') original_update = progress.update retry_events = [] dashboard_targets = {(root/n).resolve() for n in ('progress.json', 'progress.js')} def resilient_update(**values): for attempt in range(8): try: return original_update(**values) except PermissionError as exc: destination = getattr(exc, 'filename2', None) or exc.filename if destination is None or Path(destination).resolve() not in dashboard_targets: raise retry_events.append({'time': datetime.now().astimezone().isoformat(), 'attempt': attempt+1, 'error': str(exc)}) time.sleep(0.05*2**min(attempt, 4)) # The JSON is authoritative. An unavailable UI sidecar must not abort # scientific inference; the next inline attempts publication again. print('Dashboard file remains locked; defer UI publication to the next update.', file=sys.stderr, flush=True) return json.loads((root/'progress.json').read_text(encoding='utf-8')) progress.update = resilient_update record = {'started_local': datetime.now().astimezone().isoformat(timespec='seconds'), 'original_failed_run': 'logs/runs/20261028-001548_p3_all', 'reason': 'Windows denied atomic replacement of progress.js after 132 inlines.', 'adapter_sha256': digest(Path(__file__)), 'registered_code_sha256': stamp['code_sha256'], 'protocol_sha256': stamp['protocol_sha256'], 'completed_rows_before': len(rows), 'completed_rows_digest_before': before, 'gate_sha256_before': gate_digest, 'dashboard_retry_events': retry_events, 'scientific_change': False, 'status': 'running'} progress.write_json(root/'volume_recovery.json', record) if os.name == 'nt': import ctypes ctypes.windll.kernel32.SetThreadExecutionState(0x80000001) try: resilient_update(status='Đang tiếp tục volume', error=None, eta_seconds=None, message='Giữ nguyên mô hình và protocol; retry lỗi khóa file dashboard trên Windows.', tasks={'p3-vol': 'doing'}) # Import after installing the operational publisher, so the frozen # inference function receives the wrapper without editing its source. from ml_porosity.f3.volume import predict_volume predict_volume(load_protocol(), args.device) assert row_digest(root/'volume', rows) == before, 'Previously completed rows changed' assert digest(root/'summary/gate_gc.json') == gate_digest, 'G-C verdict changed' freeze(check=True) record |= {'status': 'complete', 'completed_rows_preserved': True, 'gate_preserved': True, 'frozen_code_data_environment_match': True} resilient_update(status='P3 đã hoàn tất', error=None, eta_seconds=None, message='LOWO, ablation, diagnostics và volume đầy đủ đã xong. G-C không đạt; không đổi ngưỡng hoặc khoảng bất định.') print('Full volume complete. Original rows, G-C and frozen code/data are preserved.', flush=True) except Exception as exc: record |= {'status': 'failed', 'error': str(exc)} raise finally: record['finished_local'] = datetime.now().astimezone().isoformat(timespec='seconds') progress.write_json(root/'volume_recovery.json', record) if os.name == 'nt': ctypes.windll.kernel32.SetThreadExecutionState(0x80000000) if __name__ == '__main__': main()