Просмотр исходного кода

Harden Linux toolchain: PGID timeouts, resource classes, OSS CAD PATH.

Bootstrap verify venv under XDG cache, prefer oss-cad-suite when present,
clear TD library pollution globally, and schedule formal/TD by host memory.

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 месяцев назад
Родитель
Сommit
3396cee47d

+ 9 - 0
docs/toolchain-doctor.md

@@ -0,0 +1,9 @@
+# Linux toolchain doctor
+
+Probe-only entrypoints:
+
+- `tools/doctor.sh` — prefers verify venv, clears `LD_LIBRARY_PATH`, prefers OSS CAD when present
+- `tools/doctor_linux.py` — JSON report (`--json-out`); detects `td2026` via `PATH` only (never `td603` / Windows)
+
+Verify venv path: `$XDG_CACHE_HOME/prod2u/venvs/verify` (default `~/.cache/prod2u/venvs/verify`).
+OSS CAD preference: `$XDG_CACHE_HOME/prod2u/oss-cad-suite/latest/bin` prepended when that directory exists.

+ 14 - 2
tools/bootstrap-linux.sh

@@ -3,12 +3,18 @@
 # Does not reinstall TD. Idempotent.
 set -euo pipefail
 unset LD_LIBRARY_PATH LD_PRELOAD QT_PLUGIN_PATH || true
-export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH:-}"
+export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
 
 ROOT="$(cd "$(dirname "$0")/.." && pwd)"
 CACHE="${XDG_CACHE_HOME:-$HOME/.cache}/prod2u"
 VENV="$CACHE/venvs/verify"
 REQ="$ROOT/tools/requirements-verify.txt"
+OSS_CAD_BIN="${OSS_CAD_SUITE_ROOT:-$CACHE/oss-cad-suite/latest}/bin"
+
+# Prefer OSS CAD when present (download/extract may still be in progress elsewhere).
+if [[ -d "$OSS_CAD_BIN" ]]; then
+  export PATH="$OSS_CAD_BIN:$PATH"
+fi
 
 mkdir -p "$CACHE/venvs" "$CACHE/downloads"
 if [[ ! -f "$REQ" ]]; then
@@ -34,4 +40,10 @@ for pkg in iverilog zip unzip zstd jq; do
 done
 
 echo "PRODU2_VERIFY_VENV=$VENV"
-"$VENV/bin/python" "$ROOT/tools/doctor_linux.py" --json-out "$CACHE/last-doctor.json" | tail -n 30
+LOG_DIR="${PRODU2_TOOLCHAIN_LOG_DIR:-}"
+if [[ -n "$LOG_DIR" ]]; then
+  mkdir -p "$LOG_DIR"
+  "$VENV/bin/python" "$ROOT/tools/doctor_linux.py" --json-out "$LOG_DIR/doctor.json" | tee "$LOG_DIR/doctor.stdout.txt" | tail -n 30
+else
+  "$VENV/bin/python" "$ROOT/tools/doctor_linux.py" --json-out "$CACHE/last-doctor.json" | tail -n 30
+fi

+ 7 - 2
tools/doctor.sh

@@ -1,9 +1,14 @@
 #!/usr/bin/env bash
 set -euo pipefail
 unset LD_LIBRARY_PATH LD_PRELOAD QT_PLUGIN_PATH || true
-export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH:-}"
+export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
+CACHE="${XDG_CACHE_HOME:-$HOME/.cache}/prod2u"
+OSS_CAD_BIN="${OSS_CAD_SUITE_ROOT:-$CACHE/oss-cad-suite/latest}/bin"
+if [[ -d "$OSS_CAD_BIN" ]]; then
+  export PATH="$OSS_CAD_BIN:$PATH"
+fi
 ROOT="$(cd "$(dirname "$0")/.." && pwd)"
-VENV="${PRODU2_VERIFY_VENV:-${XDG_CACHE_HOME:-$HOME/.cache}/prod2u/venvs/verify}"
+VENV="${PRODU2_VERIFY_VENV:-$CACHE/venvs/verify}"
 if [[ -x "$VENV/bin/python" ]]; then
   exec "$VENV/bin/python" "$ROOT/tools/doctor_linux.py" "$@"
 fi

+ 95 - 4
tools/doctor_linux.py

@@ -1,5 +1,10 @@
 #!/usr/bin/env python3
-"""Linux-first toolchain doctor: probe only, never installs."""
+"""Linux-first toolchain doctor: probe only, never installs.
+
+Detects td2026 via PATH (wrapper typically at /usr/local/bin/td2026).
+Prefers OSS CAD at $XDG_CACHE_HOME/prod2u/oss-cad-suite/latest/bin when present.
+Never hard-codes Windows paths or td603.
+"""
 
 from __future__ import annotations
 
@@ -18,6 +23,29 @@ from typing import Any
 ROOT = Path(__file__).resolve().parents[1]
 
 
+def _cache_root() -> Path:
+    return Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "prod2u"
+
+
+def _oss_cad_bin() -> Path:
+    override = os.environ.get("OSS_CAD_SUITE_ROOT")
+    if override:
+        return Path(override) / "bin"
+    return _cache_root() / "oss-cad-suite" / "latest" / "bin"
+
+
+def _prefer_oss_cad_on_path() -> None:
+    """Prepend OSS CAD bin when present so shutil.which prefers it."""
+    oss_bin = _oss_cad_bin()
+    if not oss_bin.is_dir():
+        return
+    current = os.environ.get("PATH", "")
+    prefix = str(oss_bin)
+    parts = current.split(os.pathsep) if current else []
+    if prefix not in parts:
+        os.environ["PATH"] = prefix + (os.pathsep + current if current else "")
+
+
 def _sha256_file(path: Path) -> str | None:
     if not path.is_file():
         return None
@@ -74,7 +102,25 @@ def probe_binary(name: str, version_args: list[str] | None = None) -> dict[str,
     return result
 
 
+def probe_oss_cad() -> dict[str, Any]:
+    oss_bin = _oss_cad_bin()
+    root = oss_bin.parent
+    markers = ["yosys", "sby", "verilator"]
+    present_tools = {
+        name: (oss_bin / name).is_file() for name in markers
+    }
+    return {
+        "name": "oss_cad_suite",
+        "root": str(root),
+        "bin": str(oss_bin),
+        "present": oss_bin.is_dir(),
+        "tools": present_tools,
+        "preferred_on_path": oss_bin.is_dir(),
+    }
+
+
 def probe_td2026() -> dict[str, Any]:
+    # PATH only — typically /usr/local/bin/td2026. Never td603 / Windows paths.
     path = _which("td2026")
     home = Path(os.environ.get("ANLOGIC_TD_HOME", "/data/anlogic/TD_Release_2026.1_SP2_NL"))
     license_path = home / "license" / "Anlogic.lic"
@@ -103,7 +149,7 @@ def probe_td2026() -> dict[str, Any]:
 
 def probe_python_venv(venv: Path) -> dict[str, Any]:
     python = venv / "bin" / "python"
-    result = {
+    result: dict[str, Any] = {
         "name": "verify_venv",
         "path": str(venv),
         "present": python.is_file(),
@@ -116,8 +162,43 @@ def probe_python_venv(venv: Path) -> dict[str, Any]:
     return result
 
 
+def probe_host_resources() -> dict[str, Any]:
+    nproc = os.cpu_count() or 1
+    mem_available_kb: int | None = None
+    try:
+        with open("/proc/meminfo", encoding="utf-8") as handle:
+            for line in handle:
+                if line.startswith("MemAvailable:"):
+                    mem_available_kb = int(line.split()[1])
+                    break
+    except OSError:
+        mem_available_kb = None
+    disk_free_bytes: int | None = None
+    try:
+        disk_free_bytes = shutil.disk_usage("/").free
+    except OSError:
+        disk_free_bytes = None
+    return {
+        "nproc": nproc,
+        "mem_available_kb": mem_available_kb,
+        "mem_available_gib": round(mem_available_kb / (1024 * 1024), 2) if mem_available_kb else None,
+        "disk_free_bytes": disk_free_bytes,
+        "disk_free_gib": round(disk_free_bytes / (1024**3), 2) if disk_free_bytes else None,
+    }
+
+
 def build_report() -> dict[str, Any]:
-    venv = Path(os.environ.get("PRODU2_VERIFY_VENV", str(Path.home() / ".cache/prod2u/venvs/verify")))
+    _prefer_oss_cad_on_path()
+    # Sanitize PATH for probes: keep system + OSS CAD, drop accidental TD lib pollution.
+    for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"):
+        os.environ.pop(key, None)
+
+    venv = Path(
+        os.environ.get(
+            "PRODU2_VERIFY_VENV",
+            str(_cache_root() / "venvs" / "verify"),
+        )
+    )
     tools = [
         probe_binary("python3", ["--version"]),
         probe_binary("git", ["--version"]),
@@ -129,10 +210,13 @@ def build_report() -> dict[str, Any]:
         probe_binary("unzip", ["-v"]),
         probe_binary("zstd", ["--version"]),
         probe_binary("jq", ["--version"]),
+        probe_oss_cad(),
         probe_td2026(),
         probe_python_venv(venv),
     ]
     missing = [item["name"] for item in tools if not item.get("present")]
+    # Core acceptance: python3 + iverilog + td2026. OSS CAD / venv may be degraded.
+    core_missing = [n for n in ("python3", "iverilog", "td2026") if n in missing]
     return {
         "schema": "prod2u-toolchain-doctor-v1",
         "generated_at_utc": datetime.now(timezone.utc).isoformat(),
@@ -141,9 +225,16 @@ def build_report() -> dict[str, Any]:
             "python": sys.version,
             "executable": sys.executable,
         },
+        "host_resources": probe_host_resources(),
+        "path_policy": {
+            "base": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
+            "oss_cad_preferred": str(_oss_cad_bin()),
+            "ld_library_path_cleared": True,
+            "td_command": "td2026",
+        },
         "tools": tools,
         "missing": missing,
-        "status": "pass" if "td2026" not in missing and "python3" not in missing and "iverilog" not in missing else "degraded",
+        "status": "pass" if not core_missing else "degraded",
     }
 
 

+ 4 - 0
tools/requirements-verify.txt

@@ -0,0 +1,4 @@
+pytest>=8
+jsonschema>=4
+psutil>=5
+cocotb>=1.8

+ 190 - 16
tools/run_verification_matrix.py

@@ -3,12 +3,17 @@
 Each lane uses an independent work root and receipt. A failed lane does not
 cancel unrelated lanes. Missing toolchains produce `blocked` or `not_run`, never
 a fabricated pass. Long tasks use tools/run_visible.py for live heartbeat.
+
+Resource classes (light / medium / heavy / exclusive) are derived from host
+nproc, MemAvailable, and free disk. Formal concurrency is memory-capped. TD is
+always exclusive (serialized after open-source lanes, with a lock file).
 """
 from __future__ import annotations
 
 import argparse
 import json
 import os
+import shutil
 import sys
 import time
 import uuid
@@ -33,10 +38,26 @@ DEFAULT_LANES = [
     "formal",
     "td",
 ]
-# TD is exclusive; keep open-source concurrency modest on ~3 GiB hosts.
-DEFAULT_MAX_WORKERS = 2
 TD_EXCLUSIVE = frozenset({"td"})
 
+# Approximate resident budgets used only for concurrency planning (not fake %).
+_CLASS_MEM_KB = {
+    "light": 256 * 1024,
+    "medium": 512 * 1024,
+    "heavy": 1536 * 1024,
+    "exclusive": 2048 * 1024,
+}
+
+LANE_RESOURCE_CLASS: dict[str, str] = {
+    "python": "light",
+    "board_viewer": "light",
+    "icarus": "medium",
+    "cocotb": "medium",
+    "verilator": "heavy",
+    "formal": "heavy",
+    "td": "exclusive",
+}
+
 
 def _utc_now() -> str:
     return datetime.now(timezone.utc).isoformat()
@@ -51,6 +72,100 @@ def _write_json(path: Path, payload: dict[str, Any]) -> None:
     path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
 
 
+def _prefer_oss_cad_on_path() -> None:
+    cache = Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "prod2u"
+    root = Path(os.environ.get("OSS_CAD_SUITE_ROOT", str(cache / "oss-cad-suite" / "latest")))
+    oss_bin = root / "bin"
+    if not oss_bin.is_dir():
+        return
+    prefix = str(oss_bin)
+    current = os.environ.get("PATH", "")
+    parts = current.split(os.pathsep) if current else []
+    if prefix not in parts:
+        os.environ["PATH"] = prefix + (os.pathsep + current if current else "")
+
+
+def host_resources() -> dict[str, Any]:
+    nproc = os.cpu_count() or 1
+    mem_available_kb: int | None = None
+    try:
+        with open("/proc/meminfo", encoding="utf-8") as handle:
+            for line in handle:
+                if line.startswith("MemAvailable:"):
+                    mem_available_kb = int(line.split()[1])
+                    break
+    except OSError:
+        mem_available_kb = None
+    try:
+        disk_free_bytes = shutil.disk_usage("/").free
+    except OSError:
+        disk_free_bytes = None
+    return {
+        "nproc": nproc,
+        "mem_available_kb": mem_available_kb,
+        "disk_free_bytes": disk_free_bytes,
+    }
+
+
+def plan_concurrency(selected: list[str], *, max_workers_cap: int | None = None) -> dict[str, Any]:
+    """Derive open-source worker count from host resources and lane classes.
+
+    - TD (exclusive) never shares the pool; callers run it alone after OSS lanes.
+    - Formal is heavy and memory-capped: at most one formal job when MemAvailable
+      is under ~3.5 GiB, and never more than one formal concurrent with another
+      heavy lane on small hosts.
+    """
+    host = host_resources()
+    nproc = int(host["nproc"] or 1)
+    mem_kb = host["mem_available_kb"]
+    disk_free = host["disk_free_bytes"]
+
+    open_lanes = [lane for lane in selected if lane not in TD_EXCLUSIVE]
+    classes = {lane: LANE_RESOURCE_CLASS.get(lane, "medium") for lane in open_lanes}
+    has_formal = "formal" in open_lanes
+    has_heavy = any(classes[lane] == "heavy" for lane in open_lanes)
+
+    # Disk gate: refuse to oversubscribe if free disk is critically low.
+    disk_ok = disk_free is None or disk_free >= 2 * 1024**3
+
+    if mem_kb is None:
+        # Unknown memory: stay conservative.
+        workers = 1 if has_heavy else min(2, nproc)
+        formal_slots = 1
+    else:
+        # Leave ~512 MiB headroom for the matrix process / OS.
+        usable = max(0, mem_kb - 512 * 1024)
+        if has_formal and mem_kb < 3500 * 1024:
+            formal_slots = 1
+            # On low-memory hosts, do not overlap formal with another heavy lane.
+            workers = 1 if has_heavy else min(2, nproc)
+        else:
+            formal_slots = 1  # formal is always single-flight within this matrix
+            # Pack light/medium/heavy budgets into usable RAM, capped by nproc.
+            budget_workers = max(1, usable // _CLASS_MEM_KB["medium"])
+            workers = max(1, min(nproc, budget_workers, 4))
+            if has_heavy and mem_kb < 2500 * 1024:
+                workers = 1
+
+    if not disk_ok:
+        workers = 1
+
+    if max_workers_cap is not None:
+        workers = max(1, min(workers, max_workers_cap))
+
+    workers = max(1, min(workers, max(1, len(open_lanes))))
+
+    return {
+        "host": host,
+        "open_lanes": open_lanes,
+        "lane_classes": classes,
+        "max_workers": workers,
+        "formal_slots": formal_slots if has_formal else 0,
+        "td_exclusive": bool(any(lane in TD_EXCLUSIVE for lane in selected)),
+        "disk_ok": disk_ok,
+    }
+
+
 def _run_visible_cmd(
     cmd: list[str],
     *,
@@ -63,7 +178,8 @@ def _run_visible_cmd(
 ) -> int:
     # Strip Anlogic libs for non-TD lanes so apt/python stay healthy.
     clean = os.environ.copy()
-    if name != "td":
+    keep_td = name == "td"
+    if not keep_td:
         for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"):
             clean.pop(key, None)
     if env:
@@ -76,6 +192,8 @@ def _run_visible_cmd(
         status_path=status_path,
         name=name,
         timeout_s=timeout_s,
+        heartbeat_s=5.0,
+        keep_td_libs=keep_td,
     )
 
 
@@ -119,6 +237,7 @@ def run_python_unit(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
         "log_path": str(log_path),
         "status_path": str(status_path),
         "report_path": str(receipt_path),
+        "resource_class": LANE_RESOURCE_CLASS["python"],
     }
     _write_json(receipt_path, receipt)
     return receipt
@@ -156,6 +275,7 @@ def run_board_viewer(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]
         "returncode": code,
         "log_path": str(log_path),
         "report_path": str(receipt_path),
+        "resource_class": LANE_RESOURCE_CLASS["board_viewer"],
     }
     _write_json(receipt_path, receipt)
     return receipt
@@ -211,6 +331,7 @@ def _run_harness_lane(
     receipt.setdefault("log_path", str(log_path))
     receipt.setdefault("report_path", str(receipt_path))
     receipt.setdefault("status_path", str(status_path))
+    receipt.setdefault("resource_class", LANE_RESOURCE_CLASS.get(lane, "medium"))
     return receipt
 
 
@@ -246,9 +367,10 @@ def run_td(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
             "verification_run_id": run_id,
             "failures": [f"td_lock_held:{lock_path}"],
             "report_path": str(work_root / "td-receipt.json"),
+            "resource_class": "exclusive",
         }
     try:
-        return _run_harness_lane(
+        receipt = _run_harness_lane(
             repo,
             work_root,
             run_id,
@@ -256,6 +378,8 @@ def run_td(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
             "td-build",
             timeout_s=3600,
         )
+        receipt["resource_class"] = "exclusive"
+        return receipt
     finally:
         try:
             lock_path.unlink(missing_ok=True)
@@ -285,6 +409,31 @@ def _overall_status(results: dict[str, dict[str, Any]], selected: list[str]) ->
     return "fail"
 
 
+def _schedule_open_lanes(open_lanes: list[str], plan: dict[str, Any]) -> list[list[str]]:
+    """Partition open-source lanes into waves respecting memory / formal caps.
+
+    When formal_slots==1 and memory is tight (max_workers==1 with heavy), run
+    heavy lanes (formal, verilator) sequentially. Otherwise run the pool wave
+    first, then any remaining exclusive-within-OSS serialization is handled by
+    max_workers alone.
+    """
+    if not open_lanes:
+        return []
+    workers = int(plan["max_workers"])
+    mem_kb = (plan.get("host") or {}).get("mem_available_kb")
+    # On low-memory hosts: serialize heavy lanes, allow light/medium to share.
+    if workers <= 1 or (mem_kb is not None and mem_kb < 2500 * 1024):
+        light_medium = [lane for lane in open_lanes if LANE_RESOURCE_CLASS.get(lane) in ("light", "medium")]
+        heavy = [lane for lane in open_lanes if LANE_RESOURCE_CLASS.get(lane) == "heavy"]
+        waves: list[list[str]] = []
+        if light_medium:
+            waves.append(light_medium)
+        for lane in heavy:
+            waves.append([lane])
+        return waves or [open_lanes]
+    return [open_lanes]
+
+
 def main() -> int:
     parser = argparse.ArgumentParser(description="Run the verification matrix")
     parser.add_argument("--work-root-prefix", required=True)
@@ -292,9 +441,18 @@ def main() -> int:
     parser.add_argument("--report-file", required=True)
     parser.add_argument("--lanes", default=",".join(DEFAULT_LANES))
     parser.add_argument("--only-lane", help="rerun a single lane")
-    parser.add_argument("--max-workers", type=int, default=DEFAULT_MAX_WORKERS)
+    parser.add_argument(
+        "--max-workers",
+        type=int,
+        default=None,
+        help="Cap open-source concurrency (default: host-resource plan).",
+    )
     args = parser.parse_args()
 
+    for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"):
+        os.environ.pop(key, None)
+    _prefer_oss_cad_on_path()
+
     repo = _repo_root
     run_id = (args.verification_run_id or uuid.uuid4().hex).strip().lower()
     if len(run_id) != 32 or any(c not in "0123456789abcdef" for c in run_id):
@@ -309,12 +467,25 @@ def main() -> int:
         print(f"unknown lanes: {unknown}", file=sys.stderr)
         return 1
 
+    plan = plan_concurrency(selected, max_workers_cap=args.max_workers)
+    print(
+        f"[matrix] resource_plan workers={plan['max_workers']} "
+        f"formal_slots={plan['formal_slots']} td_exclusive={plan['td_exclusive']} "
+        f"nproc={plan['host']['nproc']} mem_available_kb={plan['host']['mem_available_kb']} "
+        f"classes={plan['lane_classes']}",
+        flush=True,
+    )
+
     results: dict[str, dict[str, Any]] = {}
 
     def _run_lane(lane: str) -> tuple[str, dict[str, Any]]:
         work_root = Path(f"{args.work_root_prefix}-{lane}-{run_id[:8]}")
         runner = LANE_RUNNERS[lane]
-        print(f"[matrix] starting lane={lane} work_root={work_root}", flush=True)
+        print(
+            f"[matrix] starting lane={lane} class={LANE_RESOURCE_CLASS.get(lane)} "
+            f"work_root={work_root}",
+            flush=True,
+        )
         if lane in ("icarus", "verilator", "cocotb"):
             receipt = runner(repo, work_root, run_id, lane)
         else:
@@ -323,16 +494,18 @@ def main() -> int:
         return lane, receipt
 
     start = time.time()
-    # Run TD alone after open-source lanes to avoid license/memory contention.
-    open_lanes = [l for l in selected if l not in TD_EXCLUSIVE]
-    td_lanes = [l for l in selected if l in TD_EXCLUSIVE]
-
-    with ThreadPoolExecutor(max_workers=min(args.max_workers, max(1, len(open_lanes)))) as pool:
-        futures = [pool.submit(_run_lane, lane) for lane in open_lanes]
-        for fut in as_completed(futures):
-            lane, receipt = fut.result()
-            results[lane] = receipt
-
+    open_lanes = [lane for lane in selected if lane not in TD_EXCLUSIVE]
+    td_lanes = [lane for lane in selected if lane in TD_EXCLUSIVE]
+
+    for wave in _schedule_open_lanes(open_lanes, plan):
+        workers = min(plan["max_workers"], max(1, len(wave)))
+        with ThreadPoolExecutor(max_workers=workers) as pool:
+            futures = [pool.submit(_run_lane, lane) for lane in wave]
+            for fut in as_completed(futures):
+                lane, receipt = fut.result()
+                results[lane] = receipt
+
+    # TD exclusive: never overlap with OSS lanes or another TD.
     for lane in td_lanes:
         lane_name, receipt = _run_lane(lane)
         results[lane_name] = receipt
@@ -355,6 +528,7 @@ def main() -> int:
         "failures": [f"{lane}:{r['status']}" for lane, r in results.items() if r.get("status") != "pass"],
         "environment": "linux",
         "td_command": "td2026",
+        "resource_plan": plan,
     }
     report_path = Path(args.report_file)
     report_path.parent.mkdir(parents=True, exist_ok=True)

+ 82 - 32
tools/run_visible.py

@@ -1,5 +1,9 @@
 #!/usr/bin/env python3
-"""Visible, cancellable subprocess runner with heartbeat and receipts."""
+"""Visible, cancellable subprocess runner with heartbeat and receipts.
+
+POSIX process groups: each task starts a new session (start_new_session).
+Timeouts / interrupts signal only that task's PGID via killpg — never pkill/killall.
+"""
 
 from __future__ import annotations
 
@@ -21,6 +25,9 @@ try:
 except ImportError:  # pragma: no cover
     psutil = None
 
+# Keys that must never leak from a prior TD invocation into ordinary tasks.
+_TD_POLLUTE_KEYS = ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH")
+
 
 def _utc_now() -> str:
     return datetime.now(timezone.utc).isoformat()
@@ -33,19 +40,52 @@ def _atomic_write(path: Path, payload: dict[str, Any]) -> None:
     tmp.replace(path)
 
 
+def _clean_env(extra: dict[str, str] | None = None, *, keep_td_libs: bool = False) -> dict[str, str]:
+    clean = os.environ.copy()
+    if not keep_td_libs:
+        for key in _TD_POLLUTE_KEYS:
+            clean.pop(key, None)
+    if extra:
+        clean.update(extra)
+    return clean
+
+
 def _resource_snapshot(pid: int) -> dict[str, Any]:
+    """Real process metrics only — never invent progress percentages."""
     if psutil is None:
         return {"cpu_percent": None, "rss_bytes": None, "children": None}
     try:
         proc = psutil.Process(pid)
         children = proc.children(recursive=True)
         rss = proc.memory_info().rss + sum(c.memory_info().rss for c in children)
+        # interval=None returns rate since last call (or 0.0 on first sample).
         cpu = proc.cpu_percent(interval=None) + sum(c.cpu_percent(interval=None) for c in children)
-        return {"cpu_percent": cpu, "rss_bytes": rss, "children": len(children)}
+        return {"cpu_percent": round(cpu, 1), "rss_bytes": rss, "children": len(children)}
     except Exception:
         return {"cpu_percent": None, "rss_bytes": None, "children": None}
 
 
+def _terminate_group(pgid: int | None) -> None:
+    """Kill only the given process group. Never use pkill/killall."""
+    if pgid is None:
+        return
+    try:
+        os.killpg(pgid, signal.SIGTERM)
+    except ProcessLookupError:
+        return
+    deadline = time.monotonic() + 5.0
+    while time.monotonic() < deadline:
+        try:
+            os.killpg(pgid, 0)
+        except ProcessLookupError:
+            return
+        time.sleep(0.2)
+    try:
+        os.killpg(pgid, signal.SIGKILL)
+    except ProcessLookupError:
+        return
+
+
 def run_visible(
     command: list[str],
     *,
@@ -54,9 +94,10 @@ def run_visible(
     log_path: Path,
     status_path: Path,
     name: str = "task",
-    heartbeat_s: float = 8.0,
+    heartbeat_s: float = 5.0,
     timeout_s: float | None = None,
     no_progress_s: float | None = None,
+    keep_td_libs: bool = False,
 ) -> int:
     log_path.parent.mkdir(parents=True, exist_ok=True)
     status: dict[str, Any] = {
@@ -74,9 +115,7 @@ def run_visible(
     }
     _atomic_write(status_path, status)
 
-    clean_env = os.environ.copy()
-    if env:
-        clean_env.update(env)
+    clean_env = _clean_env(env, keep_td_libs=keep_td_libs)
 
     with log_path.open("w", encoding="utf-8", errors="replace") as log_file:
         proc = subprocess.Popen(
@@ -87,7 +126,7 @@ def run_visible(
             stderr=subprocess.STDOUT,
             text=True,
             bufsize=1,
-            start_new_session=True,
+            start_new_session=True,  # new POSIX process group / session
         )
         status["pid"] = proc.pid
         try:
@@ -96,10 +135,13 @@ def run_visible(
             status["pgid"] = proc.pid
         _atomic_write(status_path, status)
 
+        # Prime CPU percent baseline so the first heartbeat is meaningful.
+        _resource_snapshot(proc.pid)
+
         last_output = time.monotonic()
         last_heartbeat = time.monotonic()
         started = time.monotonic()
-        stop_reader = threading.Event()
+        last_log_bytes = 0
 
         def reader() -> None:
             nonlocal last_output
@@ -121,19 +163,30 @@ def run_visible(
                 if now - last_heartbeat >= heartbeat_s:
                     resources = _resource_snapshot(proc.pid)
                     log_size = log_path.stat().st_size if log_path.exists() else 0
+                    log_delta = log_size - last_log_bytes
+                    last_log_bytes = log_size
                     beat = {
+                        "task": name,
                         "elapsed_s": round(now - started, 1),
+                        "pid": status["pid"],
+                        "pgid": status["pgid"],
                         "log_bytes": log_size,
+                        "log_growth_bytes": log_delta,
                         "seconds_since_output": round(now - last_output, 1),
                         **resources,
                     }
                     status["heartbeat"].append(beat)
+                    # Cap retained heartbeat history to keep status files small.
+                    if len(status["heartbeat"]) > 200:
+                        status["heartbeat"] = status["heartbeat"][-100:]
                     status["last_heartbeat"] = beat
                     _atomic_write(status_path, status)
                     print(
-                        f"[heartbeat] {name} elapsed={beat['elapsed_s']}s "
+                        f"[heartbeat] task={name} elapsed={beat['elapsed_s']}s "
+                        f"pid={beat['pid']} pgid={beat['pgid']} "
                         f"cpu={beat['cpu_percent']} rss={beat['rss_bytes']} "
-                        f"children={beat['children']} log={log_size}B "
+                        f"children={beat['children']} "
+                        f"log={log_size}B (+{log_delta}B) "
                         f"quiet={beat['seconds_since_output']}s",
                         flush=True,
                     )
@@ -151,18 +204,22 @@ def run_visible(
                     status["state"] = "timeout"
                     status["timeout_reason"] = "total_timeout"
                     _terminate_group(status["pgid"])
-                    proc.wait(timeout=30)
-                    status["exit_code"] = proc.returncode
+                    try:
+                        proc.wait(timeout=30)
+                    except subprocess.TimeoutExpired:
+                        _terminate_group(status["pgid"])
+                        proc.wait(timeout=10)
+                    status["exit_code"] = 124
                     status["ended_at_utc"] = _utc_now()
                     _atomic_write(status_path, status)
-                    return status["exit_code"] or 124
+                    return 124
 
                 if no_progress_s is not None:
                     resources = _resource_snapshot(proc.pid)
                     quiet = (now - last_output) > no_progress_s
                     idle_cpu = (resources.get("cpu_percent") or 0) < 1.0
                     if quiet and idle_cpu:
-                        # Diagnostic only — do not kill solely for quiet logs if CPU active.
+                        # Diagnostic only — do not kill solely for quiet logs.
                         status["suspect_stall"] = True
                         _atomic_write(status_path, status)
 
@@ -170,27 +227,14 @@ def run_visible(
         except KeyboardInterrupt:
             status["state"] = "interrupted"
             _terminate_group(status["pgid"])
-            proc.wait(timeout=30)
+            try:
+                proc.wait(timeout=30)
+            except subprocess.TimeoutExpired:
+                _terminate_group(status["pgid"])
             status["exit_code"] = proc.returncode
             status["ended_at_utc"] = _utc_now()
             _atomic_write(status_path, status)
             raise
-        finally:
-            stop_reader.set()
-
-
-def _terminate_group(pgid: int | None) -> None:
-    if pgid is None:
-        return
-    try:
-        os.killpg(pgid, signal.SIGTERM)
-    except ProcessLookupError:
-        return
-    time.sleep(5)
-    try:
-        os.killpg(pgid, signal.SIGKILL)
-    except ProcessLookupError:
-        return
 
 
 def main() -> int:
@@ -200,7 +244,12 @@ def main() -> int:
     parser.add_argument("--log", type=Path, required=True)
     parser.add_argument("--status", type=Path, required=True)
     parser.add_argument("--timeout-s", type=float, default=None)
-    parser.add_argument("--heartbeat-s", type=float, default=8.0)
+    parser.add_argument("--heartbeat-s", type=float, default=5.0)
+    parser.add_argument(
+        "--keep-td-libs",
+        action="store_true",
+        help="Keep LD_LIBRARY_PATH/QT vars (TD subprocess only).",
+    )
     parser.add_argument("command", nargs=argparse.REMAINDER)
     args = parser.parse_args()
     command = args.command
@@ -216,6 +265,7 @@ def main() -> int:
         name=args.name,
         heartbeat_s=args.heartbeat_s,
         timeout_s=args.timeout_s,
+        keep_td_libs=args.keep_td_libs,
     )
 
 

+ 8 - 2
tools/verify.sh

@@ -5,10 +5,16 @@
 #   ./tools/verify.sh --lane td
 set -euo pipefail
 unset LD_LIBRARY_PATH LD_PRELOAD QT_PLUGIN_PATH || true
-export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH:-}"
+export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
 
 ROOT="$(cd "$(dirname "$0")/.." && pwd)"
-VENV="${PRODU2_VERIFY_VENV:-${XDG_CACHE_HOME:-$HOME/.cache}/prod2u/venvs/verify}"
+CACHE="${XDG_CACHE_HOME:-$HOME/.cache}/prod2u"
+OSS_CAD_BIN="${OSS_CAD_SUITE_ROOT:-$CACHE/oss-cad-suite/latest}/bin"
+if [[ -d "$OSS_CAD_BIN" ]]; then
+  export PATH="$OSS_CAD_BIN:$PATH"
+fi
+
+VENV="${PRODU2_VERIFY_VENV:-$CACHE/venvs/verify}"
 PY="$VENV/bin/python"
 if [[ ! -x "$PY" ]]; then
   PY=python3