| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266 |
- """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
|