Complete P3 F3 evaluation and Windows execution

Implement the frozen F3 protocol, nested LOWO, posterior label banks,
ablations, diagnostics, checkpoint validation and full-volume inference.
Record the negative G-C result: improvement at 1/4 wells, coverage80 52.38%
and coverage90 60.91%, with unchanged thresholds and historical P2 results.

Add native Windows logging, the RTX 3060 environment lock, detached runs,
and an audited dashboard-lock recovery that preserves frozen scientific code.
Update report.html, the plan and agent guidance with completed P3 status.
Archive thesis sources under code_thesis with identical Git blobs and record
the original-output audit without committing large data or model artifacts.

Validation: 129 tests passed, 13 skipped; CUDA end-to-end smoke passed;
completion audit verified 1,320 checkpoint/prediction pairs, 28 registration
bundles and all 649 interior volume inlines. Scripts 04 and 09 were not rerun.

Co-authored-by: Codex <codex@openai.com>
This commit is contained in:
2026-10-28 07:01:08 +07:00
parent a22f9d951f
commit 9976abc96b
50 changed files with 2738 additions and 219 deletions

View File

@@ -18,13 +18,11 @@ from __future__ import annotations
import argparse
import csv
import datetime as dt
import fcntl
import hashlib
import json
import os
import platform
import re
import resource
import shlex
import signal
import socket
@@ -34,6 +32,12 @@ import threading
import time
from pathlib import Path
try:
import fcntl
import resource
except ImportError: # Native Windows: neither module exists.
fcntl = resource = None
from .paths import REPO_ROOT
FIELDS = ["run_id", "parent", "name", "status", "exit_code", "start", "end", "wall_s", "wall",
@@ -96,6 +100,13 @@ def gpu_state() -> list[dict]:
def _group_pids(pgid: int) -> set[int]:
if os.name == 'nt':
import psutil
try:
parent = psutil.Process(pgid)
return {pgid, *(p.pid for p in parent.children(recursive=True))}
except (psutil.NoSuchProcess, psutil.AccessDenied):
return set()
pids = set()
for d in Path("/proc").iterdir():
if d.name.isdigit():
@@ -112,7 +123,7 @@ class GpuSampler(threading.Thread):
def __init__(self, pgid: int):
super().__init__(daemon=True)
self.pgid, self.peak, self.stop = pgid, 0, threading.Event()
self.pgid, self.peak, self.stop = pgid, None, threading.Event()
def run(self) -> None:
wait = 2.0 # early first sample so that short jobs still get a reading
@@ -123,13 +134,16 @@ class GpuSampler(threading.Thread):
continue
pids = _group_pids(self.pgid)
tot = 0
measured = False
for r in rows.splitlines():
try:
pid, mem = (int(x) for x in r.split(","))
except ValueError:
continue
measured = True
tot += mem if pid in pids else 0
self.peak = max(self.peak, tot)
if measured:
self.peak = max(self.peak or 0, tot)
def default_name(cmd: list[str]) -> str:
@@ -153,22 +167,41 @@ def device_of(cmd: list[str]) -> str:
def write_json(path: Path, obj: dict) -> None:
tmp = path.with_suffix(".tmp")
tmp.write_text(json.dumps(obj, indent=1, ensure_ascii=False, default=str))
tmp.write_text(json.dumps(obj, indent=1, ensure_ascii=False, default=str), encoding='utf-8')
tmp.replace(path)
def append_index(row: dict, root: Path | None = None) -> None:
root = root or logs_dir()
root.mkdir(parents=True, exist_ok=True)
with open(root / "index.csv", "a+", newline="") as f:
fcntl.flock(f, fcntl.LOCK_EX) # several concurrent runs may write to the index
f.seek(0)
new = not f.read(1)
w = csv.DictWriter(f, FIELDS, extrasaction="ignore")
if new:
w.writeheader()
w.writerow(row)
fcntl.flock(f, fcntl.LOCK_UN)
with open(root / "index.csv", "a+", newline="", encoding='utf-8') as f:
lock = None
if fcntl is not None:
fcntl.flock(f, fcntl.LOCK_EX)
else:
import msvcrt
lock = open(root / '.index.lock', 'a+b')
lock.seek(0, 2)
if lock.tell() == 0:
lock.write(b'0')
lock.flush()
lock.seek(0)
msvcrt.locking(lock.fileno(), msvcrt.LK_LOCK, 1)
try:
f.seek(0)
new = not f.read(1)
w = csv.DictWriter(f, FIELDS, extrasaction="ignore", lineterminator='\n')
if new:
w.writeheader()
w.writerow(row)
f.flush()
finally:
if fcntl is not None:
fcntl.flock(f, fcntl.LOCK_UN)
elif lock is not None:
lock.seek(0)
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1)
lock.close()
def index_row(meta: dict) -> dict:
@@ -248,9 +281,10 @@ def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
tee = Tee(rdir / "log.txt", t0, stamp)
tee.note(f"{run_id} {meta['start']} {meta['cmd']}")
env = os.environ | {"RUNLOG_DIR": str(rdir), "RUNLOG_ID": run_id, "PYTHONUNBUFFERED": "1"}
env = os.environ | {"RUNLOG_DIR": str(rdir), "RUNLOG_ID": run_id, "PYTHONUNBUFFERED": "1", "PYTHONUTF8": "1"}
try:
child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, process_group=0)
group = {'creationflags': subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == 'nt' else {'process_group': 0}
child = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, **group)
except OSError as e:
tee.note(f"failed to launch: {e}")
child = None
@@ -260,11 +294,16 @@ def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
got.append(signal.Signals(sig).name)
if child is not None:
try:
os.killpg(child.pid, sig)
if os.name == 'nt':
child.send_signal(signal.CTRL_BREAK_EVENT) if sig in (signal.SIGINT, signal.SIGBREAK) else child.terminate()
else:
os.killpg(child.pid, sig)
except OSError:
pass
for s in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
signals = [signal.SIGINT, signal.SIGTERM]
signals += [getattr(signal, name) for name in ('SIGHUP', 'SIGBREAK') if hasattr(signal, name)]
for s in signals:
signal.signal(s, forward)
sampler = None
if child is not None:
@@ -283,12 +322,12 @@ def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
sampler.stop.set()
else:
code = 127
ru = resource.getrusage(resource.RUSAGE_CHILDREN)
ru = resource.getrusage(resource.RUSAGE_CHILDREN) if resource is not None else None
wall = time.time() - t0
status = "ok" if code == 0 else ("interrupted" if got or code < 0 else "failed")
meta |= {"status": status, "exit_code": code, "signals": got, "end": now().isoformat(timespec="seconds"),
"wall_s": round(wall, 2), "wall": fmt_wall(wall), "cpu_user_s": round(ru.ru_utime, 1),
"cpu_sys_s": round(ru.ru_stime, 1), "max_rss_mib": round(ru.ru_maxrss / 1024),
"wall_s": round(wall, 2), "wall": fmt_wall(wall), "cpu_user_s": round(ru.ru_utime, 1) if ru else None,
"cpu_sys_s": round(ru.ru_stime, 1) if ru else None, "max_rss_mib": round(ru.ru_maxrss / 1024) if ru else None,
"gpu_peak_mib": sampler.peak if sampler else None, "gpu_end": gpu_state()}
write_json(rdir / "meta.json", meta)
tee.note(f"{status} exit {code} wall {fmt_wall(wall)} ({wall:.1f} s)")
@@ -298,7 +337,7 @@ def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
def all_metas(root: Path) -> list[dict]:
metas = [json.loads(m.read_text()) for m in [*(root / "runs").glob("*/meta.json"), *(root / "runs").glob("*/*/meta.json")]]
metas = [json.loads(m.read_text(encoding='utf-8')) for m in [*(root / "runs").glob("*/meta.json"), *(root / "runs").glob("*/*/meta.json")]]
return sorted(metas, key=lambda m: (m.get("start") or m.get("end") or "", m["run_id"]))
@@ -313,12 +352,16 @@ def reindex() -> None:
def ls(k: int) -> None:
root = logs_dir()
rows = list(csv.DictReader(open(root / "index.csv"))) if (root / "index.csv").exists() else []
rows = list(csv.DictReader(open(root / "index.csv", encoding='utf-8'))) if (root / "index.csv").exists() else []
done = {r["run_id"] for r in rows}
for meta in all_metas(root):
if meta["run_id"] in done or meta.get("status") != "running":
continue
alive = Path(f"/proc/{meta.get('launcher_pid')}").exists()
if os.name == 'nt':
import psutil
alive = psutil.pid_exists(meta.get('launcher_pid', -1))
else:
alive = Path(f"/proc/{meta.get('launcher_pid')}").exists()
meta["status"] = "running" if alive else "lost" # launcher killed with -9 / machine rebooted
start = dt.datetime.fromisoformat(meta["start"])
meta["wall_s"] = (now() - start).total_seconds() if alive else None