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

fix(cocotb): level-aware frame_accept wait and VPI Python binding

Avoid RisingEdge hang when frame_accept_enable is already high after
SET_ALL, strip OSS CAD tabbypy3/PYTHONEXECUTABLE from the simulator PATH,
and keep the real UART 450-step E2E under an isolated build directory.

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

+ 240 - 7
tests/cocotb/run_prod2u_door_temp_uart_e2e.py

@@ -1,10 +1,16 @@
 #!/usr/bin/env python3
 #!/usr/bin/env python3
-"""Run the current project's real-UART cocotb scenario."""
+"""Run the current project's real-UART cocotb scenario.
+
+Forces the verification-venv Python into VPI (blocks OSS CAD tabbypy3 /
+PYTHONEXECUTABLE poisoning) and keeps the Icarus build tree under an
+independent TEMP/build directory.
+"""
 
 
 from __future__ import annotations
 from __future__ import annotations
 
 
 import os
 import os
 from pathlib import Path
 from pathlib import Path
+import shutil
 import sys
 import sys
 import xml.etree.ElementTree as ET
 import xml.etree.ElementTree as ET
 
 
@@ -12,8 +18,31 @@ import xml.etree.ElementTree as ET
 ROOT = Path(__file__).resolve().parents[2]
 ROOT = Path(__file__).resolve().parents[2]
 TEST_DIR = Path(__file__).resolve().parent
 TEST_DIR = Path(__file__).resolve().parent
 sys.path.insert(0, str(ROOT))
 sys.path.insert(0, str(ROOT))
-TEMP_ROOT = Path(os.environ.get("TEMP", ROOT / "tmp"))
-BUILD_DIR = TEMP_ROOT / "cocotb" / "prod2u_door_temp_uart_e2e"
+
+DEFAULT_VERIFY_PYTHON = Path(
+    os.environ.get(
+        "PROD2U_P4_COCOTB_PYTHON",
+        "/root/.cache/prod2u/venvs/verify/bin/python",
+    )
+).expanduser()
+
+# Poisonous env vars exported by OSS CAD tabbypy3 / environment scripts.
+_OSS_CAD_POISON = (
+    "PYTHONEXECUTABLE",
+    "PYTHONHOME",
+    "PYTHONNOUSERSITE",
+)
+
+
+def _resolve_build_dir() -> Path:
+    explicit = os.environ.get("PROD2U_COCOTB_BUILD_DIR", "").strip()
+    if explicit:
+        return Path(explicit).expanduser()
+    temp_root = Path(os.environ.get("TEMP", ROOT / "tmp"))
+    return temp_root / "cocotb" / "prod2u_door_temp_uart_e2e"
+
+
+BUILD_DIR = _resolve_build_dir()
 RESULTS_XML = BUILD_DIR / "results.xml"
 RESULTS_XML = BUILD_DIR / "results.xml"
 
 
 
 
@@ -35,14 +64,209 @@ def results_xml_has_failures(results: Path) -> bool:
     )
     )
 
 
 
 
+def _python_has_cocotb(python_exe: Path) -> bool:
+    import subprocess
+
+    completed = subprocess.run(
+        [str(python_exe), "-B", "-c", "import cocotb, cocotb_tools"],
+        cwd=str(ROOT),
+        env={k: v for k, v in os.environ.items() if k not in _OSS_CAD_POISON},
+        text=True,
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+        timeout=20,
+        check=False,
+    )
+    return completed.returncode == 0
+
+
+def _select_python() -> Path:
+    candidates: list[Path] = []
+    configured = os.environ.get("PROD2U_P4_COCOTB_PYTHON", "").strip()
+    if configured:
+        candidates.append(Path(configured).expanduser())
+    candidates.append(DEFAULT_VERIFY_PYTHON)
+    # Prefer configured/verify venv over a possibly poisoned sys.executable.
+    seen: set[str] = set()
+    for candidate in candidates:
+        key = str(candidate)
+        if key in seen:
+            continue
+        seen.add(key)
+        if candidate.is_file() and _python_has_cocotb(candidate):
+            return candidate
+    if Path(sys.executable).is_file() and _python_has_cocotb(Path(sys.executable)):
+        return Path(sys.executable)
+    return DEFAULT_VERIFY_PYTHON
+
+
+def _is_oss_cad_bin(part: str) -> bool:
+    normalized = part.rstrip("/")
+    return normalized.endswith("oss-cad-suite/latest/bin") or normalized.endswith(
+        "oss-cad-suite/bin"
+    )
+
+
+def _tool_bin_dirs() -> list[str]:
+    """Absolute directories for iverilog/vvp so OSS CAD bin is not required on PATH."""
+    dirs: list[str] = []
+    for name in ("iverilog", "vvp"):
+        resolved = shutil.which(name)
+        if resolved:
+            parent = str(Path(resolved).parent)
+            if parent not in dirs and not _is_oss_cad_bin(parent):
+                dirs.append(parent)
+    for fallback in ("/usr/bin", "/bin"):
+        if fallback not in dirs:
+            dirs.append(fallback)
+    return dirs
+
+
+def _sanitize_env(python_exe: Path, build_dir: Path) -> dict[str, str]:
+    """Bind VPI to verification Python and hide OSS CAD python shims.
+
+    OSS CAD ``bin`` must stay off PATH: even without PYTHONEXECUTABLE, having
+    ``tabbypy3`` visible makes the VPI-embedded interpreter report
+    sys.executable as tabbypy3 (cocotb gpi_embed sanity check fails).
+    """
+    env = {k: v for k, v in os.environ.items() if k not in _OSS_CAD_POISON}
+    python_bin = str(python_exe.parent)
+    shim_dir = build_dir / "path-shim"
+    shim_dir.mkdir(parents=True, exist_ok=True)
+    for shim_name in ("python", "python3", "python3.13", "tabbypy3", "tabby"):
+        shim_path = shim_dir / shim_name
+        if shim_path.exists() or shim_path.is_symlink():
+            shim_path.unlink()
+        shim_path.symlink_to(python_exe)
+
+    path_parts: list[str] = [python_bin, str(shim_dir), *_tool_bin_dirs()]
+    for part in env.get("PATH", "").split(os.pathsep):
+        if not part or _is_oss_cad_bin(part):
+            continue
+        if part not in path_parts:
+            path_parts.append(part)
+    env["PATH"] = os.pathsep.join(path_parts)
+    env["VIRTUAL_ENV"] = str(python_exe.parent.parent)
+    env["PYGPI_PYTHON_BIN"] = str(python_exe)
+    env["PROD2U_P4_COCOTB_PYTHON"] = str(python_exe)
+    # Keep TEMP under the lane build root; cocotb_tools uses build_dir directly.
+    env["TEMP"] = str(build_dir)
+    env["TMP"] = str(build_dir)
+    env["TMPDIR"] = str(build_dir)
+    for key in _OSS_CAD_POISON:
+        env.pop(key, None)
+    # find_libpython may be unavailable while PYTHONEXECUTABLE still poisons this
+    # process; LIBPYTHON_LOC is filled after re-exec in main().
+    return env
+
+
+def _ensure_running_under(python_exe: Path, build_dir: Path) -> None:
+    """Re-exec under the selected interpreter with a sanitized environment.
+
+    PYTHONEXECUTABLE poisons sys.executable for the whole process lifetime; the
+    only fix is a clean execve before cocotb_tools/VPI start.
+    """
+    need_reexec = False
+    if "tabbypy3" in Path(sys.executable).name:
+        need_reexec = True
+    if os.environ.get("PYTHONEXECUTABLE"):
+        need_reexec = True
+    current = Path(sys.executable).expanduser()
+    if str(current) != str(python_exe) and not (
+        current.parent == python_exe.parent and current.name.startswith("python")
+    ):
+        need_reexec = True
+    if not need_reexec:
+        return
+    os.execve(
+        str(python_exe),
+        [str(python_exe), "-B", str(Path(__file__).resolve()), *sys.argv[1:]],
+        _sanitize_env(python_exe, build_dir),
+    )
+
+
 def main() -> int:
 def main() -> int:
+    build_dir = _resolve_build_dir()
+    build_dir.mkdir(parents=True, exist_ok=True)
+    results_xml = build_dir / "results.xml"
+    python_exe = _select_python()
+
+    # Re-exec first when poisoned so subsequent imports see a healthy venv.
+    _ensure_running_under(python_exe, build_dir)
+
+    sanitized = _sanitize_env(python_exe, build_dir)
+    try:
+        import find_libpython
+
+        libpython = find_libpython.find_libpython()
+        if libpython:
+            sanitized["LIBPYTHON_LOC"] = libpython
+    except Exception:
+        pass
+    os.environ.clear()
+    os.environ.update(sanitized)
+
+    # Guard: refuse to proceed if poison remains.
+    if os.environ.get("PYTHONEXECUTABLE"):
+        print(
+            "error: PYTHONEXECUTABLE is set; refusing to run VPI under OSS CAD poison: "
+            f"{os.environ['PYTHONEXECUTABLE']}",
+            file=sys.stderr,
+        )
+        return 2
+    if "tabbypy3" in Path(sys.executable).name:
+        print(f"error: sys.executable is OSS CAD tabbypy3: {sys.executable}", file=sys.stderr)
+        return 2
+    if any(_is_oss_cad_bin(part) for part in os.environ.get("PATH", "").split(os.pathsep)):
+        print("error: OSS CAD bin still on PATH after sanitize", file=sys.stderr)
+        return 2
+
     from cocotb_tools.runner import get_runner
     from cocotb_tools.runner import get_runner
 
 
     runner = get_runner("icarus")
     runner = get_runner("icarus")
+
+    _orig_set_env = runner._set_env
+
+    def _set_env_without_oss_cad_poison() -> None:
+        _orig_set_env()
+        for key in _OSS_CAD_POISON:
+            runner.env.pop(key, None)
+        # Re-assert PATH without OSS CAD (cocotb may append libs_dir only).
+        path_parts = [
+            part
+            for part in runner.env.get("PATH", "").split(os.pathsep)
+            if part and not _is_oss_cad_bin(part)
+        ]
+        runner.env["PATH"] = os.pathsep.join(path_parts)
+        runner.env["PYGPI_PYTHON_BIN"] = str(python_exe)
+        audit = build_dir / "vpi-env-audit.txt"
+        audit.write_text(
+            "\n".join(
+                [
+                    f"os.PYTHONEXECUTABLE={os.environ.get('PYTHONEXECUTABLE')!r}",
+                    f"runner.PYTHONEXECUTABLE={runner.env.get('PYTHONEXECUTABLE')!r}",
+                    f"runner.PYGPI_PYTHON_BIN={runner.env.get('PYGPI_PYTHON_BIN')!r}",
+                    f"sys.executable={sys.executable!r}",
+                    f"PATH_has_oss_cad={any(_is_oss_cad_bin(p) for p in runner.env.get('PATH', '').split(os.pathsep))}",
+                ]
+            )
+            + "\n",
+            encoding="utf-8",
+        )
+        if "tabbypy3" in runner.env.get("PYGPI_PYTHON_BIN", ""):
+            raise RuntimeError("PYGPI_PYTHON_BIN resolved to OSS CAD tabbypy3")
+        if runner.env.get("PYTHONEXECUTABLE"):
+            raise RuntimeError(
+                "PYTHONEXECUTABLE still present in runner.env after sanitize: "
+                f"{runner.env['PYTHONEXECUTABLE']}"
+            )
+
+    runner._set_env = _set_env_without_oss_cad_poison  # type: ignore[method-assign]
+
     runner.build(
     runner.build(
         sources=[*rtl_sources(), TEST_DIR / "prod2u_door_temp_uart_top.v"],
         sources=[*rtl_sources(), TEST_DIR / "prod2u_door_temp_uart_top.v"],
         hdl_toplevel="prod2u_door_temp_uart_top",
         hdl_toplevel="prod2u_door_temp_uart_top",
-        build_dir=BUILD_DIR,
+        build_dir=build_dir,
         build_args=["-I", str(ROOT)],
         build_args=["-I", str(ROOT)],
         always=True,
         always=True,
         verbose=False,
         verbose=False,
@@ -51,12 +275,21 @@ def main() -> int:
         runner.test(
         runner.test(
             hdl_toplevel="prod2u_door_temp_uart_top",
             hdl_toplevel="prod2u_door_temp_uart_top",
             test_module="test_prod2u_door_temp_uart_e2e",
             test_module="test_prod2u_door_temp_uart_e2e",
-            build_dir=BUILD_DIR,
+            build_dir=build_dir,
             test_dir=TEST_DIR,
             test_dir=TEST_DIR,
-            results_xml=str(RESULTS_XML),
+            results_xml=str(results_xml),
+            extra_env={
+                "PYGPI_PYTHON_BIN": str(python_exe),
+                "PATH": os.environ["PATH"],
+                "VIRTUAL_ENV": os.environ.get("VIRTUAL_ENV", ""),
+            },
         )
         )
     )
     )
-    return 1 if not results.is_file() or results_xml_has_failures(results) else 0
+    if not results.is_file() or results_xml_has_failures(results):
+        print(f"cocotb fail results={results}", file=sys.stderr)
+        return 1
+    print(f"cocotb pass results={results} python={python_exe}")
+    return 0
 
 
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":

+ 73 - 18
tests/cocotb/test_prod2u_door_temp_uart_e2e.py

@@ -7,6 +7,7 @@ wire boundary: bytes are serialized as 8N1 bits at 217 system clocks/bit.
 import cocotb
 import cocotb
 import cocotb.simulator as simulator
 import cocotb.simulator as simulator
 from cocotb.triggers import Event, FallingEdge, NextTimeStep, ReadOnly, ReadWrite, RisingEdge, SimTimeoutError, Timer, with_timeout
 from cocotb.triggers import Event, FallingEdge, NextTimeStep, ReadOnly, ReadWrite, RisingEdge, SimTimeoutError, Timer, with_timeout
+from cocotb.utils import get_sim_time
 
 
 
 
 CLKS_PER_BIT = 217
 CLKS_PER_BIT = 217
@@ -16,6 +17,7 @@ TEMPERATURE_DATA = 0x82
 MOTOR_STEPS = 450
 MOTOR_STEPS = 450
 MOTOR_COMPLETION_TIMEOUT_MS = 600
 MOTOR_COMPLETION_TIMEOUT_MS = 600
 TEMPERATURE_BYTE_TIMEOUT_MS = 100
 TEMPERATURE_BYTE_TIMEOUT_MS = 100
+FRAME_ACCEPT_TIMEOUT_MS = 100
 
 
 
 
 def crc16(data: bytes) -> int:
 def crc16(data: bytes) -> int:
@@ -32,8 +34,22 @@ def frame(kind: int, payload: bytes) -> bytes:
     return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
     return b"\xA5\x5A" + body + crc16(body).to_bytes(2, "little")
 
 
 
 
+def _sim_time_ns() -> str:
+    try:
+        return f"{get_sim_time(unit='ns'):.0f}ns"
+    except Exception:
+        return "unknown"
+
+
+def checkpoint(stage: str, **fields) -> None:
+    """Emit a machine-searchable stage checkpoint with sim time."""
+    extra = " ".join(f"{key}={value}" for key, value in fields.items())
+    suffix = f" {extra}" if extra else ""
+    cocotb.log.info("checkpoint stage=%s sim_time=%s%s", stage, _sim_time_ns(), suffix)
+
+
 async def clocks(dut, count: int) -> None:
 async def clocks(dut, count: int) -> None:
-    await Timer(count * 40, units="ns")
+    await Timer(count * 40, unit="ns")
 
 
 
 
 async def send_uart_byte(dut, value: int) -> None:
 async def send_uart_byte(dut, value: int) -> None:
@@ -90,26 +106,44 @@ async def observe_motor_steps(dut, observed: dict[str, int | bool], completion:
 
 
 async def receive_uart_byte(dut) -> int:
 async def receive_uart_byte(dut) -> int:
     await FallingEdge(dut.host_uart_tx)
     await FallingEdge(dut.host_uart_tx)
-    await Timer((CLKS_PER_BIT + CLKS_PER_BIT // 2) * 40, units="ns")
+    await Timer((CLKS_PER_BIT + CLKS_PER_BIT // 2) * 40, unit="ns")
     value = 0
     value = 0
     for bit in range(8):
     for bit in range(8):
         value |= int(dut.host_uart_tx.value) << bit
         value |= int(dut.host_uart_tx.value) << bit
-        await Timer(CLKS_PER_BIT * 40, units="ns")
+        await Timer(CLKS_PER_BIT * 40, unit="ns")
     assert int(dut.host_uart_tx.value) == 1
     assert int(dut.host_uart_tx.value) == 1
     return value
     return value
 
 
 
 
-async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1):
+async def wait_for_stage(awaitable, timeout_ms: int, stage: str, byte_index: int = -1, **fields):
     """Apply a bounded wait with a stable, machine-searchable failure message."""
     """Apply a bounded wait with a stable, machine-searchable failure message."""
     try:
     try:
         return await with_timeout(awaitable, timeout_ms, "ms")
         return await with_timeout(awaitable, timeout_ms, "ms")
     except SimTimeoutError as exc:
     except SimTimeoutError as exc:
         suffix = "" if byte_index < 0 else f" byte_index={byte_index}"
         suffix = "" if byte_index < 0 else f" byte_index={byte_index}"
+        extra = "".join(f" {key}={value}" for key, value in fields.items())
         raise AssertionError(
         raise AssertionError(
-            f"timeout stage={stage} timeout_ms={timeout_ms}{suffix}"
+            f"timeout stage={stage} timeout_ms={timeout_ms} sim_time={_sim_time_ns()}"
+            f"{suffix}{extra}"
         ) from exc
         ) from exc
 
 
 
 
+async def wait_level_or_edge(signal, *, want: int, timeout_ms: int, stage: str) -> None:
+    """Continue if signal already matches want; else wait for the matching edge."""
+    current = int(signal.value) if signal.value.is_resolvable else None
+    if current == want:
+        checkpoint(stage, already=want)
+        return
+    edge = RisingEdge(signal) if want else FallingEdge(signal)
+    await wait_for_stage(
+        edge,
+        timeout_ms,
+        stage,
+        signal_level=current,
+        want=want,
+    )
+
+
 def stop_background_task(task) -> None:
 def stop_background_task(task) -> None:
     if task is None:
     if task is None:
         return
         return
@@ -125,6 +159,7 @@ async def test_set_all_get_temperature_over_real_uart(dut):
     observed = {"x": 0, "y": 0, "overlap": False}
     observed = {"x": 0, "y": 0, "overlap": False}
     motor_completion = Event()
     motor_completion = Event()
     try:
     try:
+        checkpoint("test_start")
         observer_task = cocotb.start_soon(
         observer_task = cocotb.start_soon(
             observe_motor_steps(dut, observed, motor_completion)
             observe_motor_steps(dut, observed, motor_completion)
         )
         )
@@ -136,41 +171,60 @@ async def test_set_all_get_temperature_over_real_uart(dut):
         await clocks(dut, 1024)
         await clocks(dut, 1024)
         # Limits already high => startup may finish during the wait above.
         # Limits already high => startup may finish during the wait above.
         # RisingEdge alone would hang forever if startup_done is already 1.
         # RisingEdge alone would hang forever if startup_done is already 1.
-        if int(dut.u_dut.startup_done.value) == 0:
-            await wait_for_stage(
-                RisingEdge(dut.u_dut.startup_done),
-                MOTOR_COMPLETION_TIMEOUT_MS,
-                "startup_done",
-            )
+        await wait_level_or_edge(
+            dut.u_dut.startup_done,
+            want=1,
+            timeout_ms=MOTOR_COMPLETION_TIMEOUT_MS,
+            stage="startup_done",
+        )
+        checkpoint("startup_done")
 
 
         # X=01 open (DIR=0), Y=02 close (DIR=1); 450 steps each, overlapping.
         # X=01 open (DIR=0), Y=02 close (DIR=1); 450 steps each, overlapping.
         payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 0, 1, 2))
         payload = bytes((10, 20, 30, 40, 0, 0, 0, 0, 0, 1, 2))
+        checkpoint("set_all_tx")
         await send_frame(dut, frame(SET_ALL, payload))
         await send_frame(dut, frame(SET_ALL, payload))
         # Sample DIR while the jog is active (before completion).
         # Sample DIR while the jog is active (before completion).
         await clocks(dut, CLKS_PER_BIT * 8)
         await clocks(dut, CLKS_PER_BIT * 8)
         assert int(dut.x_dir.value) == 0, "SET_ALL X=01 must drive DIR=0 (open)"
         assert int(dut.x_dir.value) == 0, "SET_ALL X=01 must drive DIR=0 (open)"
         assert int(dut.y_dir.value) == 1, "SET_ALL Y=02 must drive DIR=1 (close)"
         assert int(dut.y_dir.value) == 1, "SET_ALL Y=02 must drive DIR=1 (close)"
+        checkpoint("dir_sampled", x_dir=int(dut.x_dir.value), y_dir=int(dut.y_dir.value))
         try:
         try:
             await with_timeout(motor_completion.wait(), MOTOR_COMPLETION_TIMEOUT_MS, "ms")
             await with_timeout(motor_completion.wait(), MOTOR_COMPLETION_TIMEOUT_MS, "ms")
         except SimTimeoutError as exc:
         except SimTimeoutError as exc:
             raise AssertionError(
             raise AssertionError(
                 "timeout stage=motor_completion "
                 "timeout stage=motor_completion "
-                f"timeout_ms={MOTOR_COMPLETION_TIMEOUT_MS} "
+                f"timeout_ms={MOTOR_COMPLETION_TIMEOUT_MS} sim_time={_sim_time_ns()} "
                 f"observed_x={observed['x']} observed_y={observed['y']}"
                 f"observed_x={observed['x']} observed_y={observed['y']}"
             ) from exc
             ) from exc
         assert observed["x"] == MOTOR_STEPS
         assert observed["x"] == MOTOR_STEPS
         assert observed["y"] == MOTOR_STEPS
         assert observed["y"] == MOTOR_STEPS
         assert observed["overlap"] is True
         assert observed["overlap"] is True
         assert int(dut.motor_en_n.value) == 0
         assert int(dut.motor_en_n.value) == 0
+        checkpoint(
+            "motor_completion",
+            observed_x=observed["x"],
+            observed_y=observed["y"],
+            overlap=observed["overlap"],
+        )
 
 
-
-        await with_timeout(
-            FallingEdge(dut.x_step),
-            MOTOR_COMPLETION_TIMEOUT_MS,
-            "ms",
+        # STEP may already be low after the last half-cycle; FallingEdge alone hangs.
+        await wait_level_or_edge(
+            dut.x_step,
+            want=0,
+            timeout_ms=MOTOR_COMPLETION_TIMEOUT_MS,
+            stage="x_step_idle",
+        )
+        # SET_ALL returns the controller to IDLE long before motors finish, so
+        # frame_accept_enable is often already 1; RisingEdge alone hangs forever.
+        await wait_level_or_edge(
+            dut.u_dut.frame_accept_enable,
+            want=1,
+            timeout_ms=FRAME_ACCEPT_TIMEOUT_MS,
+            stage="frame_accept_enable",
         )
         )
-        await RisingEdge(dut.u_dut.frame_accept_enable)
+        checkpoint("frame_accept_enable")
         await clocks(dut, 4)
         await clocks(dut, 4)
+        checkpoint("get_temperature_tx")
         await send_frame(dut, frame(GET_TEMPERATURE, b""))
         await send_frame(dut, frame(GET_TEMPERATURE, b""))
         response = bytearray()
         response = bytearray()
         for byte_index in range(33):
         for byte_index in range(33):
@@ -187,6 +241,7 @@ async def test_set_all_get_temperature_over_real_uart(dut):
         assert len(response) == 33
         assert len(response) == 33
         assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
         assert response[-2:] == crc16(response[2:-2]).to_bytes(2, "little")
         assert set(response[4:31]) == {0xFF}
         assert set(response[4:31]) == {0xFF}
+        checkpoint("temperature_response_ok", bytes=len(response))
     finally:
     finally:
         stop_background_task(observer_task)
         stop_background_task(observer_task)
         try:
         try:

+ 22 - 7
tools/prod2u_p4_harness.py

@@ -1403,8 +1403,14 @@ def _run_cocotb(
                 "PYTHONPYCACHEPREFIX": str(target_root / "pycache"),
                 "PYTHONPYCACHEPREFIX": str(target_root / "pycache"),
             }
             }
         )
         )
+        # OSS CAD tabbypy3 exports PYTHONEXECUTABLE/PYTHONHOME; those poison
+        # sys.executable inside the VPI-embedded interpreter and break GPI.
+        # Keeping oss-cad-suite/bin on PATH also makes embedded sys.executable
+        # resolve to tabbypy3 even when PYTHONEXECUTABLE is unset — drop it.
+        for poison in ("PYTHONEXECUTABLE", "PYTHONHOME", "PYTHONNOUSERSITE"):
+            cocotb_env.pop(poison, None)
         # Prefer the selected venv, then a shim that hides OSS CAD python
         # Prefer the selected venv, then a shim that hides OSS CAD python
-        # shims (tabbypy3) while still exposing iverilog/vvp from OSS CAD.
+        # shims (tabbypy3) while still exposing system iverilog/vvp.
         python_bin = str(Path(python_exe).expanduser().parent)
         python_bin = str(Path(python_exe).expanduser().parent)
         shim_dir = target_root / "path-shim"
         shim_dir = target_root / "path-shim"
         shim_dir.mkdir(parents=True, exist_ok=True)
         shim_dir.mkdir(parents=True, exist_ok=True)
@@ -1414,15 +1420,24 @@ def _run_cocotb(
                 shim_path.unlink()
                 shim_path.unlink()
             shim_path.symlink_to(Path(python_exe).expanduser())
             shim_path.symlink_to(Path(python_exe).expanduser())
         path_parts: list[str] = [python_bin, str(shim_dir)]
         path_parts: list[str] = [python_bin, str(shim_dir)]
-        for root in toolchain_roots():
-            bin_dir = root / "bin"
-            if bin_dir.is_dir():
-                path_parts.append(str(bin_dir))
+        for name in ("iverilog", "vvp"):
+            resolved = resolve_tool(name)
+            if resolved:
+                parent = str(Path(resolved).parent)
+                if parent not in path_parts and "oss-cad-suite" not in parent:
+                    path_parts.append(parent)
         for part in cocotb_env.get("PATH", "").split(os.pathsep):
         for part in cocotb_env.get("PATH", "").split(os.pathsep):
-            if part and part not in path_parts:
-                path_parts.append(part)
+            if not part or part in path_parts:
+                continue
+            if "oss-cad-suite" in part and part.rstrip("/").endswith("/bin"):
+                continue
+            path_parts.append(part)
         cocotb_env["PATH"] = os.pathsep.join(path_parts)
         cocotb_env["PATH"] = os.pathsep.join(path_parts)
         cocotb_env["VIRTUAL_ENV"] = str(Path(python_bin).parent)
         cocotb_env["VIRTUAL_ENV"] = str(Path(python_bin).parent)
+        cocotb_env["PYGPI_PYTHON_BIN"] = str(Path(python_exe).expanduser())
+        cocotb_env["PROD2U_P4_COCOTB_PYTHON"] = str(Path(python_exe).expanduser())
+        if "PROD2U_COCOTB_BUILD_DIR" not in cocotb_env:
+            cocotb_env["PROD2U_COCOTB_BUILD_DIR"] = str(target_root / "cocotb" / target["name"])
         completed = _run_bounded(
         completed = _run_bounded(
             [python_exe, "-B", str(ROOT / target["runner"])],
             [python_exe, "-B", str(ROOT / target["runner"])],
             timeout_name="cocotb",
             timeout_name="cocotb",