resource_scheduler.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. """Host-aware resource classes and per-task build/log isolation.
  2. Used by the verification matrix and compact-packager test orchestration.
  3. Reads nproc / MemAvailable / free disk; classifies tasks as
  4. light / medium / heavy / exclusive; allocates independent build and log
  5. directories so parallel lanes never share a sim_build tree. TD is always
  6. exclusive.
  7. """
  8. from __future__ import annotations
  9. import os
  10. import shutil
  11. from pathlib import Path
  12. from typing import Any, Iterable, Mapping
  13. RESOURCE_CLASSES = ("light", "medium", "heavy", "exclusive")
  14. # Approximate resident budgets used only for concurrency planning (not fake %).
  15. CLASS_MEM_KB: dict[str, int] = {
  16. "light": 256 * 1024,
  17. "medium": 512 * 1024,
  18. "heavy": 1536 * 1024,
  19. "exclusive": 2048 * 1024,
  20. }
  21. # Matrix lanes + compact-packager related tasks for upcoming test matrix runs.
  22. TASK_RESOURCE_CLASS: dict[str, str] = {
  23. # Verification matrix
  24. "python": "light",
  25. "board_viewer": "light",
  26. "icarus": "medium",
  27. "cocotb": "medium",
  28. "verilator": "heavy",
  29. "formal": "heavy",
  30. "td": "exclusive",
  31. # Compact packager orchestration (P1/P2/P6 consumers)
  32. "package_selftest": "light",
  33. "package_adversarial": "light",
  34. "package_content_replay": "medium",
  35. "package_detached_replay": "medium",
  36. "doc_truth": "light",
  37. "board_detached_derived": "medium",
  38. }
  39. TD_EXCLUSIVE = frozenset({"td"})
  40. # Shared relative names that must never be reused across concurrent tasks.
  41. _FORBIDDEN_SHARED_BUILD_NAMES = frozenset(
  42. {
  43. "sim_build",
  44. "sim-build",
  45. "simulation_build",
  46. }
  47. )
  48. def host_resources(*, disk_path: str | os.PathLike[str] = "/") -> dict[str, Any]:
  49. """Read nproc, MemAvailable (KiB), and free disk bytes."""
  50. nproc = os.cpu_count() or 1
  51. mem_available_kb: int | None = None
  52. try:
  53. with open("/proc/meminfo", encoding="utf-8") as handle:
  54. for line in handle:
  55. if line.startswith("MemAvailable:"):
  56. mem_available_kb = int(line.split()[1])
  57. break
  58. except OSError:
  59. mem_available_kb = None
  60. try:
  61. disk_free_bytes = shutil.disk_usage(os.fspath(disk_path)).free
  62. except OSError:
  63. disk_free_bytes = None
  64. return {
  65. "nproc": nproc,
  66. "mem_available_kb": mem_available_kb,
  67. "mem_available_gib": (
  68. round(mem_available_kb / (1024 * 1024), 2) if mem_available_kb is not None else None
  69. ),
  70. "disk_free_bytes": disk_free_bytes,
  71. "disk_free_gib": (
  72. round(disk_free_bytes / (1024**3), 2) if disk_free_bytes is not None else None
  73. ),
  74. }
  75. def classify_task(task: str, overrides: Mapping[str, str] | None = None) -> str:
  76. """Return light/medium/heavy/exclusive for a task name."""
  77. if overrides and task in overrides:
  78. value = overrides[task]
  79. else:
  80. value = TASK_RESOURCE_CLASS.get(task, "medium")
  81. if value not in RESOURCE_CLASSES:
  82. raise ValueError(f"unknown resource class for task {task!r}: {value!r}")
  83. return value
  84. def _sanitize_task_name(task: str) -> str:
  85. cleaned = "".join(ch if ch.isalnum() or ch in ("-", "_", ".") else "_" for ch in task.strip())
  86. return cleaned or "task"
  87. def allocate_task_dirs(
  88. run_root: Path | str,
  89. task: str,
  90. *,
  91. run_id: str = "",
  92. create: bool = True,
  93. ) -> dict[str, Path]:
  94. """Independent build + log dirs under run_root for one task.
  95. Layout:
  96. {run_root}/builds/{task}[-{run_id8}]/
  97. {run_root}/logs/{task}[-{run_id8}]/
  98. Never returns a path whose basename is a shared sim_build name.
  99. """
  100. root = Path(run_root).expanduser().resolve()
  101. safe = _sanitize_task_name(task)
  102. suffix = ""
  103. if run_id:
  104. hexish = "".join(c for c in run_id.lower() if c in "0123456789abcdef")
  105. if hexish:
  106. suffix = f"-{hexish[:8]}"
  107. else:
  108. suffix = f"-{_sanitize_task_name(run_id)[:8]}"
  109. leaf = f"{safe}{suffix}"
  110. if leaf in _FORBIDDEN_SHARED_BUILD_NAMES or safe in _FORBIDDEN_SHARED_BUILD_NAMES:
  111. leaf = f"task-{leaf}"
  112. build_dir = root / "builds" / leaf
  113. log_dir = root / "logs" / leaf
  114. work_root = build_dir # harness --work-root points here
  115. for path in (build_dir, log_dir):
  116. if path.name in _FORBIDDEN_SHARED_BUILD_NAMES:
  117. raise ValueError(f"refusing shared build name: {path}")
  118. if create:
  119. path.mkdir(parents=True, exist_ok=True)
  120. return {
  121. "run_root": root,
  122. "task": safe,
  123. "build_dir": build_dir,
  124. "log_dir": log_dir,
  125. "work_root": work_root,
  126. }
  127. def lane_isolation_env(work_root: Path | str, *, task: str = "") -> dict[str, str]:
  128. """Env vars that keep TEMP/pycache/cocotb builds inside the task work root.
  129. Avoids a shared repo-level sim_build when multiple lanes run in parallel.
  130. """
  131. root = Path(work_root).expanduser().resolve()
  132. temp = root / "tmp"
  133. pycache = root / "pycache"
  134. cocotb_build = root / "cocotb_build"
  135. for path in (temp, pycache, cocotb_build):
  136. path.mkdir(parents=True, exist_ok=True)
  137. env = {
  138. "TMPDIR": str(temp),
  139. "TMP": str(temp),
  140. "TEMP": str(temp),
  141. "PYTHONPYCACHEPREFIX": str(pycache),
  142. "PROD2U_COCOTB_BUILD_DIR": str(cocotb_build),
  143. }
  144. if task:
  145. env["PROD2U_TASK_NAME"] = task
  146. env["PROD2U_TASK_WORK_ROOT"] = str(root)
  147. return env
  148. def plan_concurrency(
  149. selected: Iterable[str],
  150. *,
  151. max_workers_cap: int | None = None,
  152. class_overrides: Mapping[str, str] | None = None,
  153. host: Mapping[str, Any] | None = None,
  154. disk_path: str | os.PathLike[str] = "/",
  155. ) -> dict[str, Any]:
  156. """Derive open-source worker count from host resources and lane classes.
  157. - TD (exclusive) never shares the pool; callers run it alone after OSS lanes.
  158. - Formal is heavy and memory-capped: at most one formal job; on small hosts
  159. heavy lanes do not overlap.
  160. """
  161. selected_list = [str(item) for item in selected]
  162. host_info = dict(host) if host is not None else host_resources(disk_path=disk_path)
  163. nproc = int(host_info.get("nproc") or 1)
  164. mem_kb = host_info.get("mem_available_kb")
  165. disk_free = host_info.get("disk_free_bytes")
  166. open_lanes = [lane for lane in selected_list if lane not in TD_EXCLUSIVE]
  167. classes = {lane: classify_task(lane, class_overrides) for lane in open_lanes}
  168. has_formal = "formal" in open_lanes
  169. has_heavy = any(classes[lane] == "heavy" for lane in open_lanes)
  170. disk_ok = disk_free is None or int(disk_free) >= 2 * 1024**3
  171. formal_slots = 0
  172. if mem_kb is None:
  173. workers = 1 if has_heavy else min(2, nproc)
  174. formal_slots = 1 if has_formal else 0
  175. else:
  176. mem_kb_i = int(mem_kb)
  177. usable = max(0, mem_kb_i - 512 * 1024)
  178. if has_formal and mem_kb_i < 3500 * 1024:
  179. formal_slots = 1
  180. workers = 1 if has_heavy else min(2, nproc)
  181. else:
  182. formal_slots = 1 if has_formal else 0
  183. budget_workers = max(1, usable // CLASS_MEM_KB["medium"])
  184. workers = max(1, min(nproc, budget_workers, 4))
  185. if has_heavy and mem_kb_i < 2500 * 1024:
  186. workers = 1
  187. if not disk_ok:
  188. workers = 1
  189. if max_workers_cap is not None:
  190. workers = max(1, min(workers, max_workers_cap))
  191. workers = max(1, min(workers, max(1, len(open_lanes) or 1)))
  192. if not open_lanes:
  193. workers = 1
  194. return {
  195. "host": host_info,
  196. "open_lanes": open_lanes,
  197. "lane_classes": classes,
  198. "max_workers": workers,
  199. "formal_slots": formal_slots,
  200. "td_exclusive": bool(any(lane in TD_EXCLUSIVE for lane in selected_list)),
  201. "disk_ok": disk_ok,
  202. }
  203. def schedule_waves(open_lanes: list[str], plan: Mapping[str, Any]) -> list[list[str]]:
  204. """Partition open-source lanes into waves respecting memory / formal caps."""
  205. if not open_lanes:
  206. return []
  207. workers = int(plan["max_workers"])
  208. mem_kb = (plan.get("host") or {}).get("mem_available_kb")
  209. classes = plan.get("lane_classes") or {
  210. lane: classify_task(lane) for lane in open_lanes
  211. }
  212. if workers <= 1 or (mem_kb is not None and int(mem_kb) < 2500 * 1024):
  213. light_medium = [
  214. lane for lane in open_lanes if classes.get(lane) in ("light", "medium")
  215. ]
  216. heavy = [lane for lane in open_lanes if classes.get(lane) == "heavy"]
  217. waves: list[list[str]] = []
  218. if light_medium:
  219. waves.append(light_medium)
  220. for lane in heavy:
  221. waves.append([lane])
  222. return waves or [list(open_lanes)]
  223. return [list(open_lanes)]
  224. def assert_not_shared_sim_build(path: Path | str) -> Path:
  225. """Raise if path basename is a forbidden shared simulation build name."""
  226. resolved = Path(path).expanduser().resolve()
  227. if resolved.name in _FORBIDDEN_SHARED_BUILD_NAMES:
  228. raise ValueError(
  229. f"refusing shared sim_build path {resolved}; "
  230. "use allocate_task_dirs() for per-task isolation"
  231. )
  232. return resolved