Files
ML-Porosity/tests/test_runlog.py
lamlvh cee2ff0859 P2 diagnosis on dev, P3 dev experiments, lock protocol_p3
- P2: SMC tie posterior (numpy + torch), RML/soft-DTW losses, bank training,
  D2 synthetic generator, scripts 09-13, protocol_p2 (locked) and its outcome
  (G-B failed; H1 not rejected, H3 rejected, H4 not rejected).
- Diagnosis on dev realizations 900/901 only (scripts 14-17, run_p3_dev.sh):
  posterior screen, SMC stability (P = 1024, K = 1), sigma_a misspecification
  stress and training, H3 with the SMC posterior, F3 placement on sigma_post.
- protocol_p3: H2 split into H2a (posterior-mean labels vs point ties) and
  H2b (RML vs posterior mean as a function of sigma_post); H3 descriptive only;
  sigma_a arm; new D2 config d2_synth_p3.yaml; main grid on realizations 8-15.
  Locked by configs/protocol_p3.sha256 and tag protocol-p3.
- runlog: per-run logs and runtime index (logs/index.csv).
- Docs: plan §12 items 10-11, theory, technical overview, report; wording
  aligned with Gunning & Glinsky (2006): the tie posterior is not claimed as new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 06:03:33 +00:00

71 lines
3.2 KiB
Python

"""ml_porosity.runlog: the log captures child workers, meta/index record the correct status, nested runs, signal forwarding."""
import csv
import json
import os
import signal
import subprocess
import sys
import time
from pathlib import Path
from ml_porosity.paths import REPO_ROOT
CHILD = ("import subprocess, sys; print('out-parent'); print('err-parent', file=sys.stderr); "
"subprocess.run([sys.executable, '-c', 'print(\"out-child\")']); sys.exit(int(sys.argv[1]))")
def launch(tmp: Path, *args: str, env: dict | None = None, **kw) -> subprocess.Popen:
env = {k: v for k, v in os.environ.items() if not k.startswith("RUNLOG_")} | {"ML_POROSITY_LOGS": str(tmp)} | (env or {})
return subprocess.Popen([sys.executable, "-m", "ml_porosity.runlog", *args], cwd=REPO_ROOT, env=env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **kw)
def runs(tmp: Path) -> list[Path]:
return sorted((tmp / "runs").iterdir())
def test_log_meta_index(tmp_path):
p = launch(tmp_path, "-n", "demo", "--", sys.executable, "-c", CHILD, "0")
out, _ = p.communicate(timeout=60)
assert p.returncode == 0 and "out-child" in out # still echoed to the terminal
(d,) = runs(tmp_path)
log = (d / "log.txt").read_text()
assert all(s in log for s in ("out-parent", "err-parent", "out-child")) and "[0:00:00] out-parent" in log
meta = json.loads((d / "meta.json").read_text())
assert meta["status"] == "ok" and meta["exit_code"] == 0 and meta["wall_s"] >= 0 and meta["git"]["code_sha256"]
(row,) = list(csv.DictReader(open(tmp_path / "index.csv")))
assert row["name"] == "demo" and row["status"] == "ok" and row["parent"] == ""
def test_failure_keeps_exit_code(tmp_path):
p = launch(tmp_path, sys.executable, "-c", CHILD, "3")
p.communicate(timeout=60)
assert p.returncode == 3
meta = json.loads((runs(tmp_path)[0] / "meta.json").read_text())
assert meta["status"] == "failed" and meta["exit_code"] == 3
def test_nested_steps_go_into_parent(tmp_path):
inner = f"{sys.executable} -m ml_porosity.runlog -n step -- {sys.executable} -c 'print(1)'"
p = launch(tmp_path, "-n", "parent", "--", "bash", "-c", f"{inner} && {inner}")
p.communicate(timeout=60)
assert p.returncode == 0
(d,) = runs(tmp_path)
assert sorted(x.name for x in d.iterdir() if x.is_dir()) == ["01_step", "02_step"]
rows = list(csv.DictReader(open(tmp_path / "index.csv")))
assert [r["parent"] for r in rows] == [d.name, d.name, ""]
def test_sigterm_marks_interrupted(tmp_path):
p = launch(tmp_path, sys.executable, "-c", "import time; print('started', flush=True); time.sleep(60)")
t0 = time.time()
while not (tmp_path / "runs").exists() or not any((d / "log.txt").exists() and "started" in (d / "log.txt").read_text()
for d in runs(tmp_path)):
assert time.time() - t0 < 30
time.sleep(0.1)
p.send_signal(signal.SIGTERM)
p.communicate(timeout=30)
meta = json.loads((runs(tmp_path)[0] / "meta.json").read_text())
assert meta["status"] == "interrupted" and meta["signals"] == ["SIGTERM"] and p.returncode == 128 + signal.SIGTERM