Add P0 infrastructure for the Volve-DIA benchmark

Set up the data, parsing and quality-control layer for a public benchmark
on the Volve daily drilling reports (DDR) and WITSML real-time data.

- Data manifest with SHA-256 hashes of the three Volve subtrees in use.
- DDR XML parser into DuckDB (1,759 reports, 26 wellbores, 23,447
  activities, 17 tables) with locked expected counts.
- Render QC of the publisher HTML against the XML (272,544 items).
- OCR client for the shared chandra vLLM service, with a page cache keyed
  on model, prompt hash, dpi, max_tokens and temperature, and OCR QC
  against the HTML on a 26-report pilot.
- Run logging (scripts/runlog.sh, logs/index.csv), the P0 runner and
  40 tests.
- Research plan, technical overview and progress page (in Vietnamese).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-29 12:45:34 +00:00
commit a3c175638f
172 changed files with 145856 additions and 0 deletions

401
volve_dia/runlog.py Normal file
View File

@@ -0,0 +1,401 @@
"""Log and runtime recording for every run.
python -m volve_dia.runlog [-n NAME] [--note "..."] [--] <command> [args...]
python -m volve_dia.runlog ls [-k 30] # most recent runs + runs in progress
python -m volve_dia.runlog reindex # rebuild logs/index.csv from the meta.json files
Each run creates `logs/runs/<YYYYmmdd-HHMMSS>_<name>/` (root overridable via VOLVE_DIA_LOGS):
log.txt merged stdout + stderr, including child workers (ProcessPool); each line carries the elapsed time [h:mm:ss]
meta.json command, cwd, git commit + dirty state + source hash, thread/GPU variables, device, start/end,
wall/CPU time, peak RSS, peak VRAM of the process tree, exit code; written at start with status=running
and appends one row to `logs/index.csv`. A `.py` file at the head of the command is run with the current python.
For nested calls (RUNLOG_DIR already set, e.g. the individual steps of scripts/run_p0.sh), the child step is placed
inside the parent run's directory, and the `parent` column of the index points to the parent run.
"""
from __future__ import annotations
import argparse
import csv
import datetime as dt
import hashlib
import json
import os
import platform
import re
import shlex
import signal
import socket
import subprocess
import sys
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",
"device", "git", "dirty", "code_sha", "source", "cmd"]
ENV_KEYS = ["CUDA_VISIBLE_DEVICES", "OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS",
"PYTHONHASHSEED", "DEVICE", "WORKERS", "VOLVE_DIA_OUTPUTS", "VOLVE_DIA_VOLVE_ROOT"]
CODE_DIRS = ["volve_dia", "scripts", "configs", "tests"]
GPU_POLL_S = 15.0
def logs_dir() -> Path:
env = os.environ.get("VOLVE_DIA_LOGS")
return Path(env) if env else REPO_ROOT / "logs"
def now() -> dt.datetime:
return dt.datetime.now().astimezone()
def fmt_wall(s: float | None) -> str:
if s is None:
return ""
h, r = divmod(int(round(s)), 3600)
return f"{h}:{r // 60:02d}:{r % 60:02d}"
def _out(cmd: list[str]) -> str:
try:
return subprocess.run(cmd, capture_output=True, text=True, timeout=20, cwd=REPO_ROOT).stdout.strip()
except (OSError, subprocess.SubprocessError):
return ""
def git_state() -> dict:
"""Commit + working-tree state. Since uncommitted code may also be run, a content hash of the files in
CODE_DIRS (tracked + untracked, excluding ignored files) is recorded to identify the exact code version run."""
st = _out(["git", "status", "--porcelain"]).splitlines()
files = sorted(_out(["git", "ls-files", "-co", "--exclude-standard", *CODE_DIRS]).splitlines())
h = hashlib.sha256()
for f in files:
p = REPO_ROOT / f
if p.is_file():
h.update(f.encode() + b"\0" + p.read_bytes() + b"\0")
return {"commit": _out(["git", "rev-parse", "--short=12", "HEAD"]), "branch": _out(["git", "branch", "--show-current"]),
"dirty": any(not s.startswith("??") for s in st), "n_modified": sum(not s.startswith("??") for s in st),
"n_untracked": sum(s.startswith("??") for s in st), "code_sha256": h.hexdigest()[:16] if files else ""}
def gpu_state() -> list[dict]:
rows = _out(["nvidia-smi", "--query-gpu=index,memory.used,memory.total,utilization.gpu",
"--format=csv,noheader,nounits"])
out = []
for r in rows.splitlines():
try:
i, used, tot, util = (int(x) for x in r.split(","))
except ValueError:
continue
out.append({"index": i, "mem_used_mib": used, "mem_total_mib": tot, "util_pct": util})
return out
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():
try:
if os.getpgid(int(d.name)) == pgid:
pids.add(int(d.name))
except OSError:
pass
return pids
class GpuSampler(threading.Thread):
"""Sample the VRAM of the process tree (same process group as the child process) every GPU_POLL_S seconds."""
def __init__(self, pgid: int):
super().__init__(daemon=True)
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
while not self.stop.wait(wait):
wait = GPU_POLL_S
rows = _out(["nvidia-smi", "--query-compute-apps=pid,used_memory", "--format=csv,noheader,nounits"])
if not rows:
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
if measured:
self.peak = max(self.peak or 0, tot)
def default_name(cmd: list[str]) -> str:
for a in cmd:
m = re.search(r"(\d\d_\w+)\.py$", a) or re.search(r"(run_p\d+)\.sh$", a)
if m:
return m.group(1)
if "pytest" in cmd:
return "pytest"
return re.sub(r"\W+", "_", Path(cmd[0]).stem) or "run"
def device_of(cmd: list[str]) -> str:
for i, a in enumerate(cmd):
if a == "--device" and i + 1 < len(cmd):
return cmd[i + 1]
if a.startswith("--device="):
return a.split("=", 1)[1]
return os.environ.get("DEVICE", "")
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), 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="", 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:
g = meta.get("git", {})
return {"run_id": meta["run_id"], "parent": meta.get("parent") or "", "name": meta["name"], "status": meta["status"],
"exit_code": "" if meta.get("exit_code") is None else meta["exit_code"], "start": meta.get("start") or "",
"end": meta.get("end") or "", "wall_s": "" if meta.get("wall_s") is None else round(meta["wall_s"], 1),
"wall": fmt_wall(meta.get("wall_s")), "device": meta.get("device", ""), "git": g.get("commit", ""),
"dirty": g.get("dirty", ""), "code_sha": g.get("code_sha256", ""), "source": meta.get("source", "runlog"),
"cmd": " ⏎ ".join(meta["cmd"].splitlines())}
def new_run_dir(name: str, start: dt.datetime) -> tuple[Path, str, str | None]:
parent = os.environ.get("RUNLOG_DIR")
if parent and Path(parent).is_dir():
k = sum(1 for p in Path(parent).iterdir() if p.is_dir()) + 1
while any(Path(parent).glob(f"{k:02d}_*")):
k += 1
d = Path(parent) / f"{k:02d}_{name}"
return d, f"{Path(parent).name}/{d.name}", os.environ.get("RUNLOG_ID")
base = logs_dir() / "runs" / f"{start:%Y%m%d-%H%M%S}_{name}"
d, k = base, 1
while d.exists(): # two runs started in the same second
k += 1
d = base.with_name(f"{base.name}-{k}")
return d, d.name, None
class Tee:
"""Write the child process bytes to the terminal (verbatim) and to log.txt (prefixing each line with [h:mm:ss])."""
def __init__(self, path: Path, t0: float, stamp: bool):
self.f, self.t0, self.stamp, self.bol, self.echo = open(path, "ab"), t0, stamp, True, True
def write(self, b: bytes) -> None:
if self.echo:
try:
sys.stdout.buffer.write(b)
sys.stdout.buffer.flush()
except (BrokenPipeError, ValueError): # terminal/pipe closed: keep writing to log.txt
self.echo = False
if self.stamp:
parts = b.split(b"\n")
out = []
for i, p in enumerate(parts):
if self.bol and (p or i < len(parts) - 1):
out.append(f"[{fmt_wall(time.time() - self.t0)}] ".encode())
self.bol = False
out.append(p)
if i < len(parts) - 1:
out.append(b"\n")
self.bol = True
b = b"".join(out)
self.f.write(b)
self.f.flush()
def note(self, s: str) -> None:
self.f.write(f"# {s}\n".encode())
self.f.flush()
def run(cmd: list[str], name: str | None, note: str, stamp: bool) -> int:
if cmd and cmd[0].endswith(".py"):
cmd = [sys.executable, *cmd]
name = re.sub(r"[^\w.-]+", "_", name or default_name(cmd))
start = now()
rdir, run_id, parent = new_run_dir(name, start)
rdir.mkdir(parents=True)
t0 = time.time()
meta = {"run_id": run_id, "parent": parent, "name": name, "note": note, "status": "running", "exit_code": None,
"cmd": shlex.join(cmd), "argv": cmd, "cwd": os.getcwd(), "start": start.isoformat(timespec="seconds"),
"end": None, "wall_s": None, "device": device_of(cmd), "host": socket.gethostname(),
"user": os.environ.get("USER", ""), "launcher_pid": os.getpid(), "python": platform.python_version(),
"env": {k: os.environ[k] for k in ENV_KEYS if k in os.environ}, "git": git_state(),
"gpu_start": gpu_state(), "source": "runlog"}
write_json(rdir / "meta.json", meta)
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", "PYTHONUTF8": "1"}
try:
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
got = []
def forward(sig, _frame): # Ctrl-C / kill: forward to the whole child process group and record it
got.append(signal.Signals(sig).name)
if child is not None:
try:
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
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:
sampler = GpuSampler(child.pid)
sampler.start()
fd = child.stdout.fileno()
while True:
try:
b = os.read(fd, 65536)
except InterruptedError:
continue
if not b:
break
tee.write(b)
code = child.wait()
sampler.stop.set()
else:
code = 127
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) 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)")
append_index(index_row(meta))
print(f"[runlog] {status} exit {code} wall {fmt_wall(wall)} -> {rdir}", file=sys.stderr, flush=True)
return code if code >= 0 else 128 - code
def all_metas(root: Path) -> list[dict]:
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"]))
def reindex() -> None:
root = logs_dir()
metas = [m for m in all_metas(root) if m.get("status") != "running"]
(root / "index.csv").unlink(missing_ok=True)
for m in metas:
append_index(index_row(m), root)
print(f"{len(metas)} rows -> {root / 'index.csv'}")
def ls(k: int) -> None:
root = logs_dir()
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
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
rows.append(index_row(meta))
rows = rows[-k:]
cols = ["run_id", "status", "exit_code", "start", "wall", "device", "cmd"]
w = {c: min(60, max([len(c)] + [len(str(r[c])) for r in rows])) for c in cols}
print(" ".join(c.ljust(w[c]) for c in cols))
for r in rows:
print(" ".join(str(r[c])[:w[c]].ljust(w[c]) for c in cols))
def main(argv: list[str] | None = None) -> int:
argv = sys.argv[1:] if argv is None else argv
if argv[:1] == ["ls"]:
ap = argparse.ArgumentParser(prog="python -m volve_dia.runlog ls")
ap.add_argument("-k", type=int, default=30)
ls(ap.parse_args(argv[1:]).k)
return 0
if argv == ["reindex"]:
reindex()
return 0
ap = argparse.ArgumentParser(prog="python -m volve_dia.runlog", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("-n", "--name", help="run name (default: script name, e.g. 02_parse_ddr)")
ap.add_argument("--note", default="", help="free-text note stored in meta.json")
ap.add_argument("--no-stamp", action="store_true", help="do not prefix log.txt lines with [h:mm:ss]")
ap.add_argument("cmd", nargs=argparse.REMAINDER)
a = ap.parse_args(argv)
cmd = a.cmd[1:] if a.cmd[:1] == ["--"] else a.cmd
if not cmd:
ap.error("missing command to run")
return run(cmd, a.name, a.note, not a.no_stamp)
if __name__ == "__main__":
sys.exit(main())