Skip to content

The agent that grows with you

fix(platform): host facts are right on every OS and read no environment

alt-glitch5384e22099a4
diff --git a/hermes_platform/host/darwin_pci.py b/hermes_platform/host/darwin_pci.py
new file mode 100644
index 00000000000..11ae510b062
--- /dev/null
+++ b/hermes_platform/host/darwin_pci.py
@@ -0,0 +1,77 @@
+"""PCI display controllers on macOS, read from the IOKit registry.
+
+Intel Macs name their GPU vendors here; Apple silicon has no PCI display controller. Read through
+ctypes without environment-variable input or subprocesses.
+"""
+
+from __future__ import annotations
+
+import ctypes
+import ctypes.util
+
+_UTF8 = 0x08000100 # kCFStringEncodingUTF8
+_DISPLAY_CLASS = 0x03 # PCI base class: display controller
+_MAX_DEVICES = 256
+
+
+def _data_int(cf, ref: int | None) -> int | None:
+ """Little-endian integer from a CFData property, or ``None`` for a missing or non-data value."""
+ if not ref:
+ return None
+ try:
+ if cf.CFGetTypeID(ref) != cf.CFDataGetTypeID():
+ return None
+ size = cf.CFDataGetLength(ref)
+ return int.from_bytes(ctypes.string_at(cf.CFDataGetBytePtr(ref), size), "little") if size else None
+ finally:
+ cf.CFRelease(ref)
+
+
+def _bind(iokit, cf) -> None:
+ cf.CFStringCreateWithCString.restype = ctypes.c_void_p
+ cf.CFStringCreateWithCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_uint32]
+ cf.CFGetTypeID.restype = cf.CFDataGetTypeID.restype = ctypes.c_ulong
+ cf.CFGetTypeID.argtypes = [ctypes.c_void_p]
+ cf.CFDataGetLength.restype = ctypes.c_long
+ cf.CFDataGetLength.argtypes = [ctypes.c_void_p]
+ cf.CFDataGetBytePtr.restype = ctypes.c_void_p
+ cf.CFDataGetBytePtr.argtypes = [ctypes.c_void_p]
+ cf.CFRelease.argtypes = [ctypes.c_void_p]
+ iokit.IOServiceMatching.restype = ctypes.c_void_p
+ iokit.IOServiceMatching.argtypes = [ctypes.c_char_p]
+ iokit.IOServiceGetMatchingServices.argtypes = [ctypes.c_uint32, ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint32)]
+ iokit.IOIteratorNext.restype = ctypes.c_uint32
+ iokit.IOIteratorNext.argtypes = [ctypes.c_uint32]
+ iokit.IORegistryEntryCreateCFProperty.restype = ctypes.c_void_p
+ iokit.IORegistryEntryCreateCFProperty.argtypes = [ctypes.c_uint32, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32]
+ iokit.IOObjectRelease.argtypes = [ctypes.c_uint32]
+
+
+def display_vendor_ids() -> list[str] | None:
+ """Hex PCI vendor ids of every display controller, or ``None`` when IOKit cannot be read."""
+ iokit = ctypes.CDLL(ctypes.util.find_library("IOKit"))
+ cf = ctypes.CDLL(ctypes.util.find_library("CoreFoundation"))
+ _bind(iokit, cf)
+ iterator = ctypes.c_uint32()
+ # The matching dictionary is consumed by the call; port 0 is kIOMainPortDefault.
+ if iokit.IOServiceGetMatchingServices(0, iokit.IOServiceMatching(b"IOPCIDevice"), ctypes.byref(iterator)) != 0:
+ return None
+ keys = {name: cf.CFStringCreateWithCString(None, name.encode(), _UTF8) for name in ("class-code", "vendor-id")}
+ vendors: list[str] = []
+ try:
+ for _ in range(_MAX_DEVICES):
+ entry = iokit.IOIteratorNext(iterator)
+ if not entry:
+ break
+ try:
+ read = {name: _data_int(cf, iokit.IORegistryEntryCreateCFProperty(entry, key, None, 0))
+ for name, key in keys.items()}
+ finally:
+ iokit.IOObjectRelease(entry)
+ if read["class-code"] is not None and read["class-code"] >> 16 == _DISPLAY_CLASS:
+ vendors.append("" if read["vendor-id"] is None else f"{read['vendor-id'] & 0xFFFF:04x}")
+ finally:
+ iokit.IOObjectRelease(iterator.value)
+ for key in keys.values():
+ cf.CFRelease(key)
+ return vendors
diff --git a/hermes_platform/host/facts.py b/hermes_platform/host/facts.py
index b609a91e370..87deaac12e5 100644
--- a/hermes_platform/host/facts.py
+++ b/hermes_platform/host/facts.py
@@ -1,6 +1,7 @@
"""Cached OS, architecture, CPU, memory and GPU facts for the current machine.
-Native architecture remains accurate when the Python process is emulated.
+Native architecture remains accurate when the Python process is emulated. Facts read the registry,
+sysctl, IOKit, procfs or sysfs: never the environment, a subprocess or a GPU driver library.
"""
from __future__ import annotations
@@ -9,6 +10,9 @@ import functools
import os
import platform
import sys
+import sysconfig
+
+from hermes_platform.host import darwin_pci
_ARCH_NAMES = {
"amd64": "amd64", "x86_64": "amd64", "x64": "amd64",
@@ -16,6 +20,9 @@ _ARCH_NAMES = {
"x86": "x86", "i386": "x86", "i686": "x86",
}
IMAGE_FILE_MACHINE = {0x8664: "amd64", 0xAA64: "arm64", 0x014C: "x86"}
+# The interpreter's own build: on Windows, platform.machine() names the native machine even
+# inside an x64 process emulated on arm64.
+_WINDOWS_BUILD_ARCH = {"win-amd64": "amd64", "win-arm64": "arm64", "win32": "x86"}
def normalize_arch(raw: str | None) -> str:
@@ -32,22 +39,14 @@ def os_family() -> str:
@functools.cache
def process_arch() -> str:
"""Return the architecture of this Python process."""
+ if sys.platform == "win32":
+ return _WINDOWS_BUILD_ARCH.get(sysconfig.get_platform(), "unknown")
return normalize_arch(platform.machine())
-def windows_native_arch(*, wow64_native: int | None, machine: str, env_arch: str | None) -> str:
- """Return the native architecture from Windows observations.
-
- Order matters: ``PROCESSOR_ARCHITECTURE`` reads ``AMD64`` inside an x64-emulated process
- on ARM64 hardware, so the environment is consulted only when both APIs are unavailable.
- """
- name = IMAGE_FILE_MACHINE.get(wow64_native or 0)
- if name:
- return name
- normalized = normalize_arch(machine)
- if normalized != "unknown":
- return normalized
- return normalize_arch(env_arch)
+def windows_native_arch(*, wow64_native: int | None, machine: str) -> str:
+ """Return the native architecture: ``IsWow64Process2``'s native machine, else ``platform.machine()``."""
+ return IMAGE_FILE_MACHINE.get(wow64_native or 0) or normalize_arch(machine)
def _wow64_native_machine() -> int | None:
@@ -84,8 +83,7 @@ def native_arch() -> str:
wow64 = _wow64_native_machine()
except (OSError, AttributeError, TypeError, ValueError):
wow64 = None
- env_arch = os.environ.get("PROCESSOR_ARCHITEW6432") or os.environ.get("PROCESSOR_ARCHITECTURE")
- return windows_native_arch(wow64_native=wow64, machine=platform.machine(), env_arch=env_arch)
+ return windows_native_arch(wow64_native=wow64, machine=platform.machine())
if sys.platform == "darwin" and process_arch() == "amd64" and _darwin_translated():
return "arm64"
return process_arch()
@@ -105,7 +103,7 @@ def parse_cpuinfo(text: str, *, device_tree_model: str = "") -> str:
def _read_text(path: str, limit: int = 65536) -> str:
try:
- with open(path, "r", encoding="utf-8", errors="replace") as handle:
+ with open(path, "r", encoding="utf-8-sig", errors="replace") as handle:
return handle.read(limit)
except OSError:
return ""
@@ -170,16 +168,36 @@ def cpu_model() -> str:
return parse_cpuinfo(_read_text("/proc/cpuinfo"), device_tree_model=_read_text("/proc/device-tree/model", 512))
+# ARM's MIDR implementer codes, as arm64 Linux prints them in ``CPU implementer``.
+_ARM_IMPLEMENTERS = {
+ 0x41: "ARM", 0x42: "Broadcom", 0x43: "Cavium", 0x46: "Fujitsu", 0x48: "HiSilicon", 0x4E: "NVIDIA",
+ 0x50: "Ampere", 0x51: "Qualcomm", 0x61: "Apple", 0x69: "Intel", 0x6D: "Microsoft", 0xC0: "Ampere",
+}
+
+
+def parse_cpuinfo_vendor(text: str) -> str:
+ """Return ``vendor_id`` (x86) or the named ``CPU implementer`` (arm64) from ``/proc/cpuinfo``."""
+ pairs = (line.split(":", 1) for line in text.splitlines() if ":" in line)
+ fields = {key.strip(): value.strip() for key, value in pairs}
+ if fields.get("vendor_id"):
+ return fields["vendor_id"]
+ try:
+ return _ARM_IMPLEMENTERS.get(int(fields.get("CPU implementer", ""), 16), "")
+ except ValueError:
+ return ""
+
+
@functools.cache
def cpu_vendor() -> str:
- """Return the CPU vendor, or an empty string when unavailable."""
+ """Return the CPU vendor, or an empty string when unavailable.
+
+ Windows reports the SoC vendor (``NVIDIA`` on an N1X); arm64 Linux reports the core designer.
+ """
if sys.platform == "win32":
return _winreg_str(_CPU_KEY, "VendorIdentifier")
- if sys.platform.startswith("linux"):
- for line in _read_text("/proc/cpuinfo").splitlines():
- if line.lower().startswith("vendor_id") and ":" in line:
- return line.split(":", 1)[1].strip()
- return ""
+ if sys.platform == "darwin":
+ return "Apple" if native_arch() == "arm64" else _sysctl_str(b"machdep.cpu.vendor")
+ return parse_cpuinfo_vendor(_read_text("/proc/cpuinfo"))
def parse_meminfo_total(text: str) -> int | None:
@@ -254,10 +272,26 @@ def _linux_gpu_vendor_ids() -> list[str] | None:
return [_read_text(f"{root}/{card}/device/vendor", 16).strip() for card in cards]
-def _windows_gpu_vendor_ids() -> list[str] | None:
+def parse_windows_display_adapters(rows: list[tuple[str, str, str]]) -> list[tuple[str, str]]:
+ """``(vendor id, description)`` per adapter from display-class ``(subkey, MatchingDeviceId, DriverDesc)``.
+
+ Virtual adapters (no ``VEN_`` id, such as the remote-display driver) are skipped; an
+ adapter subkey without a readable id keeps an empty vendor so it counts as unreadable.
+ """
+ adapters = []
+ for subkey, device_id, description in rows:
+ if "VEN_" in device_id.upper():
+ adapters.append((device_id.upper().split("VEN_", 1)[1][:4], description))
+ elif subkey.isdigit() and not device_id:
+ adapters.append(("", description))
+ return adapters
+
+
+def _windows_display_adapters() -> tuple[tuple[str, str], ...] | None:
import winreg
- vendors = []
+ rows = []
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _DISPLAY_CLASS_KEY) as root:
for index in range(_GPU_SCAN_LIMIT):
@@ -265,33 +299,38 @@ def _windows_gpu_vendor_ids() -> list[str] | None:
subkey = winreg.EnumKey(root, index)
except OSError:
break
- device_id = _winreg_str(f"{_DISPLAY_CLASS_KEY}\\{subkey}", "MatchingDeviceId").upper()
- if "VEN_" in device_id:
- vendors.append(device_id.split("VEN_", 1)[1][:4])
- elif subkey.isdigit(): # an adapter whose id could not be read
- vendors.append("")
+ path = f"{_DISPLAY_CLASS_KEY}\\{subkey}"
+ rows.append((subkey, _winreg_str(path, "MatchingDeviceId"), _winreg_str(path, "DriverDesc")))
except OSError:
return None
- return vendors
+ return tuple(parse_windows_display_adapters(rows))
+
+
+# The WSL GPU bridge mounts the Windows NVIDIA driver's CUDA library here only when that driver is installed.
+_WSL_NVIDIA_CUDA = "/usr/lib/wsl/lib/libcuda.so.1"
@functools.cache
def gpu_class() -> str:
"""Return ``nvidia``/``amd``/``intel``/``apple_silicon``/``none``, or ``unknown``.
- Reads sysfs, the registry or sysctl only: never a subprocess or a driver library.
+ Apple silicon by architecture; Intel Macs by IOKit PCI display controllers; Windows by the
+ display-class registry; Linux by the NVIDIA driver's procfs, the WSL GPU bridge, then sysfs DRM cards.
"""
try:
if sys.platform == "darwin":
- return "apple_silicon" if native_arch() == "arm64" else "unknown"
- if sys.platform == "win32":
- vendors = _windows_gpu_vendor_ids()
- return "unknown" if vendors is None else classify_gpu_vendors(vendors)
+ if native_arch() == "arm64":
+ return "apple_silicon"
+ vendors = darwin_pci.display_vendor_ids()
+ elif sys.platform == "win32":
+ adapters = _windows_display_adapters()
+ vendors = None if adapters is None else [vendor for vendor, _ in adapters]
+ elif os.path.exists("/proc/driver/nvidia/version") or os.path.exists(_WSL_NVIDIA_CUDA):
+ return "nvidia"
+ else:
+ vendors = _linux_gpu_vendor_ids()
except (AttributeError, OSError, TypeError, ValueError):
return "unknown"
- if os.path.exists("/proc/driver/nvidia/version"):
- return "nvidia"
- vendors = _linux_gpu_vendor_ids()
return "unknown" if vendors is None else classify_gpu_vendors(vendors)
@@ -308,7 +347,13 @@ def parse_nvidia_gpu_model(information: str) -> str:
@functools.cache
def nvidia_gpu_names() -> tuple[str, ...]:
- """Model names the Linux NVIDIA driver reports per GPU; empty elsewhere or without the driver."""
+ """Names of the NVIDIA GPUs: Windows display-class ``DriverDesc``, Linux driver procfs ``Model``; else empty."""
+ if sys.platform == "win32":
+ try:
+ adapters = _windows_display_adapters() or ()
+ except (AttributeError, OSError, TypeError, ValueError):
+ return ()
+ return tuple(name for vendor, name in adapters if vendor.lower() == "10de" and name)
if not sys.platform.startswith("linux"):
return ()
try:
@@ -343,12 +388,12 @@ def interactive_session() -> bool:
return False
if sys.platform.startswith("linux"):
session_id = _read_text("/proc/self/sessionid", 64).strip()
- return bool(session_id and session_id != "4294967295" and os.path.isdir(f"/run/user/{os.getuid()}"))
+ return bool(session_id and session_id != "4294967295" and os.path.isdir(f"/run/user/{os.getuid()}")) # windows-footgun: ok — Linux branch
return True
def clear_caches() -> None:
"""Clear every cached host fact."""
for fact in (os_family, process_arch, native_arch, cpu_model, cpu_vendor, ram_total_bytes, gpu_class,
- nvidia_gpu_names):
+ nvidia_gpu_names, _windows_display_adapters):
fact.cache_clear()
diff --git a/tests/hermes_platform/test_facts.py b/tests/hermes_platform/test_facts.py
index 24924b758be..f6a4c031f0e 100644
--- a/tests/hermes_platform/test_facts.py
+++ b/tests/hermes_platform/test_facts.py
@@ -22,27 +22,53 @@ def test_normalize_arch(raw: str, expected: str) -> None:
assert facts.normalize_arch(raw) == expected
@pytest.mark.parametrize(
- ("wow64_native", "machine", "env_arch", "expected"),
+ ("wow64_native", "machine", "expected"),
[
- (0xAA64, "AMD64", "x86", "arm64"),
- (None, "x86_64", "ARM64", "amd64"),
- (None, "unknown", "ARM64", "arm64"),
+ (0xAA64, "AMD64", "arm64"),
+ (0xAA64, "ARM64", "arm64"), # x64 Python on an N1X, measured: platform.machine() is native
+ (None, "x86_64", "amd64"),
+ (None, "unknown", "unknown"),
],
)
-def test_windows_native_arch_precedence(
- wow64_native: int | None,
- machine: str,
- env_arch: str | None,
- expected: str,
-) -> None:
- assert (
- facts.windows_native_arch(
- wow64_native=wow64_native,
- machine=machine,
- env_arch=env_arch,
- )
- == expected
- )
+def test_windows_native_arch_precedence(wow64_native: int | None, machine: str, expected: str) -> None:
+ assert facts.windows_native_arch(wow64_native=wow64_native, machine=machine) == expected
+
+
+# Display-class registry rows measured on an NVIDIA N1X laptop.
+_N1X_DISPLAY_ROWS = [
+ ("0000", r"pci\ven_10de&dev_2e03&subsys_33091043", "NVIDIA RTX Spark N1X (6144-core Blackwell RTX GPU)"),
+ ("0001", r"acpi\ven_nvda&dev_200a&rev_0034", "NVIDIA NPU"),
+ ("0002", r"pci\ven_10de&dev_2e06&subsys_33091043", "NVIDIA RTX Spark N1X (5120-core Blackwell RTX GPU)"),
+ ("0003", "RdpIdd_IndirectDisplay", "Microsoft Remote Display Adapter"),
+ ("Configuration", "", ""),
+]
+
+
+ ("rows", "gpu_class"),
+ [
+ (_N1X_DISPLAY_ROWS, "nvidia"),
+ ([("0000", "RdpIdd_IndirectDisplay", "Microsoft Remote Display Adapter")], "none"),
+ ([("0000", "", "")], "unknown"),
+ ],
+)
+def test_windows_display_adapters_classify_the_gpu(rows, gpu_class) -> None:
+ adapters = facts.parse_windows_display_adapters(rows)
+ assert facts.classify_gpu_vendors([vendor for vendor, _ in adapters]) == gpu_class
+
+
+ ("cpuinfo", "vendor"),
+ [
+ ("processor : 0\nvendor_id : GenuineIntel\nmodel name : Intel Xeon\n", "GenuineIntel"),
+ ("processor : 0\nCPU implementer : 0x41\nCPU part : 0xd87\n", "ARM"),
+ ("processor : 0\nCPU implementer : 0x61\n", "Apple"),
+ ("processor : 0\nCPU implementer : 0xee\n", ""),
+ ("processor : 0\n", ""),
+ ],
+)
+def test_cpu_vendor_from_cpuinfo(cpuinfo: str, vendor: str) -> None:
+ assert facts.parse_cpuinfo_vendor(cpuinfo) == vendor
@pytest.mark.parametrize(
("text", "device_tree_model", "expected"),
@@ -81,11 +107,13 @@ def test_windows_native_arch_matches_registry_identifier(cleared_fact_caches) ->
@pytest.mark.platforms("macos")
def test_macos_live_cpu_facts(cleared_fact_caches) -> None:
assert facts.cpu_model()
+ assert facts.cpu_vendor()
assert facts.native_arch() in {"arm64", "amd64"}
+ assert facts.gpu_class() != "unknown"
@pytest.mark.platforms("linux")
def test_linux_live_cpu_facts_match_cpuinfo(cleared_fact_caches) -> None:
cpuinfo = Path("/proc/cpuinfo").read_text(encoding="utf-8", errors="replace")
- assert facts.cpu_vendor() in cpuinfo
+ assert facts.cpu_vendor() == facts.parse_cpuinfo_vendor(cpuinfo)
assert facts.cpu_model() in cpuinfo