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

feat(runner): extract resource scheduler with per-task build isolation.

Share light/medium/heavy/exclusive planning from host nproc/MemAvailable/disk,
give each lane independent builds/logs under --run-root, keep TD exclusive,
and avoid shared sim_build for the compact packager test matrix.

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 месяцев назад
Родитель
Сommit
03e47484bd
5 измененных файлов с 547 добавлено и 174 удалено
  1. 125 0
      tests/unit/test_resource_scheduler.py
  2. 6 22
      tools/doctor_linux.py
  3. 266 0
      tools/resource_scheduler.py
  4. 146 151
      tools/run_verification_matrix.py
  5. 4 1
      tools/verify.sh

+ 125 - 0
tests/unit/test_resource_scheduler.py

@@ -0,0 +1,125 @@
+"""Unit tests for host-aware resource scheduling helpers (Lane P7)."""
+
+from __future__ import annotations
+
+import tempfile
+import unittest
+from pathlib import Path
+
+from tools.resource_scheduler import (
+    TASK_RESOURCE_CLASS,
+    allocate_task_dirs,
+    assert_not_shared_sim_build,
+    classify_task,
+    host_resources,
+    lane_isolation_env,
+    plan_concurrency,
+    schedule_waves,
+)
+
+
+class HostResourcesTests(unittest.TestCase):
+    def test_host_resources_reports_nproc_and_memory_keys(self) -> None:
+        host = host_resources()
+        self.assertGreaterEqual(int(host["nproc"]), 1)
+        self.assertIn("mem_available_kb", host)
+        self.assertIn("disk_free_bytes", host)
+
+
+class ClassifyAndPlanTests(unittest.TestCase):
+    def test_matrix_and_packager_classes(self) -> None:
+        self.assertEqual(classify_task("python"), "light")
+        self.assertEqual(classify_task("formal"), "heavy")
+        self.assertEqual(classify_task("td"), "exclusive")
+        self.assertEqual(classify_task("package_adversarial"), "light")
+        self.assertEqual(classify_task("package_detached_replay"), "medium")
+        self.assertEqual(TASK_RESOURCE_CLASS["td"], "exclusive")
+
+    def test_plan_keeps_td_exclusive_and_caps_low_memory(self) -> None:
+        host = {
+            "nproc": 8,
+            "mem_available_kb": 1800 * 1024,
+            "disk_free_bytes": 50 * 1024**3,
+        }
+        plan = plan_concurrency(
+            ["python", "icarus", "formal", "td"],
+            host=host,
+        )
+        self.assertTrue(plan["td_exclusive"])
+        self.assertEqual(plan["max_workers"], 1)
+        self.assertNotIn("td", plan["open_lanes"])
+        self.assertEqual(plan["lane_classes"]["formal"], "heavy")
+
+    def test_plan_allows_parallel_light_medium_on_roomy_host(self) -> None:
+        host = {
+            "nproc": 8,
+            "mem_available_kb": 16 * 1024 * 1024,
+            "disk_free_bytes": 100 * 1024**3,
+        }
+        plan = plan_concurrency(
+            ["python", "board_viewer", "icarus", "cocotb"],
+            host=host,
+        )
+        self.assertGreaterEqual(plan["max_workers"], 2)
+        self.assertFalse(plan["td_exclusive"])
+
+    def test_low_disk_forces_serial(self) -> None:
+        host = {
+            "nproc": 8,
+            "mem_available_kb": 16 * 1024 * 1024,
+            "disk_free_bytes": 500 * 1024**2,
+        }
+        plan = plan_concurrency(["python", "icarus"], host=host)
+        self.assertFalse(plan["disk_ok"])
+        self.assertEqual(plan["max_workers"], 1)
+
+    def test_schedule_waves_serialize_heavy_when_tight(self) -> None:
+        host = {
+            "nproc": 4,
+            "mem_available_kb": 1800 * 1024,
+            "disk_free_bytes": 40 * 1024**3,
+        }
+        plan = plan_concurrency(
+            ["python", "formal", "verilator"],
+            host=host,
+        )
+        waves = schedule_waves(plan["open_lanes"], plan)
+        self.assertEqual(waves[0], ["python"])
+        self.assertIn(["formal"], waves)
+        self.assertIn(["verilator"], waves)
+
+
+class TaskDirIsolationTests(unittest.TestCase):
+    def test_allocate_independent_build_and_log_dirs(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            a = allocate_task_dirs(root, "python", run_id="aabbccdd11223344")
+            b = allocate_task_dirs(root, "cocotb", run_id="aabbccdd11223344")
+            self.assertNotEqual(a["build_dir"], b["build_dir"])
+            self.assertNotEqual(a["log_dir"], b["log_dir"])
+            self.assertTrue(a["build_dir"].is_dir())
+            self.assertTrue(a["log_dir"].is_dir())
+            self.assertEqual(a["build_dir"].parent.name, "builds")
+            self.assertEqual(a["log_dir"].parent.name, "logs")
+            self.assertNotEqual(a["build_dir"].name, "sim_build")
+
+    def test_refuse_shared_sim_build_basename(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            bad = Path(tmp) / "sim_build"
+            bad.mkdir()
+            with self.assertRaises(ValueError):
+                assert_not_shared_sim_build(bad)
+
+    def test_lane_isolation_env_points_inside_work_root(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            work = Path(tmp) / "lane-cocotb"
+            work.mkdir()
+            env = lane_isolation_env(work, task="cocotb")
+            self.assertTrue(env["TMPDIR"].startswith(str(work.resolve())))
+            self.assertTrue(env["PROD2U_COCOTB_BUILD_DIR"].startswith(str(work.resolve())))
+            self.assertNotIn("sim_build", Path(env["PROD2U_COCOTB_BUILD_DIR"]).parts)
+            self.assertEqual(env["PROD2U_TASK_NAME"], "cocotb")
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 6 - 22
tools/doctor_linux.py

@@ -21,6 +21,8 @@ from typing import Any
 
 
 
 
 ROOT = Path(__file__).resolve().parents[1]
 ROOT = Path(__file__).resolve().parents[1]
+if str(ROOT) not in sys.path:
+    sys.path.insert(0, str(ROOT))
 
 
 
 
 def _cache_root() -> Path:
 def _cache_root() -> Path:
@@ -163,28 +165,10 @@ def probe_python_venv(venv: Path) -> dict[str, Any]:
 
 
 
 
 def probe_host_resources() -> dict[str, Any]:
 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,
-    }
+    # Shared with the verification / packager matrix scheduler.
+    from tools.resource_scheduler import host_resources
+
+    return host_resources()
 
 
 
 
 def build_report() -> dict[str, Any]:
 def build_report() -> dict[str, Any]:

+ 266 - 0
tools/resource_scheduler.py

@@ -0,0 +1,266 @@
+"""Host-aware resource classes and per-task build/log isolation.
+
+Used by the verification matrix and compact-packager test orchestration.
+Reads nproc / MemAvailable / free disk; classifies tasks as
+light / medium / heavy / exclusive; allocates independent build and log
+directories so parallel lanes never share a sim_build tree. TD is always
+exclusive.
+"""
+from __future__ import annotations
+
+import os
+import shutil
+from pathlib import Path
+from typing import Any, Iterable, Mapping
+
+RESOURCE_CLASSES = ("light", "medium", "heavy", "exclusive")
+
+# Approximate resident budgets used only for concurrency planning (not fake %).
+CLASS_MEM_KB: dict[str, int] = {
+    "light": 256 * 1024,
+    "medium": 512 * 1024,
+    "heavy": 1536 * 1024,
+    "exclusive": 2048 * 1024,
+}
+
+# Matrix lanes + compact-packager related tasks for upcoming test matrix runs.
+TASK_RESOURCE_CLASS: dict[str, str] = {
+    # Verification matrix
+    "python": "light",
+    "board_viewer": "light",
+    "icarus": "medium",
+    "cocotb": "medium",
+    "verilator": "heavy",
+    "formal": "heavy",
+    "td": "exclusive",
+    # Compact packager orchestration (P1/P2/P6 consumers)
+    "package_selftest": "light",
+    "package_adversarial": "light",
+    "package_content_replay": "medium",
+    "package_detached_replay": "medium",
+    "doc_truth": "light",
+    "board_detached_derived": "medium",
+}
+
+TD_EXCLUSIVE = frozenset({"td"})
+
+# Shared relative names that must never be reused across concurrent tasks.
+_FORBIDDEN_SHARED_BUILD_NAMES = frozenset(
+    {
+        "sim_build",
+        "sim-build",
+        "simulation_build",
+    }
+)
+
+
+def host_resources(*, disk_path: str | os.PathLike[str] = "/") -> dict[str, Any]:
+    """Read nproc, MemAvailable (KiB), and free disk bytes."""
+    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(os.fspath(disk_path)).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 is not None else None
+        ),
+        "disk_free_bytes": disk_free_bytes,
+        "disk_free_gib": (
+            round(disk_free_bytes / (1024**3), 2) if disk_free_bytes is not None else None
+        ),
+    }
+
+
+def classify_task(task: str, overrides: Mapping[str, str] | None = None) -> str:
+    """Return light/medium/heavy/exclusive for a task name."""
+    if overrides and task in overrides:
+        value = overrides[task]
+    else:
+        value = TASK_RESOURCE_CLASS.get(task, "medium")
+    if value not in RESOURCE_CLASSES:
+        raise ValueError(f"unknown resource class for task {task!r}: {value!r}")
+    return value
+
+
+def _sanitize_task_name(task: str) -> str:
+    cleaned = "".join(ch if ch.isalnum() or ch in ("-", "_", ".") else "_" for ch in task.strip())
+    return cleaned or "task"
+
+
+def allocate_task_dirs(
+    run_root: Path | str,
+    task: str,
+    *,
+    run_id: str = "",
+    create: bool = True,
+) -> dict[str, Path]:
+    """Independent build + log dirs under run_root for one task.
+
+    Layout:
+      {run_root}/builds/{task}[-{run_id8}]/
+      {run_root}/logs/{task}[-{run_id8}]/
+
+    Never returns a path whose basename is a shared sim_build name.
+    """
+    root = Path(run_root).expanduser().resolve()
+    safe = _sanitize_task_name(task)
+    suffix = ""
+    if run_id:
+        hexish = "".join(c for c in run_id.lower() if c in "0123456789abcdef")
+        if hexish:
+            suffix = f"-{hexish[:8]}"
+        else:
+            suffix = f"-{_sanitize_task_name(run_id)[:8]}"
+    leaf = f"{safe}{suffix}"
+    if leaf in _FORBIDDEN_SHARED_BUILD_NAMES or safe in _FORBIDDEN_SHARED_BUILD_NAMES:
+        leaf = f"task-{leaf}"
+    build_dir = root / "builds" / leaf
+    log_dir = root / "logs" / leaf
+    work_root = build_dir  # harness --work-root points here
+    for path in (build_dir, log_dir):
+        if path.name in _FORBIDDEN_SHARED_BUILD_NAMES:
+            raise ValueError(f"refusing shared build name: {path}")
+        if create:
+            path.mkdir(parents=True, exist_ok=True)
+    return {
+        "run_root": root,
+        "task": safe,
+        "build_dir": build_dir,
+        "log_dir": log_dir,
+        "work_root": work_root,
+    }
+
+
+def lane_isolation_env(work_root: Path | str, *, task: str = "") -> dict[str, str]:
+    """Env vars that keep TEMP/pycache/cocotb builds inside the task work root.
+
+    Avoids a shared repo-level sim_build when multiple lanes run in parallel.
+    """
+    root = Path(work_root).expanduser().resolve()
+    temp = root / "tmp"
+    pycache = root / "pycache"
+    cocotb_build = root / "cocotb_build"
+    for path in (temp, pycache, cocotb_build):
+        path.mkdir(parents=True, exist_ok=True)
+    env = {
+        "TMPDIR": str(temp),
+        "TMP": str(temp),
+        "TEMP": str(temp),
+        "PYTHONPYCACHEPREFIX": str(pycache),
+        "PROD2U_COCOTB_BUILD_DIR": str(cocotb_build),
+    }
+    if task:
+        env["PROD2U_TASK_NAME"] = task
+        env["PROD2U_TASK_WORK_ROOT"] = str(root)
+    return env
+
+
+def plan_concurrency(
+    selected: Iterable[str],
+    *,
+    max_workers_cap: int | None = None,
+    class_overrides: Mapping[str, str] | None = None,
+    host: Mapping[str, Any] | None = None,
+    disk_path: str | os.PathLike[str] = "/",
+) -> 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; on small hosts
+      heavy lanes do not overlap.
+    """
+    selected_list = [str(item) for item in selected]
+    host_info = dict(host) if host is not None else host_resources(disk_path=disk_path)
+    nproc = int(host_info.get("nproc") or 1)
+    mem_kb = host_info.get("mem_available_kb")
+    disk_free = host_info.get("disk_free_bytes")
+
+    open_lanes = [lane for lane in selected_list if lane not in TD_EXCLUSIVE]
+    classes = {lane: classify_task(lane, class_overrides) for lane in open_lanes}
+    has_formal = "formal" in open_lanes
+    has_heavy = any(classes[lane] == "heavy" for lane in open_lanes)
+
+    disk_ok = disk_free is None or int(disk_free) >= 2 * 1024**3
+    formal_slots = 0
+
+    if mem_kb is None:
+        workers = 1 if has_heavy else min(2, nproc)
+        formal_slots = 1 if has_formal else 0
+    else:
+        mem_kb_i = int(mem_kb)
+        usable = max(0, mem_kb_i - 512 * 1024)
+        if has_formal and mem_kb_i < 3500 * 1024:
+            formal_slots = 1
+            workers = 1 if has_heavy else min(2, nproc)
+        else:
+            formal_slots = 1 if has_formal else 0
+            budget_workers = max(1, usable // CLASS_MEM_KB["medium"])
+            workers = max(1, min(nproc, budget_workers, 4))
+            if has_heavy and mem_kb_i < 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) or 1)))
+    if not open_lanes:
+        workers = 1
+
+    return {
+        "host": host_info,
+        "open_lanes": open_lanes,
+        "lane_classes": classes,
+        "max_workers": workers,
+        "formal_slots": formal_slots,
+        "td_exclusive": bool(any(lane in TD_EXCLUSIVE for lane in selected_list)),
+        "disk_ok": disk_ok,
+    }
+
+
+def schedule_waves(open_lanes: list[str], plan: Mapping[str, Any]) -> list[list[str]]:
+    """Partition open-source lanes into waves respecting memory / formal caps."""
+    if not open_lanes:
+        return []
+    workers = int(plan["max_workers"])
+    mem_kb = (plan.get("host") or {}).get("mem_available_kb")
+    classes = plan.get("lane_classes") or {
+        lane: classify_task(lane) for lane in open_lanes
+    }
+    if workers <= 1 or (mem_kb is not None and int(mem_kb) < 2500 * 1024):
+        light_medium = [
+            lane for lane in open_lanes if classes.get(lane) in ("light", "medium")
+        ]
+        heavy = [lane for lane in open_lanes if classes.get(lane) == "heavy"]
+        waves: list[list[str]] = []
+        if light_medium:
+            waves.append(light_medium)
+        for lane in heavy:
+            waves.append([lane])
+        return waves or [list(open_lanes)]
+    return [list(open_lanes)]
+
+
+def assert_not_shared_sim_build(path: Path | str) -> Path:
+    """Raise if path basename is a forbidden shared simulation build name."""
+    resolved = Path(path).expanduser().resolve()
+    if resolved.name in _FORBIDDEN_SHARED_BUILD_NAMES:
+        raise ValueError(
+            f"refusing shared sim_build path {resolved}; "
+            "use allocate_task_dirs() for per-task isolation"
+        )
+    return resolved

+ 146 - 151
tools/run_verification_matrix.py

@@ -4,16 +4,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
 cancel unrelated lanes. Missing toolchains produce `blocked` or `not_run`, never
 a fabricated pass. Long tasks use tools/run_visible.py for live heartbeat.
 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).
+Resource classes (light / medium / heavy / exclusive) come from
+tools/resource_scheduler.py (nproc, MemAvailable, free disk). Formal
+concurrency is memory-capped. TD is always exclusive (serialized after
+open-source lanes, with a lock file). Per-lane TEMP/cocotb builds stay under
+the task work root — never a shared sim_build.
 """
 """
 from __future__ import annotations
 from __future__ import annotations
 
 
 import argparse
 import argparse
 import json
 import json
 import os
 import os
-import shutil
 import sys
 import sys
 import time
 import time
 import uuid
 import uuid
@@ -27,8 +28,22 @@ if str(_repo_root) not in sys.path:
     sys.path.insert(0, str(_repo_root))
     sys.path.insert(0, str(_repo_root))
 
 
 from tools import prod2u_p4_harness  # noqa: E402
 from tools import prod2u_p4_harness  # noqa: E402
+from tools.resource_scheduler import (  # noqa: E402
+    TASK_RESOURCE_CLASS,
+    TD_EXCLUSIVE,
+    allocate_task_dirs,
+    assert_not_shared_sim_build,
+    classify_task,
+    host_resources,
+    lane_isolation_env,
+    plan_concurrency,
+    schedule_waves,
+)
 from tools.run_visible import run_visible  # noqa: E402
 from tools.run_visible import run_visible  # noqa: E402
 
 
+# Back-compat alias used by receipts / external importers.
+LANE_RESOURCE_CLASS = TASK_RESOURCE_CLASS
+
 DEFAULT_LANES = [
 DEFAULT_LANES = [
     "python",
     "python",
     "board_viewer",
     "board_viewer",
@@ -38,25 +53,6 @@ DEFAULT_LANES = [
     "formal",
     "formal",
     "td",
     "td",
 ]
 ]
-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:
 def _utc_now() -> str:
@@ -85,87 +81,6 @@ def _prefer_oss_cad_on_path() -> None:
         os.environ["PATH"] = prefix + (os.pathsep + current if current else "")
         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(
 def _run_visible_cmd(
     cmd: list[str],
     cmd: list[str],
     *,
     *,
@@ -197,11 +112,40 @@ def _run_visible_cmd(
     )
     )
 
 
 
 
-def run_python_unit(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
+def _lane_paths(
+    *,
+    lane: str,
+    run_id: str,
+    run_root: Path | None,
+    work_root_prefix: str | None,
+) -> dict[str, Path]:
+    if run_root is not None:
+        dirs = allocate_task_dirs(run_root, lane, run_id=run_id, create=True)
+        assert_not_shared_sim_build(dirs["work_root"])
+        return dirs
+    if not work_root_prefix:
+        raise ValueError("either --run-root or --work-root-prefix is required")
+    work_root = Path(f"{work_root_prefix}-{lane}-{run_id[:8]}")
+    assert_not_shared_sim_build(work_root)
+    work_root.mkdir(parents=True, exist_ok=True)
+    log_dir = work_root
+    return {
+        "run_root": work_root.parent,
+        "task": lane,
+        "build_dir": work_root,
+        "log_dir": log_dir,
+        "work_root": work_root,
+    }
+
+
+def run_python_unit(repo: Path, work_root: Path, run_id: str, *, log_dir: Path | None = None) -> dict[str, Any]:
+    log_root = log_dir or work_root
     receipt_path = work_root / "python-unit-receipt.json"
     receipt_path = work_root / "python-unit-receipt.json"
-    log_path = work_root / "python-unit.log"
-    status_path = work_root / "python-unit.status.json"
+    log_path = log_root / "python-unit.log"
+    status_path = log_root / "python-unit.status.json"
     work_root.mkdir(parents=True, exist_ok=True)
     work_root.mkdir(parents=True, exist_ok=True)
+    log_root.mkdir(parents=True, exist_ok=True)
+    isolation = lane_isolation_env(work_root, task="python")
     cmd = [
     cmd = [
         sys.executable,
         sys.executable,
         "-B",
         "-B",
@@ -210,6 +154,7 @@ def run_python_unit(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
         "-q",
         "-q",
         "-p",
         "-p",
         "no:cacheprovider",
         "no:cacheprovider",
+        f"--basetemp={work_root / 'tmp' / 'pytest'}",
         "tests/unit",
         "tests/unit",
         "tests/test_project_structure.py",
         "tests/test_project_structure.py",
     ]
     ]
@@ -220,6 +165,7 @@ def run_python_unit(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
         status_path=status_path,
         status_path=status_path,
         name="python",
         name="python",
         timeout_s=600,
         timeout_s=600,
+        env=isolation,
     )
     )
     status = "pass" if code == 0 else "fail"
     status = "pass" if code == 0 else "fail"
     full_commit = prod2u_p4_harness.current_commit()
     full_commit = prod2u_p4_harness.current_commit()
@@ -237,17 +183,21 @@ def run_python_unit(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
         "log_path": str(log_path),
         "log_path": str(log_path),
         "status_path": str(status_path),
         "status_path": str(status_path),
         "report_path": str(receipt_path),
         "report_path": str(receipt_path),
-        "resource_class": LANE_RESOURCE_CLASS["python"],
+        "work_root": str(work_root),
+        "resource_class": classify_task("python"),
     }
     }
     _write_json(receipt_path, receipt)
     _write_json(receipt_path, receipt)
     return receipt
     return receipt
 
 
 
 
-def run_board_viewer(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
+def run_board_viewer(repo: Path, work_root: Path, run_id: str, *, log_dir: Path | None = None) -> dict[str, Any]:
+    log_root = log_dir or work_root
     receipt_path = work_root / "board-viewer-receipt.json"
     receipt_path = work_root / "board-viewer-receipt.json"
-    log_path = work_root / "board-viewer.log"
-    status_path = work_root / "board-viewer.status.json"
+    log_path = log_root / "board-viewer.log"
+    status_path = log_root / "board-viewer.status.json"
     work_root.mkdir(parents=True, exist_ok=True)
     work_root.mkdir(parents=True, exist_ok=True)
+    log_root.mkdir(parents=True, exist_ok=True)
+    isolation = lane_isolation_env(work_root, task="board_viewer")
     cmd = [
     cmd = [
         sys.executable,
         sys.executable,
         "-B",
         "-B",
@@ -256,6 +206,7 @@ def run_board_viewer(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]
         "-q",
         "-q",
         "-p",
         "-p",
         "no:cacheprovider",
         "no:cacheprovider",
+        f"--basetemp={work_root / 'tmp' / 'pytest'}",
         "tests/board_viewer",
         "tests/board_viewer",
     ]
     ]
     code = _run_visible_cmd(
     code = _run_visible_cmd(
@@ -265,6 +216,7 @@ def run_board_viewer(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]
         status_path=status_path,
         status_path=status_path,
         name="board_viewer",
         name="board_viewer",
         timeout_s=900,
         timeout_s=900,
+        env=isolation,
     )
     )
     receipt = {
     receipt = {
         "schema": "prod2u-board-viewer-receipt-v1",
         "schema": "prod2u-board-viewer-receipt-v1",
@@ -275,7 +227,8 @@ def run_board_viewer(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]
         "returncode": code,
         "returncode": code,
         "log_path": str(log_path),
         "log_path": str(log_path),
         "report_path": str(receipt_path),
         "report_path": str(receipt_path),
-        "resource_class": LANE_RESOURCE_CLASS["board_viewer"],
+        "work_root": str(work_root),
+        "resource_class": classify_task("board_viewer"),
     }
     }
     _write_json(receipt_path, receipt)
     _write_json(receipt_path, receipt)
     return receipt
     return receipt
@@ -290,11 +243,15 @@ def _run_harness_lane(
     extra_args: list[str] | None = None,
     extra_args: list[str] | None = None,
     *,
     *,
     timeout_s: float = 1800,
     timeout_s: float = 1800,
+    log_dir: Path | None = None,
 ) -> dict[str, Any]:
 ) -> dict[str, Any]:
+    log_root = log_dir or work_root
     receipt_path = work_root / f"{lane}-receipt.json"
     receipt_path = work_root / f"{lane}-receipt.json"
-    log_path = work_root / f"{lane}.log"
-    status_path = work_root / f"{lane}.status.json"
+    log_path = log_root / f"{lane}.log"
+    status_path = log_root / f"{lane}.status.json"
     work_root.mkdir(parents=True, exist_ok=True)
     work_root.mkdir(parents=True, exist_ok=True)
+    log_root.mkdir(parents=True, exist_ok=True)
+    isolation = lane_isolation_env(work_root, task=lane)
     cmd = [
     cmd = [
         sys.executable,
         sys.executable,
         "-B",
         "-B",
@@ -317,6 +274,7 @@ def _run_harness_lane(
         status_path=status_path,
         status_path=status_path,
         name=lane,
         name=lane,
         timeout_s=timeout_s,
         timeout_s=timeout_s,
+        env=isolation,
     )
     )
     try:
     try:
         receipt = json.loads(receipt_path.read_text(encoding="utf-8-sig"))
         receipt = json.loads(receipt_path.read_text(encoding="utf-8-sig"))
@@ -331,11 +289,19 @@ def _run_harness_lane(
     receipt.setdefault("log_path", str(log_path))
     receipt.setdefault("log_path", str(log_path))
     receipt.setdefault("report_path", str(receipt_path))
     receipt.setdefault("report_path", str(receipt_path))
     receipt.setdefault("status_path", str(status_path))
     receipt.setdefault("status_path", str(status_path))
-    receipt.setdefault("resource_class", LANE_RESOURCE_CLASS.get(lane, "medium"))
+    receipt.setdefault("work_root", str(work_root))
+    receipt.setdefault("resource_class", classify_task(lane))
     return receipt
     return receipt
 
 
 
 
-def run_hdl_lane(repo: Path, work_root: Path, run_id: str, lane: str) -> dict[str, Any]:
+def run_hdl_lane(
+    repo: Path,
+    work_root: Path,
+    run_id: str,
+    lane: str,
+    *,
+    log_dir: Path | None = None,
+) -> dict[str, Any]:
     return _run_harness_lane(
     return _run_harness_lane(
         repo,
         repo,
         work_root,
         work_root,
@@ -344,10 +310,17 @@ def run_hdl_lane(repo: Path, work_root: Path, run_id: str, lane: str) -> dict[st
         "hdl-sim",
         "hdl-sim",
         ["--backend", lane],
         ["--backend", lane],
         timeout_s=1200,
         timeout_s=1200,
+        log_dir=log_dir,
     )
     )
 
 
 
 
-def run_formal(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
+def run_formal(
+    repo: Path,
+    work_root: Path,
+    run_id: str,
+    *,
+    log_dir: Path | None = None,
+) -> dict[str, Any]:
     # Wall-clock for the whole formal lane. Per-task timeout remains
     # Wall-clock for the whole formal lane. Per-task timeout remains
     # PROD2U_P4_TIMEOUT_FORMAL_SECONDS (default 600). Low-memory hosts need a
     # PROD2U_P4_TIMEOUT_FORMAL_SECONDS (default 600). Low-memory hosts need a
     # long lane budget because frame_tx BMC depth=96 alone can exceed 15 minutes.
     # long lane budget because frame_tx BMC depth=96 alone can exceed 15 minutes.
@@ -358,10 +331,24 @@ def run_formal(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
         lane_timeout = 7200.0
         lane_timeout = 7200.0
     if lane_timeout <= 0:
     if lane_timeout <= 0:
         lane_timeout = 7200.0
         lane_timeout = 7200.0
-    return _run_harness_lane(repo, work_root, run_id, "formal", "formal", timeout_s=lane_timeout)
+    return _run_harness_lane(
+        repo,
+        work_root,
+        run_id,
+        "formal",
+        "formal",
+        timeout_s=lane_timeout,
+        log_dir=log_dir,
+    )
 
 
 
 
-def run_td(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
+def run_td(
+    repo: Path,
+    work_root: Path,
+    run_id: str,
+    *,
+    log_dir: Path | None = None,
+) -> dict[str, Any]:
     lock_dir = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "prod2u"
     lock_dir = Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "prod2u"
     lock_dir.mkdir(parents=True, exist_ok=True)
     lock_dir.mkdir(parents=True, exist_ok=True)
     lock_path = lock_dir / "td.lock"
     lock_path = lock_dir / "td.lock"
@@ -377,6 +364,7 @@ def run_td(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
             "verification_run_id": run_id,
             "verification_run_id": run_id,
             "failures": [f"td_lock_held:{lock_path}"],
             "failures": [f"td_lock_held:{lock_path}"],
             "report_path": str(work_root / "td-receipt.json"),
             "report_path": str(work_root / "td-receipt.json"),
+            "work_root": str(work_root),
             "resource_class": "exclusive",
             "resource_class": "exclusive",
         }
         }
     try:
     try:
@@ -387,6 +375,7 @@ def run_td(repo: Path, work_root: Path, run_id: str) -> dict[str, Any]:
             "td",
             "td",
             "td-build",
             "td-build",
             timeout_s=3600,
             timeout_s=3600,
+            log_dir=log_dir,
         )
         )
         receipt["resource_class"] = "exclusive"
         receipt["resource_class"] = "exclusive"
         return receipt
         return receipt
@@ -419,34 +408,18 @@ def _overall_status(results: dict[str, dict[str, Any]], selected: list[str]) ->
     return "fail"
     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:
 def main() -> int:
     parser = argparse.ArgumentParser(description="Run the verification matrix")
     parser = argparse.ArgumentParser(description="Run the verification matrix")
-    parser.add_argument("--work-root-prefix", required=True)
+    parser.add_argument(
+        "--work-root-prefix",
+        default="",
+        help="Legacy prefix: {prefix}-{lane}-{run_id8} (mutually exclusive with --run-root).",
+    )
+    parser.add_argument(
+        "--run-root",
+        default="",
+        help="Run root with builds/ and logs/ per task (preferred for packager matrix).",
+    )
     parser.add_argument("--verification-run-id", default="")
     parser.add_argument("--verification-run-id", default="")
     parser.add_argument("--report-file", required=True)
     parser.add_argument("--report-file", required=True)
     parser.add_argument("--lanes", default=",".join(DEFAULT_LANES))
     parser.add_argument("--lanes", default=",".join(DEFAULT_LANES))
@@ -477,29 +450,49 @@ def main() -> int:
         print(f"unknown lanes: {unknown}", file=sys.stderr)
         print(f"unknown lanes: {unknown}", file=sys.stderr)
         return 1
         return 1
 
 
+    run_root = Path(args.run_root).expanduser().resolve() if args.run_root else None
+    work_root_prefix = args.work_root_prefix.strip() or None
+    if run_root is None and work_root_prefix is None:
+        print("error: provide --run-root or --work-root-prefix", file=sys.stderr)
+        return 2
+
     plan = plan_concurrency(selected, max_workers_cap=args.max_workers)
     plan = plan_concurrency(selected, max_workers_cap=args.max_workers)
     print(
     print(
         f"[matrix] resource_plan workers={plan['max_workers']} "
         f"[matrix] resource_plan workers={plan['max_workers']} "
         f"formal_slots={plan['formal_slots']} td_exclusive={plan['td_exclusive']} "
         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"nproc={plan['host']['nproc']} mem_available_kb={plan['host']['mem_available_kb']} "
+        f"disk_free_bytes={plan['host'].get('disk_free_bytes')} "
         f"classes={plan['lane_classes']}",
         f"classes={plan['lane_classes']}",
         flush=True,
         flush=True,
     )
     )
 
 
     results: dict[str, dict[str, Any]] = {}
     results: dict[str, dict[str, Any]] = {}
+    lane_dirs: dict[str, dict[str, str]] = {}
 
 
     def _run_lane(lane: str) -> tuple[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]}")
+        paths = _lane_paths(
+            lane=lane,
+            run_id=run_id,
+            run_root=run_root,
+            work_root_prefix=work_root_prefix,
+        )
+        work_root = paths["work_root"]
+        log_dir = paths["log_dir"]
+        lane_dirs[lane] = {
+            "work_root": str(work_root),
+            "build_dir": str(paths["build_dir"]),
+            "log_dir": str(log_dir),
+        }
         runner = LANE_RUNNERS[lane]
         runner = LANE_RUNNERS[lane]
         print(
         print(
-            f"[matrix] starting lane={lane} class={LANE_RESOURCE_CLASS.get(lane)} "
-            f"work_root={work_root}",
+            f"[matrix] starting lane={lane} class={classify_task(lane)} "
+            f"work_root={work_root} log_dir={log_dir}",
             flush=True,
             flush=True,
         )
         )
         if lane in ("icarus", "verilator", "cocotb"):
         if lane in ("icarus", "verilator", "cocotb"):
-            receipt = runner(repo, work_root, run_id, lane)
+            receipt = runner(repo, work_root, run_id, lane, log_dir=log_dir)
         else:
         else:
-            receipt = runner(repo, work_root, run_id)
+            receipt = runner(repo, work_root, run_id, log_dir=log_dir)
         print(f"[matrix] finished lane={lane} status={receipt.get('status')}", flush=True)
         print(f"[matrix] finished lane={lane} status={receipt.get('status')}", flush=True)
         return lane, receipt
         return lane, receipt
 
 
@@ -507,7 +500,7 @@ def main() -> int:
     open_lanes = [lane for lane in selected if lane not in TD_EXCLUSIVE]
     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]
     td_lanes = [lane for lane in selected if lane in TD_EXCLUSIVE]
 
 
-    for wave in _schedule_open_lanes(open_lanes, plan):
+    for wave in schedule_waves(open_lanes, plan):
         workers = min(plan["max_workers"], max(1, len(wave)))
         workers = min(plan["max_workers"], max(1, len(wave)))
         with ThreadPoolExecutor(max_workers=workers) as pool:
         with ThreadPoolExecutor(max_workers=workers) as pool:
             futures = [pool.submit(_run_lane, lane) for lane in wave]
             futures = [pool.submit(_run_lane, lane) for lane in wave]
@@ -535,10 +528,12 @@ def main() -> int:
         "status": overall,
         "status": overall,
         "duration_seconds": round(duration, 3),
         "duration_seconds": round(duration, 3),
         "lanes": results,
         "lanes": results,
+        "lane_dirs": lane_dirs,
         "failures": [f"{lane}:{r['status']}" for lane, r in results.items() if r.get("status") != "pass"],
         "failures": [f"{lane}:{r['status']}" for lane, r in results.items() if r.get("status") != "pass"],
         "environment": "linux",
         "environment": "linux",
         "td_command": "td2026",
         "td_command": "td2026",
         "resource_plan": plan,
         "resource_plan": plan,
+        "host_resources": host_resources(),
     }
     }
     report_path = Path(args.report_file)
     report_path = Path(args.report_file)
     report_path.parent.mkdir(parents=True, exist_ok=True)
     report_path.parent.mkdir(parents=True, exist_ok=True)

+ 4 - 1
tools/verify.sh

@@ -45,9 +45,12 @@ else
   EXTRA+=(--lanes "$LANES")
   EXTRA+=(--lanes "$LANES")
 fi
 fi
 
 
+# Prefer --run-root so each lane gets independent builds/ and logs/ trees
+# (never a shared sim_build). Keep work/ for backward-compatible artifacts.
+mkdir -p "$STATE"/{builds,logs,work,receipts,artifacts}
 echo "run_id=$RUN_ID root=$STATE"
 echo "run_id=$RUN_ID root=$STATE"
 exec "$PY" -B "$ROOT/tools/run_verification_matrix.py" \
 exec "$PY" -B "$ROOT/tools/run_verification_matrix.py" \
-  --work-root-prefix "$STATE/work/lane" \
+  --run-root "$STATE" \
   --verification-run-id "$(printf '%s' "$RUN_ID" | tr -cd 'a-f0-9' | head -c 32 | awk '{printf "%-32s", $0}' | tr ' ' '0')" \
   --verification-run-id "$(printf '%s' "$RUN_ID" | tr -cd 'a-f0-9' | head -c 32 | awk '{printf "%-32s", $0}' | tr ' ' '0')" \
   --report-file "$STATE/receipts/verification-matrix.json" \
   --report-file "$STATE/receipts/verification-matrix.json" \
   "${EXTRA[@]}"
   "${EXTRA[@]}"