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

fix(verify): LD-safe sys.executable for CLI pytest children

Rewrite bare OSS CAD libexec sys.executable to the py3bin/venv wrapper after
TD poison-strip, and reject bootstrap installs into the source checkout so
worktrees under /data/prod2u stay out of the toolchain root.

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

+ 18 - 0
tests/conftest.py

@@ -0,0 +1,18 @@
+"""Pytest hooks shared by unit/structure suites.
+
+Rewrite bare OSS CAD ``libexec`` ``sys.executable`` to the LD-safe wrapper so
+CLI subprocess tests do not exit 127 after TD poison-strip.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+_REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(_REPO_ROOT) not in sys.path:
+    sys.path.insert(0, str(_REPO_ROOT))
+
+from tools.tool_env import ensure_safe_sys_executable  # noqa: E402
+
+ensure_safe_sys_executable()

+ 5 - 1
tools/bootstrap_oss_cad_suite.py

@@ -107,7 +107,11 @@ def _assert_safe_toolchain_root(path: Path) -> Path:
     home = Path.home().resolve()
     base = DEFAULT_TOOLCHAIN_BASE.resolve()
     _assert_under(base, resolved, "toolchain path")
-    if resolved in {home, home.parent, Path(resolved.anchor)}:
+    if resolved in {home, home.parent, Path(resolved.anchor), base}:
+        raise ValueError(f"unsafe toolchain root: {resolved}")
+    # Never install into the source checkout that ships this helper (or nested paths).
+    workspace_root = Path(__file__).resolve().parents[1]
+    if resolved == workspace_root or workspace_root in resolved.parents:
         raise ValueError(f"unsafe toolchain root: {resolved}")
     return resolved
 

+ 2 - 12
tools/replay_review_compact.py

@@ -40,19 +40,9 @@ REFERENCE_REGENERATION_REPLAY = "not_packaged_by_policy"
 HARDWARE_VALIDATION = "not_run"
 
 
-def _safe_python() -> str:
-    """Avoid bare oss-cad libexec (needs ld-linux + libpython)."""
-    override = os.environ.get("PRODU2_VERIFY_PYTHON", "").strip()
-    if override:
-        return override
-    wrapper = Path("/data/prod2u/venvs/verify/bin/python")
-    exe = Path(sys.executable)
-    if "libexec" in exe.as_posix() and wrapper.is_file():
-        return str(wrapper)
-    if wrapper.is_file():
-        return str(wrapper)
-    return str(exe)
+from tool_env import ensure_safe_sys_executable, safe_python as _safe_python  # noqa: E402
 
+ensure_safe_sys_executable()
 
 
 class ReplayError(RuntimeError):

+ 14 - 25
tools/run_verification_matrix.py

@@ -28,6 +28,11 @@ if str(_repo_root) not in sys.path:
     sys.path.insert(0, str(_repo_root))
 
 from tools import prod2u_p4_harness  # noqa: E402
+from tools.tool_env import (  # noqa: E402
+    ensure_safe_sys_executable,
+    safe_python as _safe_python,
+    strip_poison_env,
+)
 from tools.resource_scheduler import (  # noqa: E402
     TASK_RESOURCE_CLASS,
     TD_EXCLUSIVE,
@@ -55,18 +60,6 @@ DEFAULT_LANES = [
 ]
 
 
-def _safe_python() -> str:
-    """Prefer LD-safe wrapper; bare oss-cad libexec lacks libpython without ld-linux."""
-    override = os.environ.get("PRODU2_VERIFY_PYTHON", "").strip()
-    if override:
-        return override
-    wrapper = Path("/data/prod2u/venvs/verify/bin/python")
-    exe = Path(sys.executable)
-    if "libexec" in exe.as_posix() and wrapper.is_file():
-        return str(wrapper)
-    return str(exe)
-
-
 def _utc_now() -> str:
     return datetime.now(timezone.utc).isoformat()
 
@@ -175,6 +168,11 @@ def run_python_unit(repo: Path, work_root: Path, run_id: str, *, log_dir: Path |
     work_root.mkdir(parents=True, exist_ok=True)
     log_root.mkdir(parents=True, exist_ok=True)
     isolation = lane_isolation_env(work_root, task="python")
+    isolation["PRODU2_VERIFY_PYTHON"] = _safe_python()
+    isolation.setdefault(
+        "PRODU2_VERIFY_VENV",
+        os.environ.get("PRODU2_VERIFY_VENV", "/data/prod2u/venvs/verify"),
+    )
     cmd = [
         _safe_python(),
         "-B",
@@ -461,19 +459,10 @@ def main() -> int:
     )
     args = parser.parse_args()
 
-    for key in (
-        "LD_LIBRARY_PATH",
-        "LD_PRELOAD",
-        "QT_PLUGIN_PATH",
-        "PYTHONHOME",
-        "PYTHONPATH",
-        "PYTHONEXECUTABLE",
-        "PERL5LIB",
-        "PERL_LOCAL_LIB_ROOT",
-        "PERL_MB_OPT",
-        "PERL_MM_OPT",
-    ):
-        os.environ.pop(key, None)
+    strip_poison_env()
+    ensure_safe_sys_executable()
+    if not os.environ.get("PRODU2_VERIFY_PYTHON", "").strip():
+        os.environ["PRODU2_VERIFY_PYTHON"] = _safe_python()
     _prefer_oss_cad_on_path()
 
     repo = _repo_root

+ 102 - 0
tools/tool_env.py

@@ -0,0 +1,102 @@
+"""LD-safe Python / env helpers for Prod2U verify lanes.
+
+OSS CAD Suite's real interpreter lives at ``libexec/python3.11`` and needs
+``libpython`` from ``$OSS/lib``. The durable launcher is ``py3bin/python3.11``
+(or the verify venv symlink to it), which invokes ld-linux with an explicit
+``--library-path`` and must **not** rely on a global ``LD_LIBRARY_PATH``
+(TD Anlogic libs must stay out of OSS/Python/cocotb/Verilator).
+
+When a process is started via that wrapper, CPython still reports
+``sys.executable`` as the bare ``libexec`` binary. CLI tests that spawn
+``[sys.executable, ...]`` then exit 127 after poison-strip. Rewrite
+``sys.executable`` (and prefer ``PRODU2_VERIFY_PYTHON``) so children re-enter
+the LD-safe wrapper without reintroducing TD library pollution.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from pathlib import Path
+from typing import Mapping, MutableMapping
+
+# Keys that must not leak from Anlogic TD / host into OSS verify children.
+POISON_ENV_KEYS: tuple[str, ...] = (
+    "LD_LIBRARY_PATH",
+    "LD_PRELOAD",
+    "QT_PLUGIN_PATH",
+    "PYTHONHOME",
+    "PYTHONPATH",
+    "PYTHONEXECUTABLE",
+    "PERL5LIB",
+    "PERL_LOCAL_LIB_ROOT",
+    "PERL_MB_OPT",
+    "PERL_MM_OPT",
+)
+
+
+def strip_poison_env(env: MutableMapping[str, str] | None = None) -> MutableMapping[str, str]:
+    """Remove TD/host poison keys from ``env`` (or ``os.environ``)."""
+    target: MutableMapping[str, str] = os.environ if env is None else env
+    for key in POISON_ENV_KEYS:
+        target.pop(key, None)
+    return target
+
+
+def _is_libexec_python(path: Path) -> bool:
+    return "libexec" in path.as_posix()
+
+
+def safe_python() -> str:
+    """Return an LD-safe Python launcher path for verify/CLI subprocesses."""
+    override = os.environ.get("PRODU2_VERIFY_PYTHON", "").strip()
+    if override:
+        candidate = Path(override).expanduser()
+        if candidate.is_file():
+            return str(candidate)
+
+    exe = Path(sys.executable)
+    if not _is_libexec_python(exe):
+        return str(exe)
+
+    # libexec/python3.11 -> py3bin/python3.11 (OSS CAD durable wrapper)
+    sibling = exe.parent.parent / "py3bin" / exe.name
+    if sibling.is_file():
+        return str(sibling)
+
+    venv = os.environ.get("PRODU2_VERIFY_VENV", "").strip()
+    if venv:
+        for name in ("python", "python3"):
+            candidate = Path(venv).expanduser() / "bin" / name
+            if candidate.is_file():
+                return str(candidate)
+
+    default_venv = Path("/data/prod2u/venvs/verify/bin/python")
+    if default_venv.is_file():
+        return str(default_venv)
+
+    default_py3bin = Path("/data/prod2u/oss-cad-suite/latest/py3bin/python3.11")
+    if default_py3bin.is_file():
+        return str(default_py3bin)
+
+    return str(exe)
+
+
+def ensure_safe_sys_executable() -> str:
+    """Point ``sys.executable`` at the LD-safe wrapper when it is bare libexec."""
+    current = Path(sys.executable)
+    if not _is_libexec_python(current):
+        return str(current)
+    safe = safe_python()
+    if Path(safe).is_file() and Path(safe).as_posix() != current.as_posix():
+        sys.executable = safe
+    return sys.executable
+
+
+def verify_child_env(extra: Mapping[str, str] | None = None) -> dict[str, str]:
+    """Env for verify-python children: poison stripped, safe interpreter advertised."""
+    env = strip_poison_env(os.environ.copy())
+    env["PRODU2_VERIFY_PYTHON"] = safe_python()
+    if extra:
+        env.update(extra)
+    return env

+ 3 - 0
tools/verify.sh

@@ -25,6 +25,9 @@ PY="$VENV/bin/python"
 if [[ ! -x "$PY" ]]; then
   PY=python3
 fi
+# Advertise LD-safe launcher for CLI subprocesses (sys.executable may be libexec).
+export PRODU2_VERIFY_VENV="$VENV"
+export PRODU2_VERIFY_PYTHON="$PY"
 
 RUN_ID="${PRODU2_RUN_ID:-$(date -u +%Y%m%dT%H%M%SZ)-$(openssl rand -hex 4 2>/dev/null || python3 -c 'import uuid; print(uuid.uuid4().hex[:8])')}"
 STATE="${XDG_STATE_HOME:-$HOME/.local/state}/prod2u/runs/$RUN_ID"