Skip to content

A GPU task manager for Windows, Linux, and WSL: per-process VRAM, GPU activity, and LLM model/KV-cache insights (Windows AMD and NVIDIA).

Python

Resolve root display adapter names by exact Windows LUID

Scott Hanselman6aa71a88d6d0
diff --git a/README.md b/README.md
index fcff4f3..bd1ad57 100644
--- a/README.md
+++ b/README.md
@@ -513,7 +513,8 @@ Under multi-GPU WSL, host attribution is disabled with a reason rather than risk
two devices by memory usage; Linux processes are listed once with GPU `?`, because `/dev/dxg`
does not identify their GPU. `--gpu N` retains the existing single-device host matching.
-`--list-gpus` lists selectable hardware adapters with their vendor and LUID. `--gpu N` selects
+`--list-gpus` lists selectable non-software DXGI adapters on Windows (including root-enumerated
+display adapters), or hardware adapters on other platforms, with their vendor and adapter key. `--gpu N` selects
one of these adapters: NVIDIA adapters are listed first, followed by other vendors, with each
group ordered by dedicated memory. An out-of-range
index is rejected rather than silently selecting another device. Compute-only devices such as an
@@ -525,6 +526,20 @@ If a unique match cannot be established, telemetry is unavailable; buffer logs c
so model-buffer attribution across GPUs is not yet reliable. This conservative matching also applies
to NVIDIA and may suppress telemetry when Windows does not expose a usable PCI address.
+On Windows, each exact DXGI LUID is also resolved through `DisplayConfigGetDeviceInfo` to its
+PnP device interface, including inactive displays, then read through SetupAPI. A `ROOT\DISPLAY`
+instance uses its PnP friendly name (device description as fallback) and is labelled `ROOT display
+adapter` in `--list-gpus`, rather than inheriting the physical GPU's DXGI name or vendor label.
+It stays selectable at the same index, is not paired with PCI telemetry, and still needs matching
+LUID counters to show usage. A missing PnP name gives an explicit root-display label; a failed
+identity lookup retains the DXGI description with a reason in the list, text, TUI and JSON
+`counter_status`. JSON `adapter.device_instance_id` records the resolved instance (empty if unknown);
+`adapter.identity_status` records lookup limitations. Physical adapter names and ordering are unchanged.
+The StarDesk inactive virtual-display case is covered by mocked API regressions, **not yet validated
+with StarDesk installed**. Read-only live checks on Windows 11 build 28000, NVIDIA RTX Spark N1X,
+driver 32.0.16.2114 confirmed its physical PCI identity and unchanged display name; no display
+configuration or drivers were changed.
+
AMD adapters can be selected and use the existing Windows GPU process counters; HIP runtime DLLs
are recognized as runtime evidence. On supported drivers, the AMD Display Library supplied by the
Windows driver can provide graphics activity, clocks, edge temperature, board or ASIC power, fan
@@ -813,7 +828,7 @@ Identification is designed to stay cheap. Measured on one Windows machine:
| Probe | Cost | Used |
|---|---|---|
| Process list, command line, listening ports | under 1 ms | Once per process / every 5 s |
-| Windows adapter discovery (DXGI + PCI location, no telemetry sample) | ~0.40 ms median; first/cold call up to 14.1 ms in 30 reads (Windows 11 build 26340, RTX 4080 SUPER, NVIDIA 630.20) | TUI only, every 5 s; synchronous OS calls, not a hard latency bound. Other drivers/multi-GPU laptops unmeasured; provider reconstruction after changes/errors has additional driver-dependent cost |
+| Windows adapter discovery (DXGI + exact-LUID PnP identity + PCI location, no telemetry sample) | ~0.86 ms median, 2.60 ms max in 30 warm reads, 26.1 ms first/cold call (Windows 11 build 28000, RTX Spark N1X, driver 32.0.16.2114); same machine without the PnP probe: ~0.36 ms median | Once at startup; TUI rediscovery every 5 s. PnP uses fixed buffers, one interface lookup per adapter and at most two name-property reads, no path/device enumeration or retries. Synchronous OS calls are not a hard latency bound. Other drivers, virtual displays and multi-GPU laptops unmeasured; provider reconstruction has additional driver-dependent cost |
| Windows NVML handle reacquisition (no telemetry sample) | ~8.7 ms median, 9.3 ms max in 30 reads on the same machine | Every 5 s per active collector; retries initialization after NVML session-loss errors. Other drivers unmeasured |
| Memory-map scan (DLLs + mapped files) | 1-50 ms per process | New processes, a 64 MiB / 10% memory change, or every 2 min; at most 150 ms per refresh |
| GGUF header, model-store manifests | ms, cached | Once per file / every 60 s |
diff --git a/src/gputaskman/cli.py b/src/gputaskman/cli.py
index 666d034..cc98274 100644
--- a/src/gputaskman/cli.py
+++ b/src/gputaskman/cli.py
@@ -111,6 +111,8 @@ def main() -> None:
for i, adapter in enumerate(ordered_adapters(enumerate_adapters())):
print(f"{i}: {adapter.name} ({adapter.vendor}, LUID 0x{adapter.luid & 0xffffffffffffffff:016x})")
+ if adapter.identity_status:
+ print(f" {adapter.identity_status}")
return
_check_gpu(ap, args.gpu)
diff --git a/src/gputaskman/collector.py b/src/gputaskman/collector.py
index f2befa7..38d4c20 100644
--- a/src/gputaskman/collector.py
+++ b/src/gputaskman/collector.py
@@ -307,6 +307,7 @@ class Collector:
snap.counter_status = " ".join(filter(None, (
snap.counter_status, "NVIDIA telemetry stopped after this GPU was re-enabled; "
"restart gputaskman to restore it.")))
+ snap.counter_status = " ".join(filter(None, (snap.counter_status, self.adapter.identity_status)))
if self.drm_card is not None:
snap.process_status = self.counters.drm.status
live = [(pid, g) for pid, g in procs.items() if _is_live(g)]
diff --git a/src/gputaskman/dxgi.py b/src/gputaskman/dxgi.py
index 9c60742..3c44d9d 100644
--- a/src/gputaskman/dxgi.py
+++ b/src/gputaskman/dxgi.py
@@ -45,9 +45,17 @@ class Adapter:
shared_system: int
software: bool
pci_address: tuple[int, int, int] | None = None
+ device_instance_id: str = ""
+ identity_status: str = ""
+
+ @property
+ def root_display(self) -> bool:
+ return self.device_instance_id.upper().startswith("ROOT\\DISPLAY\\")
@property
def vendor(self) -> str:
+ if self.root_display:
+ return "ROOT display adapter"
return VENDORS.get(self.vendor_id, hex(self.vendor_id))
@@ -69,6 +77,113 @@ class _QueryAdapter(ctypes.Structure):
("data", ctypes.c_void_p), ("size", wintypes.UINT)]
+class _DeviceInfoHeader(ctypes.Structure):
+ _fields_ = [("kind", wintypes.UINT), ("size", wintypes.UINT),
+ ("luid", _LUID), ("id", wintypes.UINT)]
+
+
+class _AdapterName(ctypes.Structure):
+ _fields_ = [("header", _DeviceInfoHeader), ("path", ctypes.c_wchar * 128)]
+
+
+class _DeviceInterface(ctypes.Structure):
+ _fields_ = [("size", wintypes.DWORD), ("guid", _GUID), ("flags", wintypes.DWORD),
+ ("reserved", ctypes.c_size_t)]
+
+
+class _DeviceInfo(ctypes.Structure):
+ _fields_ = [("size", wintypes.DWORD), ("guid", _GUID), ("instance", wintypes.DWORD),
+ ("reserved", ctypes.c_size_t)]
+
+
+def adapter_identity(luid: int) -> tuple[str, str]:
+ """Resolve this exact LUID, including inactive displays, without enumerating other devices.
+
+ Fixed buffers and one call per property bound the work; OS calls themselves have no timeout.
+ A failed lookup leaves the DXGI description intact, with a reason supplied by the caller.
+ """
+ user = ctypes.WinDLL("user32")
+ get_name = user.DisplayConfigGetDeviceInfo
+ get_name.argtypes = [ctypes.POINTER(_DeviceInfoHeader)]
+ get_name.restype = wintypes.LONG
+ name = _AdapterName()
+ name.header = _DeviceInfoHeader(
+ 4, ctypes.sizeof(name), _LUID(luid & 0xffffffff, ctypes.c_int32(luid >> 32).value), 0)
+ status = get_name(ctypes.byref(name.header))
+ if status or not name.path:
+ raise OSError(f"DisplayConfig adapter path unavailable (error {status})")
+
+ setup = ctypes.WinDLL("setupapi", use_last_error=True)
+ setup.SetupDiCreateDeviceInfoList.argtypes = [ctypes.POINTER(_GUID), wintypes.HWND]
+ setup.SetupDiCreateDeviceInfoList.restype = wintypes.HANDLE
+ setup.SetupDiOpenDeviceInterfaceW.argtypes = [
+ wintypes.HANDLE, wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(_DeviceInterface)]
+ setup.SetupDiOpenDeviceInterfaceW.restype = wintypes.BOOL
+ setup.SetupDiGetDeviceInterfaceDetailW.argtypes = [
+ wintypes.HANDLE, ctypes.POINTER(_DeviceInterface), ctypes.c_void_p, wintypes.DWORD,
+ ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(_DeviceInfo)]
+ setup.SetupDiGetDeviceInterfaceDetailW.restype = wintypes.BOOL
+ setup.SetupDiGetDeviceInstanceIdW.argtypes = [
+ wintypes.HANDLE, ctypes.POINTER(_DeviceInfo), wintypes.LPWSTR, wintypes.DWORD,
+ ctypes.POINTER(wintypes.DWORD)]
+ setup.SetupDiGetDeviceInstanceIdW.restype = wintypes.BOOL
+ setup.SetupDiGetDeviceRegistryPropertyW.argtypes = [
+ wintypes.HANDLE, ctypes.POINTER(_DeviceInfo), wintypes.DWORD,
+ ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p, wintypes.DWORD,
+ ctypes.POINTER(wintypes.DWORD)]
+ setup.SetupDiGetDeviceRegistryPropertyW.restype = wintypes.BOOL
+ setup.SetupDiDestroyDeviceInfoList.argtypes = [wintypes.HANDLE]
+ setup.SetupDiDestroyDeviceInfoList.restype = wintypes.BOOL
+ devices = setup.SetupDiCreateDeviceInfoList(None, None)
+ if devices == ctypes.c_void_p(-1).value:
+ raise OSError(f"PnP device list unavailable (error {ctypes.get_last_error()})")
+ try:
+ interface = _DeviceInterface()
+ interface.size = ctypes.sizeof(interface)
+ if not setup.SetupDiOpenDeviceInterfaceW(devices, name.path, 0, ctypes.byref(interface)):
+ raise OSError(f"PnP adapter interface unavailable (error {ctypes.get_last_error()})")
+ detail = ctypes.create_string_buffer(4096)
+ # SP_DEVICE_INTERFACE_DETAIL_DATA_W has a packed WCHAR path but pointer-size alignment on x64.
+ ctypes.cast(detail, ctypes.POINTER(wintypes.DWORD))[0] = 8 if ctypes.sizeof(ctypes.c_void_p) == 8 else 6
+ info = _DeviceInfo()
+ info.size = ctypes.sizeof(info)
+ if not setup.SetupDiGetDeviceInterfaceDetailW(
+ devices, ctypes.byref(interface), detail, ctypes.sizeof(detail), None, ctypes.byref(info)):
+ raise OSError(f"PnP adapter details unavailable (error {ctypes.get_last_error()})")
+ instance = ctypes.create_unicode_buffer(512)
+ if not setup.SetupDiGetDeviceInstanceIdW(devices, ctypes.byref(info), instance, len(instance), None):
+ raise OSError(f"PnP adapter instance unavailable (error {ctypes.get_last_error()})")
+ if not instance.value:
+ raise OSError("PnP adapter instance is empty")
+ for prop in (12, 0): # SPDRP_FRIENDLYNAME, then SPDRP_DEVICEDESC
+ text = ctypes.create_unicode_buffer(1024)
+ kind, size = wintypes.DWORD(), wintypes.DWORD()
+ if (setup.SetupDiGetDeviceRegistryPropertyW(
+ devices, ctypes.byref(info), prop, ctypes.byref(kind), text,
+ ctypes.sizeof(text), ctypes.byref(size))
+ and kind.value == 1 and 2 <= size.value <= ctypes.sizeof(text)
+ and text.value.strip()):
+ return instance.value, text.value.strip()
+ # Even when the name is missing, a ROOT display must not inherit a physical GPU's name.
+ return instance.value, ""
+ finally:
+ setup.SetupDiDestroyDeviceInfoList(devices)
+
+
+def _identify_adapter(adapter: Adapter) -> None:
+ try:
+ instance, name = adapter_identity(adapter.luid)
+ except (OSError, AttributeError) as error:
+ adapter.identity_status = f"Windows PnP identity unavailable ({error}); name and vendor are DXGI-reported."
+ return
+ adapter.device_instance_id = instance
+ if adapter.root_display:
+ adapter.name = name or f"ROOT display adapter ({instance})"
+ # Keep physical DXGI names and capacity-based ordering unchanged.
+ if not name:
+ adapter.identity_status = "Windows PnP adapter name unavailable; device instance is known."
+
+
def adapter_pci_address(luid: int) -> tuple[int, int, int] | None:
"""Obtain the WDDM adapter's bus/device/function; the PCI domain is not exposed."""
try:
@@ -116,15 +231,18 @@ def enumerate_adapters(*, strict: bool = False) -> list[Adapter]:
status = _vcall(adapter, 10, ctypes.c_long, ctypes.POINTER(_DESC1))(adapter, ctypes.byref(desc))
if status == 0:
luid = ((desc.AdapterLuid.HighPart & 0xffffffff) << 32) | desc.AdapterLuid.LowPart
- out.append(Adapter(
+ found = Adapter(
luid=luid,
name=desc.Description,
vendor_id=desc.VendorId,
dedicated_vram=desc.DedicatedVideoMemory,
shared_system=desc.SharedSystemMemory,
software=bool(desc.Flags & 2),
- pci_address=adapter_pci_address(luid),
- ))
+ )
+ _identify_adapter(found)
+ if not found.root_display:
+ found.pci_address = adapter_pci_address(luid)
+ out.append(found)
elif strict:
raise OSError("DXGI adapter description unavailable")
finally:
diff --git a/tests/test_dxgi.py b/tests/test_dxgi.py
new file mode 100644
index 0000000..7348694
--- /dev/null
+++ b/tests/test_dxgi.py
@@ -0,0 +1,268 @@
+import contextlib
+import ctypes
+import io
+import sys
+import unittest
+from unittest.mock import Mock, patch
+
+from rich.console import Console
+
+from gputaskman import dxgi
+from gputaskman.app import GpuTaskManager
+from gputaskman.cli import main
+from gputaskman.collector import Collector, ordered_adapters, select_adapter
+from gputaskman.pdh import AdapterGpu, ProcGpu
+from gputaskman.report import to_dict, to_text
+
+
+ROOT = "ROOT\\DISPLAY\\0001"
+PATH = r"\\?\ROOT#DISPLAY#0001#{5b45201d-f2f2-4f3b-85bb-30ff1f953599}"
+STARDESK = "StarDesk Virtual Display Adapter"
+
+
+class IdentityApiTests(unittest.TestCase):
+ def setUp(self):
+ self.user, self.setup = Mock(), Mock()
+ self.user.DisplayConfigGetDeviceInfo.side_effect = self.get_name
+ self.setup.SetupDiCreateDeviceInfoList.return_value = 123
+ self.setup.SetupDiOpenDeviceInterfaceW.return_value = True
+ self.setup.SetupDiGetDeviceInterfaceDetailW.return_value = True
+ self.setup.SetupDiGetDeviceInstanceIdW.side_effect = self.get_instance
+ self.setup.SetupDiGetDeviceRegistryPropertyW.side_effect = self.get_property
+ self.dll = patch.object(dxgi.ctypes, "WinDLL", side_effect=self.load, create=True)
+ self.dll.start()
+ self.addCleanup(self.dll.stop)
+ self.last_error = patch.object(dxgi.ctypes, "get_last_error", return_value=5, create=True)
+ self.last_error.start()
+ self.addCleanup(self.last_error.stop)
+
+ def load(self, name, **kwargs):
+ return {"user32": self.user, "setupapi": self.setup}[name]
+
+ def get_name(self, header):
+ request = ctypes.cast(header, ctypes.POINTER(dxgi._AdapterName)).contents
+ self.assertEqual(request.header.kind, 4)
+ self.assertEqual(request.header.size, ctypes.sizeof(dxgi._AdapterName))
+ self.assertEqual(request.header.id, 0)
+ self.requested_luid = ((request.header.luid.HighPart & 0xffffffff) << 32
+ | request.header.luid.LowPart)
+ request.path = PATH
+ return 0
+
+ def get_instance(self, handle, info, buffer, length, required):
+ buffer.value = ROOT
+ return True
+
+ def get_property(self, handle, info, prop, kind, buffer, length, required):
+ self.assertEqual(prop, 12)
+ buffer.value = STARDESK
+ kind._obj.value = 1
+ required._obj.value = (len(STARDESK) + 1) * ctypes.sizeof(ctypes.c_wchar)
+ return True
+
+ def test_exact_luid_lookup_needs_no_active_display_path(self):
+ self.assertEqual(dxgi.adapter_identity(0x20452), (ROOT, STARDESK))
+ self.assertEqual(self.requested_luid, 0x20452)
+ self.setup.SetupDiOpenDeviceInterfaceW.assert_called_once()
+ self.assertEqual(self.setup.SetupDiOpenDeviceInterfaceW.call_args.args[1], PATH)
+ self.setup.SetupDiDestroyDeviceInfoList.assert_called_once_with(123)
+ self.assertEqual(self.user.method_calls[0][0], "DisplayConfigGetDeviceInfo")
+
+ def test_signed_high_luid_preserves_all_bits(self):
+ dxgi.adapter_identity(0xfedcba9800020452)
+ self.assertEqual(self.requested_luid, 0xfedcba9800020452)
+
+ def test_friendly_name_falls_back_to_device_description(self):
+ original = self.get_property
+
+ def property_value(*args):
+ if args[2] == 12:
+ return False
+ return original(*args[:2], 12, *args[3:])
+
+ self.setup.SetupDiGetDeviceRegistryPropertyW.side_effect = property_value
+ self.assertEqual(dxgi.adapter_identity(0x20452), (ROOT, STARDESK))
+ self.assertEqual([c.args[2] for c in self.setup.SetupDiGetDeviceRegistryPropertyW.call_args_list], [12, 0])
+
+ def test_missing_or_invalid_names_keep_verified_instance(self):
+ for kind, size, text in ((7, 100, STARDESK), (1, 100000, STARDESK), (1, 0, STARDESK), (1, 4, " ")):
+ with self.subTest(kind=kind, size=size, text=text):
+ def invalid(*args):
+ args[3]._obj.value = kind
+ args[4].value = text
+ args[6]._obj.value = size
+ return True
+
+ self.setup.SetupDiGetDeviceRegistryPropertyW.side_effect = invalid
+ self.assertEqual(dxgi.adapter_identity(0x20452), (ROOT, ""))
+
+ def test_api_failures_are_bounded_and_close_device_list(self):
+ for function in ("SetupDiOpenDeviceInterfaceW", "SetupDiGetDeviceInterfaceDetailW",
+ "SetupDiGetDeviceInstanceIdW"):
+ with self.subTest(function=function):
+ api = getattr(self.setup, function)
+ previous_effect, previous_value = api.side_effect, api.return_value
+ api.side_effect, api.return_value = None, False
+ self.setup.SetupDiDestroyDeviceInfoList.reset_mock()
+ with self.assertRaisesRegex(OSError, "error 5"):
+ dxgi.adapter_identity(0x20452)
+ self.setup.SetupDiDestroyDeviceInfoList.assert_called_once_with(123)
+ api.side_effect, api.return_value = previous_effect, previous_value
+
+ def test_displayconfig_failure_does_not_open_pnp_list(self):
+ self.user.DisplayConfigGetDeviceInfo.side_effect = None
+ self.user.DisplayConfigGetDeviceInfo.return_value = 87
+ with self.assertRaisesRegex(OSError, "error 87"):
+ dxgi.adapter_identity(0x20452)
+ self.setup.SetupDiCreateDeviceInfoList.assert_not_called()
+
+ def test_invalid_device_list_is_not_used_or_closed(self):
+ self.setup.SetupDiCreateDeviceInfoList.return_value = ctypes.c_void_p(-1).value
+ with self.assertRaisesRegex(OSError, "device list unavailable"):
+ dxgi.adapter_identity(0x20452)
+ self.setup.SetupDiOpenDeviceInterfaceW.assert_not_called()
+ self.setup.SetupDiDestroyDeviceInfoList.assert_not_called()
+
+ def test_empty_instance_is_not_accepted(self):
+ self.setup.SetupDiGetDeviceInstanceIdW.side_effect = None
+ with self.assertRaisesRegex(OSError, "instance is empty"):
+ dxgi.adapter_identity(0x20452)
+
+ @unittest.skipUnless(sys.platform == "win32", "Windows ABI")
+ def test_windows_structure_sizes(self):
+ self.assertEqual(ctypes.sizeof(dxgi._DeviceInfoHeader), 20)
+ self.assertEqual(ctypes.sizeof(dxgi._AdapterName), 276)
+ size = 32 if ctypes.sizeof(ctypes.c_void_p) == 8 else 28
+ self.assertEqual(ctypes.sizeof(dxgi._DeviceInterface), size)
+ self.assertEqual(ctypes.sizeof(dxgi._DeviceInfo), size)
+
+
+class AdapterIdentityTests(unittest.TestCase):
+ def adapter(self, luid=0x20452, vendor=0x8086):
+ return dxgi.Adapter(luid, "Intel(R) UHD Graphics 630", vendor, 128 << 20, 8 << 30, False)
+
+ def identify(self, adapter, instance=ROOT, name=STARDESK):
+ with patch.object(dxgi, "adapter_identity", return_value=(instance, name)):
+ dxgi._identify_adapter(adapter)
+ return adapter
+
+ def test_root_name_comes_from_exact_pnp_identity_not_dxgi_vendor(self):
+ for vendor in (0x8086, 0x10de, 0x1002, 0):
+ with self.subTest(vendor=vendor):
+ a = self.identify(self.adapter(vendor=vendor))
+ self.assertEqual(a.name, STARDESK)
+ self.assertEqual(a.vendor_id, vendor)
+ self.assertEqual(a.vendor, "ROOT display adapter")
+ self.assertEqual(a.device_instance_id, ROOT)
+
+ def test_physical_name_and_vendor_are_unchanged(self):
+ a = self.identify(self.adapter(0x1295f), "PCI\\VEN_8086&DEV_3E9B\\123", "Generic PnP description")
+ self.assertEqual(a.name, "Intel(R) UHD Graphics 630")
+ self.assertEqual(a.vendor, "Intel")
+ self.assertFalse(a.root_display)
+
+ def test_root_instance_not_duplicate_name_proves_root_display(self):
+ for instance, root in (("root\\display\\0001", True), ("ROOT\\DISPLAYOTHER\\0001", False),
+ ("PCI\\VEN_8086\\0001", False), ("", False)):
+ with self.subTest(instance=instance):
+ a = self.identify(self.adapter(), instance)
+ self.assertEqual(a.root_display, root)
+ self.assertEqual(a.name, STARDESK if root else "Intel(R) UHD Graphics 630")
+
+ def test_missing_pnp_name_has_explicit_root_label_and_reason(self):
+ a = self.identify(self.adapter(), name="")
+ self.assertEqual(a.name, f"ROOT display adapter ({ROOT})")
+ self.assertIn("name unavailable", a.identity_status)
+ self.assertEqual(a.vendor, "ROOT display adapter")
+
+ def test_probe_failure_preserves_dxgi_and_explains_uncertainty(self):
+ for error in (OSError("access denied"), AttributeError("API missing")):
+ with self.subTest(error=error), patch.object(dxgi, "adapter_identity", side_effect=error):
+ a = self.adapter()
+ dxgi._identify_adapter(a)
+ self.assertEqual(a.name, "Intel(R) UHD Graphics 630")
+ self.assertEqual(a.device_instance_id, "")
+ self.assertIn(str(error), a.identity_status)
+ self.assertIn("DXGI-reported", a.identity_status)
+
+ def test_list_explains_failed_identity_lookup(self):
+ a = self.adapter()
+ a.identity_status = "Windows PnP identity unavailable; name and vendor are DXGI-reported."
+ output = io.StringIO()
+ with patch("sys.argv", ["gputaskman", "--list-gpus"]), patch("gputaskman.cli._check_platform"), \
+ patch("gputaskman.collector.enumerate_adapters", return_value=[a]), \
+ contextlib.redirect_stdout(output):
+ main()
+ self.assertIn(a.name, output.getvalue())
+ self.assertIn(a.identity_status, output.getvalue())
+
+ def test_enumeration_keeps_slots_and_does_not_query_root_pci_location(self):
+ luids = [0x142f1, 0x1295f, 0x20452]
+
+ def enum(factory, index, out):
+ if index == len(luids):
+ return 0x887a0002
+ out._obj.value = index + 10
+ return 0
+
+ def description(adapter, desc):
+ index = adapter.value - 10
+ desc._obj.Description = "NVIDIA Quadro P620" if index == 0 else "Intel(R) UHD Graphics 630"
+ desc._obj.AdapterLuid.LowPart = luids[index]
+ desc._obj.VendorId = 0x10de if index == 0 else 0x8086
+ desc._obj.DedicatedVideoMemory = 128 << 20
+ return 0
+
+ def vcall(obj, index, *types):
+ return {12: enum, 10: description, 2: lambda obj: None}[index]
+
+ def identity(luid):
+ return (ROOT, STARDESK) if luid == 0x20452 else ("PCI\\physical", "PnP name")
+
+ api = Mock()
+ api.CreateDXGIFactory1.return_value = 0
+ with patch.object(dxgi.ctypes, "WinDLL", return_value=api, create=True), \
+ patch.object(dxgi, "_vcall", side_effect=vcall), \
+ patch.object(dxgi, "adapter_identity", side_effect=identity), \
+ patch.object(dxgi, "adapter_pci_address", return_value=(1, 0, 0)) as pci:
+ adapters = ordered_adapters(dxgi.enumerate_adapters(strict=True))
+ self.assertEqual([a.luid for a in adapters], luids)
+ self.assertEqual([a.name for a in adapters], ["NVIDIA Quadro P620", "Intel(R) UHD Graphics 630", STARDESK])
+ self.assertIsNone(select_adapter(adapters, 2).pci_address)
+ self.assertEqual([call.args[0] for call in pci.call_args_list], luids[:2])
+ output = io.StringIO()
+ with patch("sys.argv", ["gputaskman", "--list-gpus"]), patch("gputaskman.cli._check_platform"), \
+ patch("gputaskman.collector.enumerate_adapters", return_value=adapters), \
+ contextlib.redirect_stdout(output):
+ main()
+ self.assertIn(f"2: {STARDESK} (ROOT display adapter, LUID 0x0000000000020452)", output.getvalue())
+
+ def test_unmatched_report_stays_unknown_in_json_text_and_tui(self):
+ c = Collector.__new__(Collector)
+ c.adapter = self.identify(self.adapter())
+ c.adapters = [c.adapter]
+ c.gpu_index, c.scan_budget, c.host, c.host_status = 0, None, None, ""
+ c.nvml = Mock(ok=False)
+ c.counters = Mock(outside={})
+ c.counters.sample.return_value = (
+ {0x1295f: {4: ProcGpu(dedicated=1024, engines={"compute": 10})}},
+ {0x1295f: AdapterGpu(dedicated=1024, shared=0)})
+ c.inspector, c.prober = Mock(), Mock()
+ for reason in ("", "Windows PnP name unavailable"):
+ with self.subTest(reason=reason), patch("gputaskman.collector.BACKEND", "wddm"):
+ c.adapter.identity_status = reason
+ s = c.sample()
+ data = to_dict(s)
+ self.assertEqual(data["gpu"], STARDESK)
+ self.assertEqual(data["adapter"]["device_instance_id"], ROOT)
+ for key in ("vram_used", "shared_used", "attributed"):
+ self.assertIsNone(data[key])
+ self.assertFalse(data["counter_adapter_matched"])
+ self.assertEqual(data["processes"], [])
+ self.assertIn("could not be matched", data["counter_status"])
+ self.assertIn(reason, data["counter_status"])
+ self.assertIn(STARDESK, to_text(s))
+ output = io.StringIO()
+ Console(file=output, width=200).print(GpuTaskManager().render_device(s))
+ self.assertIn(STARDESK, output.getvalue())
+ self.assertIn(reason, output.getvalue())