Skip to content

Add GPU metrics to GraphicsCard - #3088

Merged
dbwiddis merged 9 commits into
oshi:masterfrom
dbwiddis:gpu-phase-1
Mar 11, 2026
Merged

dbwiddis merged 9 commits into
oshi:masterfrom
dbwiddis:gpu-phase-1

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Mar 11, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds GPU metrics to the GraphicsCard API (Phase 1 described in #2112 (comment)):

  • getGpuTicks() — activity tick snapshot (100ns units) for delta-based utilization (when available)
  • getGpuUtilization() — GPU core load as a 0.0–1.0 fraction (when available)
  • getVramUsed() — dedicated VRAM in use (bytes)
  • getSharedMemoryUsed() — shared/UMA memory in use (bytes)

Platform Coverage

Platform Utilization VRAM Used Shared Used
Windows PDH + LHM fallback PDH + LHM fallback PDH
Linux (AMD) sysfs gpu_busy_percent sysfs mem_info_vram_used N/A
Linux (Intel) sysfs rps freq ratio N/A N/A
macOS IOKit IOAccelerator IOKit IOAccelerator N/A

New Files

  • GpuTicks — interface for immutable GPU activity tick snapshots
  • DefaultGpuTicks — immutable GpuTicks implementation
  • GpuInformation — PDH driver for GPU Engine and GPU Adapter Memory counters (Windows)
  • LhmSensor — WMI driver for ROOT\LibreHardwareMonitor sensor/hardware queries (Windows)

Changes

  • GraphicsCard: four new API methods
  • AbstractGraphicsCard: safe default implementations (-1 / zero-tick snapshot)
  • WindowsGraphicsCard: PDH + LHM-backed implementations; @ThreadSafe
  • LinuxGraphicsCard: sysfs-backed implementations; @ThreadSafe
  • MacGraphicsCard: IOKit IOAccelerator-backed implementations
  • WmiUtil: added LHM_NAMESPACE constant
  • WmiQueryHandler: extended COM exception suppression to cover LHM_NAMESPACE

Compatibility

Unsupported platforms and methods return -1 (memory values) or a zero-tick snapshot (ticks) via AbstractGraphicsCard defaults. No changes required to FreeBSD, AIX, Solaris, or OpenBSD implementations.

Summary by CodeRabbit

  • New Features

    • GPU metrics: timestamped active-time snapshots, real-time utilization %, VRAM used, and shared-memory used across Windows, macOS, and Linux.
    • Improved multi‑GPU/per‑adapter detection with better matching, LUID awareness, and fallbacks.
    • Optional LibreHardwareMonitor (LHM) integration for richer GPU sensor data.
  • Documentation

    • Changelog updated to list GPU metrics in 6.11.0 New Features.

@coderabbitai

coderabbitai Bot commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds GPU runtime metrics and APIs: new GpuTicks type and DefaultGpuTicks; extends GraphicsCard with utilization and memory methods; implements platform collectors and helpers (Windows: DXGI/LUID + PDH/WMI/LHM; Linux: DRM/sysfs; macOS: IOKit); updates WMI handling and related types.

Changes

Cohort / File(s) Summary
Changelog & Core Types
CHANGELOG.md, oshi-core/src/main/java/oshi/hardware/GpuTicks.java, oshi-core/src/main/java/oshi/hardware/common/DefaultGpuTicks.java
Adds changelog entry; introduces GpuTicks interface and immutable DefaultGpuTicks implementation.
GraphicsCard API & Base
oshi-core/src/main/java/oshi/hardware/GraphicsCard.java, oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java
Adds getGpuTicks(), getGpuUtilization(), getVramUsed(), getSharedMemoryUsed() signatures and default/placeholder implementations; makes VRAM field final and updates toString.
Linux platform
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java
Adds drmDevicePath/driverName fields and constructor change; adds DRM/sysfs discovery and implementations for ticks, utilization, and memory; annotation → @ThreadSafe.
macOS platform
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
Adds IOKit PerformanceStatistics querying and helpers; implements ticks/utilization/VRAM methods; annotation → @ThreadSafe and logging.
Windows platform & DXGI changes
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java, oshi-core/src/main/java/oshi/driver/windows/DxgiAdapterInfo.java, oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java
Adds LUID low/high to DXGI adapter info and propagation; extends constructors/signatures; builds LUID/LHM mappings; implements PDH/WMI/LHM-based ticks, utilization, and memory; annotation → @ThreadSafe.
Windows PDH/WMI & LHM helpers
oshi-core/src/main/java/oshi/driver/windows/perfmon/GpuInformation.java, oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java, oshi-core/src/main/java/oshi/util/platform/windows/WmiUtil.java, oshi-core/src/main/java/oshi/util/platform/windows/WmiQueryHandler.java
Adds GpuInformation PDH wildcard queries, LhmSensor WMI helper, LHM_NAMESPACE constant, and adjusts WMI error handling to account for LibreHardwareMonitor/OpenHardwareMonitor namespaces.
Windows WMI/DXGI tests
oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java
Updates test constructor calls to supply new LUID parameters for DxgiAdapterInfo.

Sequence Diagram(s)

sequenceDiagram
  participant Client as "Client\n(app)"
  participant API as "GraphicsCard\nAPI"
  participant Impl as "Platform\nGraphicsCard"
  participant Source as "Metric Source\n(DRM / IOKit / PDH / WMI / LHM / DXGI)"
  Client->>API: request GPU metrics
  API->>Impl: call getGpuTicks/getGpuUtilization/getVramUsed/getSharedMemoryUsed
  Impl->>Source: query platform counters/sensors and DXGI/LUID context
  Source-->>Impl: return timestamps and values
  Impl-->>API: assemble GpuTicks and metrics
  API-->>Client: return metrics
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I hopped through counters, drivers, and code,
I chased LUIDs down every road.
PDH, WMI, sysfs in hand—
ticks and VRAM across the land.
Metrics gathered—hop!—now proudly show.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 55.07% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add GPU metrics to GraphicsCard' directly and clearly summarizes the main change: introducing four new GPU metric methods (getGpuTicks, getGpuUtilization, getVramUsed, getSharedMemoryUsed) to the GraphicsCard interface and its implementations across multiple platforms.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (6)
oshi-core/src/main/java/oshi/hardware/common/DefaultGpuTicks.java (1)

14-38: Consider adding toString() for debugging convenience.

This immutable snapshot class could benefit from a toString() implementation for logging and debugging purposes. The equals() and hashCode() methods are less critical since snapshots are typically used for delta calculations rather than identity comparisons.

🔧 Optional: Add toString()
     `@Override`
     public long getActiveTicks() {
         return activeTicks;
     }
+
+    `@Override`
+    public String toString() {
+        return "GpuTicks[timestamp=" + timestamp + ", activeTicks=" + activeTicks + "]";
+    }
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/common/DefaultGpuTicks.java` around
lines 14 - 38, Add a concise toString() to DefaultGpuTicks to aid
logging/debugging: implement public String toString() in the DefaultGpuTicks
class that returns a readable representation including the class name and the
timestamp and activeTicks fields (e.g., "DefaultGpuTicks{timestamp=...,
activeTicks=...}"), referencing the existing fields timestamp and activeTicks
and the class DefaultGpuTicks so callers printing instances will get meaningful
output.
oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java (2)

45-52: Potential NPE if WmiQueryHandler.createInstance() returns null.

createInstance() can return null when custom class instantiation fails (see lines 77-82 of WmiQueryHandler.java). Using Objects.requireNonNull() will throw an NPE in that case, which may not provide a clear error message.

Consider either:

  1. Adding a descriptive message to requireNonNull() for better diagnostics
  2. Handling the null case gracefully (return empty result)
🛡️ Option 1: Add descriptive message
-        return Objects.requireNonNull(WmiQueryHandler.createInstance()).queryWMI(query, true);
+        return Objects.requireNonNull(WmiQueryHandler.createInstance(),
+                "WmiQueryHandler.createInstance() returned null").queryWMI(query, true);
🛡️ Option 2: Return empty result on null handler
     public static WmiResult<LhmSensorProperty> querySensors(String parent, String sensorType) {
         StringBuilder sb = new StringBuilder(SENSOR);
         sb.append(" WHERE Parent=\"").append(parent);
         sb.append("\" AND SensorType=\"").append(sensorType).append('"');
         WmiQuery<LhmSensorProperty> query = new WmiQuery<>(WmiUtil.LHM_NAMESPACE, sb.toString(),
                 LhmSensorProperty.class);
-        return Objects.requireNonNull(WmiQueryHandler.createInstance()).queryWMI(query, true);
+        WmiQueryHandler handler = WmiQueryHandler.createInstance();
+        if (handler == null) {
+            return new WmiResult<>(LhmSensorProperty.class);
+        }
+        return handler.queryWMI(query, true);
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java` around lines
45 - 52, Replace the blind Objects.requireNonNull(...) call in querySensors with
an explicit local variable for the handler and a descriptive requireNonNull
message: call WmiQueryHandler.createInstance(), assign it to a variable (e.g.,
handler), then use Objects.requireNonNull(handler,
"WmiQueryHandler.createInstance() returned null while creating handler for
LhmSensor queries") before invoking handler.queryWMI(...); this ensures
querySensors (in LhmSensor.querySensors) fails with a clear diagnostic instead
of a generic NPE from requireNonNull.

59-64: Same Objects.requireNonNull concern applies here.

Consider applying the same fix pattern as suggested for querySensors().

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java` around lines
59 - 64, Replace the inline Objects.requireNonNull(...) call in queryGpuHardware
with the same null-check pattern used in querySensors(): assign
WmiQueryHandler.createInstance() to a local variable (e.g., WmiQueryHandler
handler), if handler is null throw an IllegalStateException with a clear
message, then call handler.queryWMI(query, true); update the method
queryGpuHardware to use this local variable instead of
Objects.requireNonNull(WmiQueryHandler.createInstance()).
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (2)

342-374: buildLuidPrefix doesn't use vendorId or deviceId parameters.

The method signature accepts vendorId, deviceId, and adapterName but only uses the instance count for logic. The parameters are documented as "PCI vendor ID" and "PCI device ID" but never referenced in the method body.

Either:

  1. Remove unused parameters if they can't be used for matching
  2. Implement actual matching logic using these IDs if PDH instances expose them

The single-adapter shortcut at line 365-367 could return wrong LUID if the system has non-GPU adapters (e.g., remote display adapters) that also expose GPU Adapter Memory counters.

♻️ Suggested cleanup if parameters cannot be used
-    private static String buildLuidPrefix(int vendorId, int deviceId, String adapterName) {
+    private static String buildLuidPrefix() {
         Pair<List<String>, Map<GpuAdapterMemoryProperty, List<Long>>> adapterData = GpuInformation
                 .queryGpuAdapterMemoryCounters();

Then update call sites to buildLuidPrefix().

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 342 - 374, The buildLuidPrefix method currently accepts vendorId,
deviceId, and adapterName but never uses them; remove these unused parameters
from the buildLuidPrefix signature and Javadoc, update all callers to call
buildLuidPrefix() with no arguments, and adjust tests if any; keep the existing
logic that queries GpuInformation.queryGpuAdapterMemoryCounters(), preserve the
single-adapter shortcut and LOG.debug message, and ensure imports and any
references to the old parameters are cleaned up.

325-340: Consider narrowing the exception catch.

Catching Exception is broad and could mask programming errors (e.g., NullPointerException). Since WMI/COM failures typically throw Win32Exception or similar, consider catching a more specific type:

-        } catch (Exception e) {
+        } catch (RuntimeException e) {
             LOG.debug("LHM GPU hardware query failed (LHM may not be running): {}", e.getMessage());
         }

This still catches WMI/COM failures but allows checked exceptions to propagate if any are added in the future.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 325 - 340, The catch in buildLhmParentMap() is too broad—replace
catch(Exception e) with a narrower catch for the expected WMI/COM failure types
(e.g., com.sun.jna.platform.win32.Win32Exception and/or the specific WMI
exception type used in your project) around the call to
LhmSensor.queryGpuHardware() and related WmiUtil.getString(...) calls; keep the
same LOG.debug(...) behavior but catch only those specific exceptions so
programming errors (NullPointerException, etc.) will still propagate.
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java (1)

236-243: Consider stricter model matching to avoid false positives.

The bidirectional contains check (normModel.contains(normName) || normName.contains(normModel)) could match unrelated GPUs if one name is a substring of another (e.g., "AMD Radeon Pro 5500M" matching "AMD Radeon Pro 5500" on a system with both).

Consider using equality as primary match and only falling back to contains if no exact match is found across all services.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java`
around lines 236 - 243, The matchesName method currently returns matches if
names contain each other, causing false positives; modify the matchesName(String
model) method to first perform a strict equality check between normModel and
normName (using equals), and only if that fails perform a single-direction
substring fallback (e.g., normModel.contains(normName)) rather than the
bidirectional contains; keep the original normalization (toLowerCase, replace,
trim) and ensure null/empty guard remains.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@oshi-core/src/main/java/oshi/driver/windows/perfmon/GpuInformation.java`:
- Around line 75-93: The guard using PerfmonDisabled.PERF_OS_DISABLED in
queryGpuEngineCounters and queryGpuAdapterMemoryCounters incorrectly gates
GPUPerformanceCounters; either remove these PERF_OS_DISABLED checks so the PDH
calls in
PerfCounterWildcardQuery.queryInstancesAndValuesFromPDH(GpuEngineProperty.class,
GPU_ENGINE) and
PerfCounterWildcardQuery.queryInstancesAndValuesFromPDH(GpuAdapterMemoryProperty.class,
GPU_ADAPTER_MEMORY) run and fail gracefully, or replace the guard with a
GPU-specific flag (e.g., PerfmonDisabled.PERF_GPU_DISABLED tied to
GPUPerformanceCounters) and check that instead so GPU queries are only skipped
when GPUPerformanceCounters are disabled.

In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`:
- Around line 193-211: findDrmInfo currently ignores its gpuName parameter and
returns the first card with a driver symlink, causing incorrect selection on
multi‑GPU systems; update findDrmInfo to attempt best‑effort name matching by
reading each card's uevent file (under device + "/uevent") and compare the
PCI_SLOT_NAME or other identifiers against gpuName (or correlate with lspci
output) before falling back to the first driverful card; use the existing
readDriverName helper and DRM_PATH constant to locate files and only return the
first card when no match is found, or alternatively document the limitation
clearly if reliable matching is not possible.
- Around line 240-243: The AMD branch in LinuxGraphicsCard currently returns an
integer percent from FileUtil.getIntFromFile(drmDevicePath +
"/gpu_busy_percent") but doesn't convert it to the API's 0.0–1.0 range; in the
AMD branch (where "amdgpu".equals(driver)) change the return to convert pct to a
double fraction (e.g., return pct >= 0 ? pct / 100.0 : -1d) using the existing
drmDevicePath and FileUtil.getIntFromFile call so negative error values still
map to -1d.
- Around line 251-259: The intelFreqUtilization() method currently returns a
0–100 value; change it to return a 0.0–1.0 fraction by computing (actual /
(double) max) and capping with Math.min(1.0, ...), returning -1.0 for unknowns
as before, and add a brief inline comment in intelFreqUtilization() (and/or
getGpuUtilization() caller) clarifying this is a rough frequency-ratio proxy for
GPU utilization, not measured core utilization.

In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java`:
- Around line 118-146: getGpuUtilization currently returns 0–100 instead of the
API's 0.0–1.0 fraction; update the two return paths in getGpuUtilization to
normalize to 0.0–1.0: in the "GPU Core Utilization" branch (using
GPU_CORE_UTIL_KEY and GPU_UTIL_DIVISOR) remove the "* 100.0" so you return (raw
/ GPU_UTIL_DIVISOR) as a double, and in the "Device Utilization %" branch (using
DEVICE_UTIL_KEY and CFNumberRef) return num.longValue() / 100.0 as a double;
keep perfStats.release() in the finally block.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 419-435: getGpuUtilization currently returns LHM "Load" sensor
values (0–100) directly; update it to convert percentage to the API's 0.0–1.0
range by dividing the returned value from WmiUtil.getFloat(sensors,
LhmSensorProperty.VALUE, i) by 100.0 before returning; additionally, either add
a short javadoc note on WindowsGraphicsCard.getGpuUtilization stating that
accurate GPU utilization requires LibreHardwareMonitor (LhmSensor.querySensors)
to be running or implement a PDH-based fallback path (e.g., using PDH counters
and tick-delta calculation) when lhmParent is empty or the LHM query fails (the
quick fix is to perform the divide and add the documentation statement).

---

Nitpick comments:
In `@oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java`:
- Around line 45-52: Replace the blind Objects.requireNonNull(...) call in
querySensors with an explicit local variable for the handler and a descriptive
requireNonNull message: call WmiQueryHandler.createInstance(), assign it to a
variable (e.g., handler), then use Objects.requireNonNull(handler,
"WmiQueryHandler.createInstance() returned null while creating handler for
LhmSensor queries") before invoking handler.queryWMI(...); this ensures
querySensors (in LhmSensor.querySensors) fails with a clear diagnostic instead
of a generic NPE from requireNonNull.
- Around line 59-64: Replace the inline Objects.requireNonNull(...) call in
queryGpuHardware with the same null-check pattern used in querySensors(): assign
WmiQueryHandler.createInstance() to a local variable (e.g., WmiQueryHandler
handler), if handler is null throw an IllegalStateException with a clear
message, then call handler.queryWMI(query, true); update the method
queryGpuHardware to use this local variable instead of
Objects.requireNonNull(WmiQueryHandler.createInstance()).

In `@oshi-core/src/main/java/oshi/hardware/common/DefaultGpuTicks.java`:
- Around line 14-38: Add a concise toString() to DefaultGpuTicks to aid
logging/debugging: implement public String toString() in the DefaultGpuTicks
class that returns a readable representation including the class name and the
timestamp and activeTicks fields (e.g., "DefaultGpuTicks{timestamp=...,
activeTicks=...}"), referencing the existing fields timestamp and activeTicks
and the class DefaultGpuTicks so callers printing instances will get meaningful
output.

In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java`:
- Around line 236-243: The matchesName method currently returns matches if names
contain each other, causing false positives; modify the matchesName(String
model) method to first perform a strict equality check between normModel and
normName (using equals), and only if that fails perform a single-direction
substring fallback (e.g., normModel.contains(normName)) rather than the
bidirectional contains; keep the original normalization (toLowerCase, replace,
trim) and ensure null/empty guard remains.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 342-374: The buildLuidPrefix method currently accepts vendorId,
deviceId, and adapterName but never uses them; remove these unused parameters
from the buildLuidPrefix signature and Javadoc, update all callers to call
buildLuidPrefix() with no arguments, and adjust tests if any; keep the existing
logic that queries GpuInformation.queryGpuAdapterMemoryCounters(), preserve the
single-adapter shortcut and LOG.debug message, and ensure imports and any
references to the old parameters are cleaned up.
- Around line 325-340: The catch in buildLhmParentMap() is too broad—replace
catch(Exception e) with a narrower catch for the expected WMI/COM failure types
(e.g., com.sun.jna.platform.win32.Win32Exception and/or the specific WMI
exception type used in your project) around the call to
LhmSensor.queryGpuHardware() and related WmiUtil.getString(...) calls; keep the
same LOG.debug(...) behavior but catch only those specific exceptions so
programming errors (NullPointerException, etc.) will still propagate.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 770536c3-48b7-45d9-bd59-a5cd804efa2b

📥 Commits

Reviewing files that changed from the base of the PR and between a3626c0 and 7a649a7.

📒 Files selected for processing (12)
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/driver/windows/perfmon/GpuInformation.java
  • oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java
  • oshi-core/src/main/java/oshi/hardware/GpuTicks.java
  • oshi-core/src/main/java/oshi/hardware/GraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/common/DefaultGpuTicks.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/main/java/oshi/util/platform/windows/WmiQueryHandler.java
  • oshi-core/src/main/java/oshi/util/platform/windows/WmiUtil.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Analyze (java)
🔇 Additional comments (11)
CHANGELOG.md (1)

5-5: LGTM!

The changelog entry follows the established format and is correctly placed under the "New Features" section for 6.11.0.

oshi-core/src/main/java/oshi/util/platform/windows/WmiUtil.java (1)

32-37: LGTM!

The new LHM_NAMESPACE constant follows the same pattern as OHM_NAMESPACE, with complete and consistent Javadoc documentation.

oshi-core/src/main/java/oshi/hardware/GpuTicks.java (1)

1-33: LGTM!

Well-designed interface with clear semantics:

  • The immutable contract is appropriate for snapshot data
  • Sentinel value (0 for activeTicks) is clearly documented
  • The utilization formula in Javadoc aligns with the percentage range (0.0-100.0) specified in GraphicsCard.getGpuUtilization()
oshi-core/src/main/java/oshi/util/platform/windows/WmiQueryHandler.java (1)

130-149: LGTM!

The logic correctly extends the existing OHM exception suppression to also cover LHM namespace. This is appropriate since both are optional external monitoring tools that may not be running.

oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java (1)

84-102: LGTM!

Default implementations correctly return sentinel values:

  • getGpuTicks() returns a snapshot with activeTicks=0 (documented sentinel for unavailable)
  • Other methods return -1 consistent with the interface contract

Platform-specific subclasses can override these to provide actual metrics where available.

oshi-core/src/main/java/oshi/hardware/GraphicsCard.java (1)

52-85: LGTM!

The new API methods are well-documented with clear semantics:

  • Sentinel value conventions are clearly stated (-1 for unavailable scalar metrics, 0 for activeTicks)
  • getGpuTicks() is guaranteed non-null per documentation
  • Documentation explains the intended usage pattern for utilization calculation
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java (1)

1-64: LGTM!

The class structure, imports, constants, and constructor are well-organized. The GPU_UTIL_DIVISOR constant correctly represents the unsigned 32-bit maximum for scaling the raw utilization value.

oshi-core/src/main/java/oshi/driver/windows/perfmon/GpuInformation.java (1)

1-68: LGTM!

The class structure follows established patterns for OSHI perfmon drivers. The enums correctly implement PdhCounterWildcardProperty with the wildcard instance filter as the first element. The @ThreadSafe annotation is appropriate for this stateless utility class.

oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (1)

66-72: LGTM!

The fallback strategy (lspci primary, lshw backup) is sensible for broad Linux compatibility. The DRM info integration into both parsing paths is consistent.

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (2)

380-417: LGTM!

The GPU ticks aggregation logic is well-designed. Grouping by engine type and taking the maximum across types correctly captures overall adapter utilization from parallel GPU pipelines. The LUID filtering is case-insensitive as appropriate for PDH instance names.


437-473: LGTM!

The two-tier fallback for VRAM (PDH → LHM) provides good coverage. The MB-to-bytes conversion constant is correct, and the exception handling ensures graceful degradation when LHM is unavailable.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (1)

84-92: ⚠️ Potential issue | 🟠 Major

Use the PCI slot address for the follow-up lspci -s query.

lookupDevice is populated from the Device: field, which contains the device name, not the PCI address. queryLspciMemorySize() passes it to lspci -s, which expects a PCI slot address in the format [domain:]bus:device.function. In lspci -vnnm output, the selectable address lives under the Slot: field. Additionally, the current logic only captures Device: when !found is true, so once a VGA/3D controller is detected, lookupDevice remains stale for subsequent cards. This results in incorrect VRAM discovery on the primary lspci path.

🔧 Proposed fix
         String lookupDevice = null;
         for (String line : lspci) {
             String[] split = line.trim().split(":", 2);
             String prefix = split[0];
+            if (prefix.equals("Slot") && split.length > 1) {
+                lookupDevice = split[1].trim();
+            }
             // Skip until line contains "VGA" or "3D controller"
             if (prefix.equals("Class") && (line.contains("VGA") || line.contains("3D controller"))) {
                 found = true;
-            } else if (prefix.equals("Device") && !found && split.length > 1) {
-                lookupDevice = split[1].trim();
             }

Also applies to: 97-100, 125-128

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`
around lines 84 - 92, The parsing logic in LinuxGraphicsCard that sets
lookupDevice (used by queryLspciMemorySize()) is incorrectly pulling the Device:
name and only when !found, causing stale PCI addresses; change the parser to
extract the PCI slot address from the "Slot" field (split[0].equals("Slot") &&
split.length>1) and assign lookupDevice = split[1].trim() when you identify the
VGA/3D block (use found to mark start of a card but allow capturing Slot after
found is true), and ensure you reset/handle found per card so each GPU's Slot is
captured for queryLspciMemorySize(); update similar occurrences around the other
blocks (lines referenced) to consistently use Slot for lspci -s queries.
🧹 Nitpick comments (4)
oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java (2)

71-76: Consider moving LhmHardwareProperty enum before the methods that use it.

The LhmHardwareProperty enum is defined after queryGpuHardware() which returns WmiResult<LhmHardwareProperty>. Moving it alongside LhmSensorProperty (near line 31) would improve readability by keeping type declarations together before the methods that reference them.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java` around lines
71 - 76, Move the enum LhmHardwareProperty so it appears before any methods that
reference it (e.g., before queryGpuHardware()) and colocate it near the existing
LhmSensorProperty declaration to keep type declarations together; update the
class ordering only (no behavioral changes) so LhmHardwareProperty is declared
above methods like queryGpuHardware() that return
WmiResult<LhmHardwareProperty>.

45-54: WQL injection risk: sanitize query parameters.

The parent and sensorType parameters are directly concatenated into the WQL query string without escaping. If these values contain quotes or special characters (e.g., a malformed LHM identifier), the query could break or be manipulated.

Consider escaping double quotes in the parameters:

🛡️ Proposed fix to escape WQL parameters
     public static WmiResult<LhmSensorProperty> querySensors(String parent, String sensorType) {
+        // Escape embedded double quotes in WQL string literals
+        String safeParent = parent.replace("\"", "\\\"");
+        String safeSensorType = sensorType.replace("\"", "\\\"");
         StringBuilder sb = new StringBuilder(SENSOR);
-        sb.append(" WHERE Parent=\"").append(parent);
-        sb.append("\" AND SensorType=\"").append(sensorType).append('"');
+        sb.append(" WHERE Parent=\"").append(safeParent);
+        sb.append("\" AND SensorType=\"").append(safeSensorType).append('"');
         WmiQuery<LhmSensorProperty> query = new WmiQuery<>(WmiUtil.LHM_NAMESPACE, sb.toString(),
                 LhmSensorProperty.class);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java` around lines
45 - 54, The querySensors method builds a WQL string by concatenating SENSOR
with raw parent and sensorType values, which allows injection when those strings
contain quotes/special chars; update querySensors to sanitize or escape the
parameters (escape embedded double quotes and other WQL-sensitive characters in
parent and sensorType) before appending them to the StringBuilder, or use a
parameterized WmiQuery API if available; ensure the sanitized values are used in
the WmiQuery<>(WmiUtil.LHM_NAMESPACE, sb.toString(), LhmSensorProperty.class)
call and keep the SENSOR constant and WmiQueryHandler usage unchanged.
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (2)

336-338: Consider catching more specific exception types.

Catching generic Exception here (and at lines 427, 464) may hide unexpected errors. If the WMI/COM layer throws specific exception types (e.g., COMException), catching those explicitly would make the error handling clearer and avoid swallowing unrelated exceptions.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 336 - 338, Replace the broad catch(Exception e) in the
WindowsGraphicsCard class (the try/catch blocks performing the LHM GPU
hardware/WMI queries) with catches for the specific COM/WMI exceptions thrown by
the underlying layer (e.g., COMException and any WMI-specific exception type
your COM/WMI library provides), logging those with LOG.debug as before; do not
swallow other unexpected exceptions—either let them propagate or add a separate
catch(Exception e) that rethrows (or logs at error and rethrows) so unrelated
failures are not silently ignored.

352-371: Document multi-GPU limitation in method Javadoc.

The current implementation only works reliably for single-GPU systems. While the debug log at line 368 notes this, the method's Javadoc (lines 342-350) doesn't mention this limitation. Consider adding a note to the Javadoc so callers understand the expected behavior.

📝 Proposed Javadoc addition
     /**
      * Builds the PDH LUID instance prefix used to match GPU Engine and GPU Adapter Memory counter instances to this
      * adapter. The prefix has the form {`@code` luid_0xHHHHHHHH_0xLLLLLLLL_phys_0} (case-insensitive in PDH).
      *
      * <p>
      * Since DXGI does not expose the LUID directly in {`@code` DXGI_ADAPTER_DESC}, we enumerate PDH GPU Adapter Memory
      * instances and match by adapter name to discover the LUID. Falls back to an empty string if no match is found.
      *
+     * <p>
+     * <strong>Limitation:</strong> On multi-GPU systems, this method returns an empty string because PDH GPU Adapter
+     * Memory instances do not carry adapter names, preventing reliable correlation. Callers will receive {`@code` -1}
+     * for PDH-based metrics in such configurations.
+     *
      * `@return` PDH LUID instance prefix string, or empty string if not determinable
      */
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 352 - 371, Add documentation to the buildLuidPrefix method in
WindowsGraphicsCard to explicitly state it only supports reliable LUID matching
on single-GPU systems and will return an empty string (leading to -1 PDH
metrics) when multiple GPU Adapter Memory instances are present; update the
method Javadoc to mention the multi-GPU limitation, the current behavior
(returns empty and logs a debug message), and a note that future enhancement
could correlate via DXGI LUID enumeration so callers know to expect this
limitation when calling buildLuidPrefix.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 172-177: Add DXGI LUID support: extend DxgiAdapterInfo with a luid
(two-part or 64-bit) field populated from DXGI_ADAPTER_DESC.Luid when
enumerating adapters in WindowsDxgi, then change the WindowsGraphicsCard code
path that currently calls buildLuidPrefix() to instead call a new or overloaded
buildLuidPrefix(String luid) (or buildLuidPrefixFromLuid) that formats the PDH
instance prefix as "luid_0xHHHH_0xLLLL_phys_0" using the adapter's LUID from
DxgiAdapterInfo; ensure WindowsDxgi.findMatch returns the DxgiAdapterInfo with
the new LUID so dxgiMatch.getLuid() can be used to construct the correct
LUID-based prefix for multi-GPU PDH instance matching.

---

Outside diff comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`:
- Around line 84-92: The parsing logic in LinuxGraphicsCard that sets
lookupDevice (used by queryLspciMemorySize()) is incorrectly pulling the Device:
name and only when !found, causing stale PCI addresses; change the parser to
extract the PCI slot address from the "Slot" field (split[0].equals("Slot") &&
split.length>1) and assign lookupDevice = split[1].trim() when you identify the
VGA/3D block (use found to mark start of a card but allow capturing Slot after
found is true), and ensure you reset/handle found per card so each GPU's Slot is
captured for queryLspciMemorySize(); update similar occurrences around the other
blocks (lines referenced) to consistently use Slot for lspci -s queries.

---

Nitpick comments:
In `@oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java`:
- Around line 71-76: Move the enum LhmHardwareProperty so it appears before any
methods that reference it (e.g., before queryGpuHardware()) and colocate it near
the existing LhmSensorProperty declaration to keep type declarations together;
update the class ordering only (no behavioral changes) so LhmHardwareProperty is
declared above methods like queryGpuHardware() that return
WmiResult<LhmHardwareProperty>.
- Around line 45-54: The querySensors method builds a WQL string by
concatenating SENSOR with raw parent and sensorType values, which allows
injection when those strings contain quotes/special chars; update querySensors
to sanitize or escape the parameters (escape embedded double quotes and other
WQL-sensitive characters in parent and sensorType) before appending them to the
StringBuilder, or use a parameterized WmiQuery API if available; ensure the
sanitized values are used in the WmiQuery<>(WmiUtil.LHM_NAMESPACE,
sb.toString(), LhmSensorProperty.class) call and keep the SENSOR constant and
WmiQueryHandler usage unchanged.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 336-338: Replace the broad catch(Exception e) in the
WindowsGraphicsCard class (the try/catch blocks performing the LHM GPU
hardware/WMI queries) with catches for the specific COM/WMI exceptions thrown by
the underlying layer (e.g., COMException and any WMI-specific exception type
your COM/WMI library provides), logging those with LOG.debug as before; do not
swallow other unexpected exceptions—either let them propagate or add a separate
catch(Exception e) that rethrows (or logs at error and rethrows) so unrelated
failures are not silently ignored.
- Around line 352-371: Add documentation to the buildLuidPrefix method in
WindowsGraphicsCard to explicitly state it only supports reliable LUID matching
on single-GPU systems and will return an empty string (leading to -1 PDH
metrics) when multiple GPU Adapter Memory instances are present; update the
method Javadoc to mention the multi-GPU limitation, the current behavior
(returns empty and logs a debug message), and a note that future enhancement
could correlate via DXGI LUID enumeration so callers know to expect this
limitation when calling buildLuidPrefix.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3a4b4b2c-8dc7-4d13-92d1-e29c8a199fa9

📥 Commits

Reviewing files that changed from the base of the PR and between 7a649a7 and 8381c3d.

📒 Files selected for processing (6)
  • oshi-core/src/main/java/oshi/driver/windows/perfmon/GpuInformation.java
  • oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java
  • oshi-core/src/main/java/oshi/hardware/common/DefaultGpuTicks.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-core/src/main/java/oshi/driver/windows/perfmon/GpuInformation.java
  • oshi-core/src/main/java/oshi/hardware/common/DefaultGpuTicks.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Analyze (java)
🔇 Additional comments (8)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (2)

193-209: DRM lookup is still global instead of per-card.

gpuName is still unused here, so every LinuxGraphicsCard falls back to the first cardN with a driver symlink. On multi-GPU hosts that can bind utilization/VRAM reads to the wrong adapter.


236-260: Utilization scaling now matches the API contract.

AMD now returns a fraction, and the Intel path clamps the frequency proxy to 1.0 with a clear caveat about what is being measured.

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (5)

416-432: LGTM! LHM utilization correctly converted to 0.0–1.0 range.

The division by 100.0 on line 424 properly converts LHM's percentage-based Load sensor (0–100) to the API's fractional specification (0.0–1.0). The exception handling and fallback to -1d are appropriate.


377-414: LGTM! GPU ticks implementation correctly aggregates across engine types.

The approach of summing ticks by engine type across all PIDs and taking the maximum is sound—GPU engines operate as parallel pipelines, so the maximum value represents overall adapter activity. The case-insensitive LUID matching and fallback to zero ticks are appropriate.


434-470: LGTM! VRAM used implementation with appropriate fallback chain.

The priority order (PDH DedicatedUsage → LHM SmallData) is sensible, and the MB-to-bytes conversion is correct. Both paths have proper exception handling with -1L fallback.


72-73: Annotation change from @Immutable to @ThreadSafe is appropriate.

All instance fields are final, and the dynamic metric methods perform stateless queries to external sources (PDH/WMI). The class is safe for concurrent use.


472-491: LGTM! Shared memory implementation is consistent with other PDH-based metrics.

The pattern matches getVramUsed() for PDH queries. No LHM fallback is provided, which is appropriate if LHM doesn't expose a shared memory sensor.

oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java (1)

195-242: Fix unsafe type casting of the IOAccelerator model property before using it for GPU matching.

The code directly casts modelPtr to CFStringRef (line 198) without checking its actual CoreFoundation type. In IORegistry, the model property is typically exposed as CFData (byte buffer), not CFString. If the cast fails or the pointer refers to a different CF type, stringValue() may return null or garbage, causing queryPerfStats() to fail and both getGpuUtilization() and getVramUsed() to fall back to -1. Follow the pattern from MacDisplay.java (lines 105–112): first obtain the property as CFTypeRef, then safely wrap it as the correct type (likely CFDataRef), and decode the bytes as UTF-8.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

♻️ Duplicate comments (1)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (1)

194-210: ⚠️ Potential issue | 🟠 Major

Map DRM devices by PCI identity instead of returning the first card.

findDrmInfo() still binds every card to the first cardN with a driver symlink, so multi-GPU systems can report utilization/VRAM from the wrong device. getGraphicsCardsFromLspci() already has the PCI slot, so this lookup should match /device/uevent PCI_SLOT_NAME before falling back.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`
around lines 194 - 210, findDrmInfo currently returns the first DRM card with a
driver symlink, causing wrong mappings on multi‑GPU systems; update findDrmInfo
to prefer matching the card whose device/uevent contains the PCI_SLOT_NAME that
matches the PCI slot from getGraphicsCardsFromLspci (gpuName parameter), by
reading and parsing device + "/uevent" for the "PCI_SLOT_NAME=" key (use or add
a small helper similar to readDriverName to read uevent keys), return that
matched Pair<>(devicePath, driver), and only if no PCI match is found fall back
to the first card with a non‑empty driver; reference symbols: findDrmInfo,
getGraphicsCardsFromLspci, readDriverName, PCI_SLOT_NAME, DRM_PATH.
🧹 Nitpick comments (2)
oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java (1)

52-56: Consider defensively escaping quotes in WQL parameters, though practical risk is low.

The parent parameter is concatenated directly into the WQL query without escaping. While the hardcoded sensorType values ("Load", "SmallData") pose no risk, the parent parameter is obtained from buildLhmParentMap(), which retrieves values from LibreHardwareMonitor WMI results (e.g., structured identifiers like /gpu-nvidia/0).

Since this is a controlled data source rather than user input, the practical injection risk is low. However, this method is public and defensive coding is reasonable. Similar unescaped concatenation patterns exist elsewhere in the codebase (e.g., OhmSensor.java, OhmHardware.java). If escaping is desired, verify the proper WQL escaping syntax—backslash escaping (replace("\"", "\\\"")) may not apply to WQL as it does to SQL, and WmiQuery does not appear to support parameterized queries.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java` around lines
52 - 56, The querySensors method builds a WQL string by concatenating the parent
parameter into SENSOR; make it defensive by sanitizing/escaping any double-quote
characters from parent before building the query (e.g., in
LhmSensor.querySensors replace or escape '"' in the parent value), so the
WmiQuery created with WmiUtil.LHM_NAMESPACE and the SENSOR constant cannot break
the WQL string; also consider applying the same sanitation where
buildLhmParentMap produces parent values or in callers to avoid repeating logic.
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

326-326: Minor: Consider importing HashMap for consistency.

Line 326 uses java.util.HashMap inline, but Map is already imported at line 10. For consistency, consider adding HashMap to imports.

♻️ Suggested fix

Add to imports:

import java.util.HashMap;

Then update line 326:

-        Map<String, String> map = new java.util.HashMap<>();
+        Map<String, String> map = new HashMap<>();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
at line 326, The code instantiates a java.util.HashMap inline in
WindowsGraphicsCard (variable name map) while Map is already imported; add an
import for java.util.HashMap at the top of the file and replace the inline
qualification with new HashMap<>() when constructing the Map to keep imports
consistent (update the instantiation of map in the WindowsGraphicsCard class
accordingly).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@oshi-core/src/main/java/oshi/driver/windows/DxgiAdapterInfo.java`:
- Around line 36-37: The public 6-arg constructor change breaks callers using
the previous 4-arg overload; restore a delegating 4-arg constructor in class
DxgiAdapterInfo that accepts (String description, int vendorId, int deviceId,
long dedicatedVideoMemory) and delegates to the existing DxgiAdapterInfo(String,
int, int, long, int, int) by passing 0 for luidLowPart and luidHighPart so
existing tests (e.g., WindowsDxgiTest) and other callers continue to work.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 469-472: The loops in getVramUsed() and getSharedMemoryUsed()
iterate over instances but directly index into dedicated and shared lists which
can be misaligned; update those loops to guard accesses (e.g., only return
dedicated.get(i) if i < dedicated.size(), and only return shared.get(i) if i <
shared.size()) or iterate to Math.min(instances.size(), dedicated.size()) /
Math.min(instances.size(), shared.size()) respectively, mirroring the
bounds-checking pattern used to fix getGpuTicks() so you never index past the
smaller list.
- Around line 72-73: The AbstractGraphicsCard class violates the `@Immutable`
contract because its field vram is not final; update the declaration of the vram
field in AbstractGraphicsCard (the private long vram) to be final so that vram
is immutable after construction, ensuring the immutability contract and
preserving the ThreadSafe guarantee for subclasses like WindowsGraphicsCard;
ensure constructor assignment remains unchanged and run tests/compile to verify
no other code mutates vram.
- Around line 424-433: The loop in WindowsGraphicsCard that iterates over
instances and accesses runningTimes.get(i) can throw IndexOutOfBoundsException
if runningTimes is shorter; update the loop to guard access by checking bounds
(e.g., compute an effective length using Math.min(instances.size(),
runningTimes.size()) or skip when i >= runningTimes.size()) before reading
runningTimes.get(i), keeping the rest of the logic that extracts engType and
merges into engineTypeSums unchanged.

---

Duplicate comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`:
- Around line 194-210: findDrmInfo currently returns the first DRM card with a
driver symlink, causing wrong mappings on multi‑GPU systems; update findDrmInfo
to prefer matching the card whose device/uevent contains the PCI_SLOT_NAME that
matches the PCI slot from getGraphicsCardsFromLspci (gpuName parameter), by
reading and parsing device + "/uevent" for the "PCI_SLOT_NAME=" key (use or add
a small helper similar to readDriverName to read uevent keys), return that
matched Pair<>(devicePath, driver), and only if no PCI match is found fall back
to the first card with a non‑empty driver; reference symbols: findDrmInfo,
getGraphicsCardsFromLspci, readDriverName, PCI_SLOT_NAME, DRM_PATH.

---

Nitpick comments:
In `@oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java`:
- Around line 52-56: The querySensors method builds a WQL string by
concatenating the parent parameter into SENSOR; make it defensive by
sanitizing/escaping any double-quote characters from parent before building the
query (e.g., in LhmSensor.querySensors replace or escape '"' in the parent
value), so the WmiQuery created with WmiUtil.LHM_NAMESPACE and the SENSOR
constant cannot break the WQL string; also consider applying the same sanitation
where buildLhmParentMap produces parent values or in callers to avoid repeating
logic.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Line 326: The code instantiates a java.util.HashMap inline in
WindowsGraphicsCard (variable name map) while Map is already imported; add an
import for java.util.HashMap at the top of the file and replace the inline
qualification with new HashMap<>() when constructing the Map to keep imports
consistent (update the instantiation of map in the WindowsGraphicsCard class
accordingly).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ddc9973d-f189-44af-a0a1-43f8b9af3b96

📥 Commits

Reviewing files that changed from the base of the PR and between 8381c3d and 314439c.

📒 Files selected for processing (5)
  • oshi-core/src/main/java/oshi/driver/windows/DxgiAdapterInfo.java
  • oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
🔇 Additional comments (7)
oshi-core/src/main/java/oshi/jna/platform/windows/WindowsDxgi.java (1)

261-266: LGTM: the LUID wiring is consistent with the PDH matching path.

The constructor call keeps the raw DXGI order (low, then high), while the emitted high_low representation matches the format used later by WindowsGraphicsCard.buildLuidPrefix(...). That should keep adapter identity aligned across DXGI and PDH.

oshi-core/src/main/java/oshi/driver/windows/wmi/LhmSensor.java (2)

23-43: LGTM!

The utility class structure is well-designed: @ThreadSafe is accurate (no shared mutable state), the private constructor prevents instantiation, and the enums follow the established WMI query pattern in OSHI.


68-76: LGTM!

The query uses hardcoded filter values, so there's no injection risk. The WQL syntax with multiple OR conditions is correct, and the null-safety check follows good defensive practices.

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (3)

97-113: LGTM!

The constructor properly initializes the new final fields luidPrefix and lhmParent with clear Javadoc documentation. The immutability supports the @ThreadSafe contract.


131-133: LGTM!

The LHM parent map is built once at the start and reused throughout the method, avoiding redundant WMI queries.


440-456: LGTM!

The previous review feedback about converting LHM's 0–100 percentage to the 0.0–1.0 API contract has been addressed with the /100.0 division at line 448. The defensive exception handling is appropriate.

oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (1)

237-260: Utilization scaling looks consistent now.

AMD is normalized to a 0.0–1.0 fraction, and the Intel path now documents that the frequency ratio is only a proxy.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (1)

162-165: Limitation: lshw path cannot match DRM to specific GPU on multi-GPU systems.

When using the lshw fallback (lspci unavailable), findDrmInfo(null) is called, which returns the first DRM card with a driver symlink. On multi-GPU systems, this may assign incorrect DRM paths to some cards.

This is an inherent limitation since lshw doesn't expose PCI slot information in the same format. The current behavior is acceptable as a best-effort fallback, but consider adding a brief comment near the lshw card creation noting this limitation for maintainability.

Also applies to: 181-184

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`
around lines 162 - 165, The lshw fallback currently calls findDrmInfo(null) and
may return the first DRM card with a driver symlink, potentially misassigning
DRM paths on multi-GPU systems; update the card creation sites (the
cardList.add(...) that constructs new LinuxGraphicsCard(...) where
findDrmInfo(null) is used, including the similar block at the other location) to
add a clear inline comment explaining this limitation (that lshw cannot reliably
match DRM to PCI devices and we therefore do a best-effort match by picking the
first DRM entry), so future maintainers understand the behavior and why no
stricter mapping is performed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`:
- Around line 162-165: The lshw fallback currently calls findDrmInfo(null) and
may return the first DRM card with a driver symlink, potentially misassigning
DRM paths on multi-GPU systems; update the card creation sites (the
cardList.add(...) that constructs new LinuxGraphicsCard(...) where
findDrmInfo(null) is used, including the similar block at the other location) to
add a clear inline comment explaining this limitation (that lshw cannot reliably
match DRM to PCI devices and we therefore do a best-effort match by picking the
first DRM entry), so future maintainers understand the behavior and why no
stricter mapping is performed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: bc21a47a-877a-4afc-bc93-ae40d27c7838

📥 Commits

Reviewing files that changed from the base of the PR and between 314439c and 14b643a.

📒 Files selected for processing (3)
  • oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (15)
oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java (3)

12-12: Good fix for the Javadoc typo.

The class documentation now correctly describes this as "An abstract Graphics Card" instead of "An abstract Sound Card".


21-21: Good: vram field is now final.

This aligns with the @Immutable annotation on the class and ensures thread safety for the inherited field.


84-102: LGTM: Default implementations for GPU metrics.

The default implementations correctly:

  • Return a DefaultGpuTicks with the current timestamp and 0L for activeTicks (the documented sentinel for unavailable tick-level metrics)
  • Return -1 for utilization and memory methods (the documented sentinel for unavailable values)

This provides safe fallback behavior for platforms that don't override these methods.

oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (5)

29-42: LGTM: Class annotation and new fields.

The change from @Immutable to @ThreadSafe is appropriate since the class now has methods that read dynamic system state (sysfs files). The new drmDevicePath and driverName fields are correctly declared final to maintain thread safety for the instance state.


54-59: LGTM: Constructor properly initializes DRM fields.

The constructor correctly stores the drmDevicePath and driverName after calling the parent constructor.


201-228: LGTM: DRM discovery with PCI slot matching.

The implementation now attempts to match GPU to DRM card via the PCI_SLOT_NAME from the uevent file. The endsWith comparison on line 221 correctly handles both domain-qualified (0000:01:00.0) and short (01:00.0) slot formats. The fallback to first-card-with-driver provides reasonable behavior for lshw (where slot info is unavailable) and single-GPU systems.


263-295: LGTM: GPU utilization implementations.

The implementations correctly:

  • Return 0L for activeTicks since tick-level counters aren't available via sysfs
  • AMD: Divide gpu_busy_percent by 100.0 to return 0.0–1.0 range
  • Intel: Return frequency ratio (actual / max) capped at 1.0, with an appropriate comment noting it's a proxy for utilization
  • Return -1d when metrics are unavailable

297-315: LGTM: Memory metric implementations.

The VRAM and shared memory implementations correctly return values from sysfs when available (AMD) and -1L for unsupported drivers/platforms.

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (7)

73-114: LGTM: Class annotation and new fields.

The change from @Immutable to @ThreadSafe is appropriate since the class now queries dynamic system state. The new luidPrefix and lhmParent fields are correctly declared final.


326-341: LGTM: LHM parent map building.

The method gracefully handles LHM unavailability by catching exceptions and returning an empty map. The debug-level logging is appropriate since LHM is optional.


356-396: LGTM: LUID prefix building with proper multi-GPU support.

The implementation correctly:

  • Extracts LUID parts from the DXGI adapter descriptor
  • Formats the PDH instance prefix in the correct order (luid_0xHHHH_0xLLLL_phys_0)
  • Falls back to PDH enumeration for zero LUID (software adapters)
  • Returns empty string for multi-GPU when LUID is unavailable (preventing incorrect metric attribution)

402-439: LGTM: GPU ticks implementation with proper bounds checking.

The implementation correctly:

  • Uses Math.min(instances.size(), runningTimes.size()) to prevent IndexOutOfBoundsException
  • Filters instances by LUID prefix for correct per-adapter attribution
  • Aggregates engine types and returns the max (representing overall adapter utilization)
  • Returns zero-tick snapshot when LUID is unavailable

441-457: LGTM: GPU utilization from LHM.

The implementation correctly divides the LHM percentage by 100.0 to return the 0.0–1.0 range specified by the API contract. The class Javadoc documents that LHM is optional for certain metrics.


459-496: LGTM: VRAM used implementation with PDH priority and LHM fallback.

The implementation correctly:

  • Prioritizes PDH Dedicated Usage counter (more accurate)
  • Falls back to LHM with proper MB-to-bytes conversion
  • Uses bounds checking with Math.min

498-518: LGTM: Shared memory used implementation.

The implementation correctly uses PDH Shared Usage counter with proper bounds checking.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (2)

32-32: Unused LOG variable.

The LOG field is declared but never referenced anywhere in this class. Consider removing it along with the SLF4J imports (lines 12-13) to eliminate dead code.

-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-    private static final Logger LOG = LoggerFactory.getLogger(LinuxGraphicsCard.class);
-
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`
at line 32, Remove the unused SLF4J logger and its imports: delete the private
static final Logger LOG = LoggerFactory.getLogger(LinuxGraphicsCard.class);
declaration from the LinuxGraphicsCard class and also remove the corresponding
SLF4J import lines (org.slf4j.Logger and org.slf4j.LoggerFactory) so there is no
dead code or unused imports remaining.

248-257: Misleading comment about symlink target format.

The comment on lines 253-254 mentions .ko files, but the /sys/class/drm/cardN/device/driver symlink typically resolves to a directory path like ../../../bus/pci/drivers/amdgpu, not a kernel module file. Consider clarifying:

-        // The symlink target ends with the driver module name, e.g. ".../kernel/drivers/gpu/drm/amdgpu/amdgpu.ko"
-        // or the symlink itself points to a directory named after the driver.
+        // The symlink target is typically a relative path ending with the driver name,
+        // e.g. "../../../bus/pci/drivers/amdgpu"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`
around lines 248 - 257, The comment in readDriverName incorrectly claims the
symlink target ends with a kernel module (.ko); update the comment in the
readDriverName(String driverSymlink) method to state that the
/sys/class/drm/.../driver symlink typically resolves to a driver directory
(e.g., ../../../bus/pci/drivers/amdgpu) rather than a .ko file, and keep the
existing logic that extracts the last path segment from the variable target to
return the driver name.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 441-450: The Windows implementation of getGpuUtilization() in
WindowsGraphicsCard currently divides the LHM sensor value by 100, returning
0.0–1.0, while the public contract in GraphicsCard.getGpuUtilization() specifies
a percentage 0.0–100.0; update WindowsGraphicsCard.getGpuUtilization() to return
the raw LHM percentage (remove the "/ 100.0" division or otherwise scale the
value to the 0–100 range) so the returned unit matches the GraphicsCard
documentation, and keep the same fallback/default return behavior.

---

Nitpick comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`:
- Line 32: Remove the unused SLF4J logger and its imports: delete the private
static final Logger LOG = LoggerFactory.getLogger(LinuxGraphicsCard.class);
declaration from the LinuxGraphicsCard class and also remove the corresponding
SLF4J import lines (org.slf4j.Logger and org.slf4j.LoggerFactory) so there is no
dead code or unused imports remaining.
- Around line 248-257: The comment in readDriverName incorrectly claims the
symlink target ends with a kernel module (.ko); update the comment in the
readDriverName(String driverSymlink) method to state that the
/sys/class/drm/.../driver symlink typically resolves to a driver directory
(e.g., ../../../bus/pci/drivers/amdgpu) rather than a .ko file, and keep the
existing logic that extracts the last path segment from the variable target to
return the driver name.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d8540210-017b-4c1b-8967-49388ffb9828

📥 Commits

Reviewing files that changed from the base of the PR and between 14b643a and eaa5e6f.

📒 Files selected for processing (4)
  • oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (5)
oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java (1)

31-34: LGTM: test fixtures are updated consistently for the new constructor signature.

Passing 0, 0 for the new LUID fields keeps these cases focused on findMatch behavior without changing the intent of the tests.

Also applies to: 45-48, 60-61, 71-72, 87-88

oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (4)

54-59: LGTM!

Constructor correctly initializes final fields for thread safety. The empty-string convention for unavailable DRM info is used consistently with callers.


91-101: LGTM!

Good integration of PCI slot capture for DRM matching. The slot extraction correctly happens outside the found block, ensuring the slot is captured before the card is processed.


263-295: LGTM!

Dynamic metric implementations look correct. Past review concerns have been addressed:

  • AMD utilization now returns 0.0–1.0 fraction (line 277)
  • Intel frequency-ratio proxy returns 0.0–1.0 with appropriate comment (lines 287, 292)
  • Unsupported scenarios consistently return -1

297-316: LGTM!

VRAM and shared memory implementations correctly return -1 for unsupported configurations. The inline comments adequately explain the limitations for Intel (system memory) and NVIDIA (requires NVML).

@codecov

codecov Bot commented Mar 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.45%. Comparing base (a3626c0) to head (35430c2).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3088      +/-   ##
==========================================
+ Coverage   84.64%   85.45%   +0.81%     
==========================================
  Files          33       33              
  Lines        1478     1478              
  Branches      217      217              
==========================================
+ Hits         1251     1263      +12     
+ Misses        132      118      -14     
- Partials       95       97       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (3)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (1)

270-290: ⚠️ Potential issue | 🟠 Major

GPU utilization returns 0–100 instead of 0.0–1.0 — issue persists.

The past reviews flagged this issue and were marked "addressed," but the current code still returns percentage values (0–100) instead of fractions (0.0–1.0):

  • AMD (line 272): pct >= 0 ? pct : -1d returns raw 0–100 from gpu_busy_percent
  • Intel (line 287): Math.min(100.0, actual * 100.0 / max) returns 0–100

The PR summary specifies getGpuUtilization() should return "0.0–1.0 fraction."

🔧 Proposed fix to normalize to 0.0–1.0
         if ("amdgpu".equals(driver)) {
             int pct = FileUtil.getIntFromFile(drmDevicePath + "/gpu_busy_percent");
-            return pct >= 0 ? pct : -1d;
+            return pct >= 0 ? pct / 100.0 : -1d;
         }
         if ("i915".equals(driver) || "xe".equals(driver)) {
             return intelFreqUtilization();
         }
     private double intelFreqUtilization() {
         // Frequency ratio is a rough proxy for GPU utilization; not measured core utilization.
         String gtPath = drmDevicePath + "/../gt/gt0";
         long actual = FileUtil.getLongFromFile(gtPath + "/rps_act_freq_mhz");
         long max = FileUtil.getLongFromFile(gtPath + "/rps_max_freq_mhz");
         if (actual > 0 && max > 0) {
-            return Math.min(100.0, actual * 100.0 / max);
+            return Math.min(1.0, (double) actual / max);
         }
         return -1d;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`
around lines 270 - 290, The GPU utilization methods are returning percentages
(0–100) rather than the required 0.0–1.0 fraction; update the AMD and Intel
paths to normalize to a fraction: in the branch that reads gpu_busy_percent
(using FileUtil.getIntFromFile and the drmDevicePath logic) return pct/100.0
when pct >= 0 (preserving -1d for unavailable), and in intelFreqUtilization()
convert the computed percentage Math.min(100.0, actual * 100.0 / max) to a
fraction by dividing by 100.0 (again returning -1d when values are invalid);
ensure method signatures (intelFreqUtilization and the caller, e.g.,
getGpuUtilization) continue to return double.
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

326-341: ⚠️ Potential issue | 🟠 Major

Name-keyed LHM correlation collapses identical GPUs.

The past review flagged this issue: map.put(...) overwrites when two adapters have the same normalized name. On dual-GPU systems with identical models, both WindowsGraphicsCard instances will query the same LHM parent, returning another adapter's metrics.

Consider marking ambiguous names and skipping LHM for them rather than returning incorrect data.

🛡️ Safer fallback for ambiguous LHM names
     private static Map<String, String> buildLhmParentMap() {
         Map<String, String> map = new HashMap<>();
+        java.util.Set<String> ambiguous = new java.util.HashSet<>();
         try {
             WmiResult<LhmHardwareProperty> hw = LhmSensor.queryGpuHardware();
             for (int i = 0; i < hw.getResultCount(); i++) {
                 String identifier = WmiUtil.getString(hw, LhmHardwareProperty.IDENTIFIER, i);
                 String hwName = WmiUtil.getString(hw, LhmHardwareProperty.NAME, i);
                 if (!identifier.isEmpty() && !hwName.isEmpty()) {
-                    map.put(WindowsDxgi.normalizeName(hwName), identifier);
+                    String normalized = WindowsDxgi.normalizeName(hwName);
+                    if (ambiguous.contains(normalized)) {
+                        continue;
+                    }
+                    String previous = map.putIfAbsent(normalized, identifier);
+                    if (previous != null && !previous.equals(identifier)) {
+                        map.remove(normalized);
+                        ambiguous.add(normalized);
+                    }
                 }
             }
         } catch (Exception e) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 326 - 341, The current buildLhmParentMap() uses
map.put(WindowsDxgi.normalizeName(hwName), identifier) which overwrites entries
when two adapters normalize to the same name; change buildLhmParentMap to detect
duplicates: compute norm = WindowsDxgi.normalizeName(hwName), if map does not
contain norm insert identifier, but if map already contains a different
identifier replace the value with a special marker (e.g., null or a constant
like "AMBIGUOUS") to mark the name as ambiguous, and ensure any caller (the
WindowsGraphicsCard code that looks up LHM parent IDs) treats that marker as
“skip LHM” so ambiguous names do not return another adapter’s metrics.
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java (1)

126-141: ⚠️ Potential issue | 🟠 Major

GPU utilization returns 0–100 instead of 0.0–1.0 — issue persists.

The past review flagged this and was marked "addressed," but the current code still returns values in the 0–100 range:

  • Line 132: raw / GPU_UTIL_DIVISOR * 100.0 produces 0–100
  • Line 140: num.longValue() returns raw 0–100 integer from "Device Utilization %"

The PR summary specifies getGpuUtilization() should return "0.0–1.0 fraction."

🔧 Proposed fix to normalize to 0.0–1.0
             if (result != null) {
                 CFNumberRef num = new CFNumberRef(result);
                 long raw = num.longValue();
-                return raw / GPU_UTIL_DIVISOR * 100.0;
+                return raw / GPU_UTIL_DIVISOR;
             }
             // Fallback: "Device Utilization %" (already 0-100 integer on some drivers)
             CFStringRef devUtilKey = CFStringRef.createCFString(DEVICE_UTIL_KEY);
             result = perfStats.getValue(devUtilKey);
             devUtilKey.release();
             if (result != null) {
                 CFNumberRef num = new CFNumberRef(result);
-                return num.longValue();
+                return num.longValue() / 100.0;
             }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java`
around lines 126 - 141, The method in MacGraphicsCard (getGpuUtilization)
currently returns 0–100; normalize both branches to a 0.0–1.0 fraction by
dividing the computed values by 100.0: for the core-util branch change the
expression from raw / GPU_UTIL_DIVISOR * 100.0 to raw / (GPU_UTIL_DIVISOR *
100.0) (or cast to double and divide by 100.0) and for the fallback device-util
branch return num.longValue() / 100.0 (as a double) instead of returning the raw
long; ensure return types are double to avoid integer division.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`:
- Around line 270-290: The GPU utilization methods are returning percentages
(0–100) rather than the required 0.0–1.0 fraction; update the AMD and Intel
paths to normalize to a fraction: in the branch that reads gpu_busy_percent
(using FileUtil.getIntFromFile and the drmDevicePath logic) return pct/100.0
when pct >= 0 (preserving -1d for unavailable), and in intelFreqUtilization()
convert the computed percentage Math.min(100.0, actual * 100.0 / max) to a
fraction by dividing by 100.0 (again returning -1d when values are invalid);
ensure method signatures (intelFreqUtilization and the caller, e.g.,
getGpuUtilization) continue to return double.

In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java`:
- Around line 126-141: The method in MacGraphicsCard (getGpuUtilization)
currently returns 0–100; normalize both branches to a 0.0–1.0 fraction by
dividing the computed values by 100.0: for the core-util branch change the
expression from raw / GPU_UTIL_DIVISOR * 100.0 to raw / (GPU_UTIL_DIVISOR *
100.0) (or cast to double and divide by 100.0) and for the fallback device-util
branch return num.longValue() / 100.0 (as a double) instead of returning the raw
long; ensure return types are double to avoid integer division.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 326-341: The current buildLhmParentMap() uses
map.put(WindowsDxgi.normalizeName(hwName), identifier) which overwrites entries
when two adapters normalize to the same name; change buildLhmParentMap to detect
duplicates: compute norm = WindowsDxgi.normalizeName(hwName), if map does not
contain norm insert identifier, but if map already contains a different
identifier replace the value with a special marker (e.g., null or a constant
like "AMBIGUOUS") to mark the name as ambiguous, and ensure any caller (the
WindowsGraphicsCard code that looks up LHM parent IDs) treats that marker as
“skip LHM” so ambiguous names do not return another adapter’s metrics.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e0757a5b-d8f2-4a56-8949-aea43570bcd3

📥 Commits

Reviewing files that changed from the base of the PR and between 14b643a and 016911d.

📒 Files selected for processing (5)
  • oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
  • oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-core/src/test/java/oshi/driver/windows/WindowsDxgiTest.java
  • oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Analyze (java)
🔇 Additional comments (14)
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java (4)

181-227: LGTM!

The IOKit resource management follows the established pattern from other Mac platform files. The IOIterator, CFStringRef keys, and IORegistryEntry services are properly released in finally blocks. The CFRetain before returning the sub-dictionary is correct to keep it alive after the parent props is released.


236-243: LGTM!

The name matching logic handles common variations between IOAccelerator model strings and system_profiler display names appropriately.


112-116: LGTM!

The implementation correctly returns a zero-tick snapshot with a timestamp, as macOS does not expose cumulative GPU tick counters via IOKit.


148-166: LGTM!

The VRAM usage query properly handles resource cleanup and returns -1L when the metric is unavailable, consistent with the API contract.

oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (4)

196-223: LGTM!

The findDrmInfo method now properly attempts PCI slot matching via the uevent file's PCI_SLOT_NAME key. The endsWith comparison correctly handles domain-qualified vs short PCI addresses (e.g., "0000:01:00.0" vs "01:00.0").


29-54: LGTM!

The new drmDevicePath and driverName fields are final, supporting the @ThreadSafe annotation. The constructor properly initializes all fields.


292-305: LGTM!

The VRAM usage implementation correctly limits to AMD GPUs where mem_info_vram_used is available via sysfs. The comments appropriately explain that Intel uses system memory and NVIDIA requires NVML.


232-252: LGTM!

The helper methods properly handle edge cases: readUeventValue safely iterates file lines and returns empty string if the key isn't found; readDriverName extracts the driver name from the symlink target's last path segment with appropriate null checks.

oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (6)

402-439: LGTM!

The getGpuTicks implementation correctly aggregates GPU engine running times by engine type and returns the maximum, which represents overall adapter utilization. The bounds check at line 425 (Math.min(instances.size(), runningTimes.size())) properly guards against misaligned PDH query results.


459-496: LGTM!

The getVramUsed implementation correctly prioritizes PDH dedicated usage (with LUID matching) and falls back to LHM memory sensors when PDH is unavailable. The MB-to-bytes conversion uses the correct constant.


498-518: LGTM!

The getSharedMemoryUsed implementation correctly queries PDH shared usage counters with LUID matching and returns -1L when unavailable.


356-396: LGTM!

The LUID prefix building correctly uses the DXGI adapter's LUID when available, with an appropriate fallback to PDH enumeration for single-GPU systems. Multi-GPU systems without valid LUIDs are handled gracefully by returning empty string (resulting in -1 metrics).


91-114: LGTM!

The new luidPrefix and lhmParent fields are final, properly supporting the @ThreadSafe annotation. The constructor documentation clearly explains the purpose of each parameter.


441-457: The GraphicsCard interface documentation explicitly specifies: "utilization in the range 0.0 to 100.0" — a percentage, not a 0.0–1.0 fraction. All platform implementations (Windows, macOS, Linux) consistently return values in the 0–100 percentage range. The Windows implementation is correct and requires no changes.

Note: The PR summary's reference to "0.0–1.0 fraction" appears to be inaccurate; the actual documented and implemented API contract is 0–100 percentage.

			> Likely an incorrect or invalid review comment.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

453-458: ⚠️ Potential issue | 🟠 Major

Normalize LHM load to the 0.0–1.0 API range.

LhmSensor load sensors report percentages, so this currently returns 0..100 on Windows while the new GraphicsCard API is defined as a fraction. Divide by 100.0 before returning.

Suggested fix
-                        return WmiUtil.getFloat(sensors, LhmSensorProperty.VALUE, i);
+                        return WmiUtil.getFloat(sensors, LhmSensorProperty.VALUE, i) / 100d;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 453 - 458, The GPU load from LhmSensor is reported as a percentage
but WindowsGraphicsCard's code (in the block using LhmSensor.querySensors,
WmiResult<LhmSensorProperty>, and WmiUtil.getFloat with LhmSensorProperty.VALUE)
currently returns 0..100; change the return to a fraction by dividing the
retrieved value by 100.0 (e.g., return WmiUtil.getFloat(...)/100.0f or /100.0)
so the GraphicsCard API receives a 0.0–1.0 value and keep the same return type
used by the surrounding method.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 412-413: The code in WindowsGraphicsCard assigns
GpuTicks.timestamp using System.nanoTime() which is monotonic, not wall-clock;
change the timestamp computation in the WindowsGraphicsCard logic (the long
variable named timestamp used to populate GpuTicks / GpuTicks.getTimestamp()) to
use wall-clock time in 100ns units—for example derive it from
System.currentTimeMillis() multiplied by 10_000L (optionally adding finer
precision if desired) so GpuTicks.getTimestamp() returns real-world time as
documented.

---

Duplicate comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 453-458: The GPU load from LhmSensor is reported as a percentage
but WindowsGraphicsCard's code (in the block using LhmSensor.querySensors,
WmiResult<LhmSensorProperty>, and WmiUtil.getFloat with LhmSensorProperty.VALUE)
currently returns 0..100; change the return to a fraction by dividing the
retrieved value by 100.0 (e.g., return WmiUtil.getFloat(...)/100.0f or /100.0)
so the GraphicsCard API receives a 0.0–1.0 value and keep the same return type
used by the surrounding method.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 46c482f7-44bc-4d6f-8eda-1cda85c6cf17

📥 Commits

Reviewing files that changed from the base of the PR and between 016911d and f8b7c65.

📒 Files selected for processing (1)
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

449-464: ⚠️ Potential issue | 🟠 Major

getGpuUtilization() still has no PDH-backed path.

This method only returns an LHM Load sensor and otherwise reports -1, so Windows GPU utilization stays unsupported on stock systems even though this class now has per-adapter PDH engine data. Please either add the promised PDH fallback here or narrow the Windows docs so callers do not expect utilization without LHM.

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@oshi-core/src/main/java/oshi/hardware/GpuTicks.java`:
- Around line 9-15: Update the class-level Javadoc for GpuTicks to correctly
describe the timestamp as a monotonic time source rather than a wall-clock time:
change "wall-clock timestamp" to indicate the timestamp is a monotonic,
System.nanoTime()-style value captured at the same instant as activeTicks so
callers compute utilization using deltas (e.g., (delta activeTicks)/(delta
timestamp) * 100); also ensure the getTimestamp() method Javadoc explicitly
states it returns a monotonic nanosecond timestamp suitable for interval
calculations, not real-world clock time.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 428-446: The current code in WindowsGraphicsCard groups
RUNNING_TIME by engine type into engineTypeSums and returns maxTicks (max of
sums), but because RUNNING_TIME is cumulative per engine type that lets deltas
undercount when the busiest engine class shifts; change the aggregation so you
return the cumulative total across all engine types instead of the max — i.e.,
sum engineTypeSums.values() into totalTicks and return new
DefaultGpuTicks(timestamp, totalTicks) (ensure you still filter instances by
luidPrefix and use the same instances/runningTimes logic when building
engineTypeSums).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: caef9121-8e70-49be-89b2-2adb09b65524

📥 Commits

Reviewing files that changed from the base of the PR and between f8b7c65 and 43567cd.

📒 Files selected for processing (2)
  • oshi-core/src/main/java/oshi/hardware/GpuTicks.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 11, windows-latest

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)

451-466: ⚠️ Potential issue | 🟠 Major

getGpuUtilization() is still effectively LHM-only on Windows.

The PR objective says Windows utilization should be PDH-backed with LHM fallback and exposed as a 0.0–1.0 fraction, but this method returns -1d whenever LHM is absent/fails and currently returns the raw LHM reading directly. That means utilization is unavailable on stock systems without LibreHardwareMonitor, and the unit may not match the public contract. Please add the PDH path here (or narrow the Windows/docs contract) and normalize the LHM value before returning it.

#!/bin/bash
set -e

printf '\n== GraphicsCard utilization contract ==\n'
fd '^GraphicsCard\.java$' oshi-core/src/main/java -t f -x sed -n '55,95p' {}

printf '\n== WindowsGraphicsCard.getGpuUtilization() ==\n'
sed -n '451,466p' oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java

printf '\n== PDH-related GPU paths in WindowsGraphicsCard ==\n'
rg -n 'getGpuUtilization|getGpuTicks|queryGpuEngineCounters|RUNNING_TIME' --type java \
  oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`
around lines 451 - 466, getGpuUtilization currently only uses LHM and returns
raw LHM values or -1; change it to attempt the PDH-backed path first (use the
existing PDH helpers in this class such as queryGpuEngineCounters/getGpuTicks or
other PDH GPU methods) and return a 0.0–1.0 fraction when PDH succeeds, and only
then fall back to LHM (keep the existing LhmSensor.querySensors/lhmParent logic
but normalize the LHM reading by dividing the returned WmiUtil.getFloat(...)
value by 100.0 and clamp to [0.0,1.0]); only return -1d if both PDH and the
normalized LHM fallback fail, and keep the existing exception handling/logging
around the LHM block.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In
`@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java`:
- Around line 451-466: getGpuUtilization currently only uses LHM and returns raw
LHM values or -1; change it to attempt the PDH-backed path first (use the
existing PDH helpers in this class such as queryGpuEngineCounters/getGpuTicks or
other PDH GPU methods) and return a 0.0–1.0 fraction when PDH succeeds, and only
then fall back to LHM (keep the existing LhmSensor.querySensors/lhmParent logic
but normalize the LHM reading by dividing the returned WmiUtil.getFloat(...)
value by 100.0 and clamp to [0.0,1.0]); only return -1d if both PDH and the
normalized LHM fallback fail, and keep the existing exception handling/logging
around the LHM block.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c15dc80c-2ba9-4696-a98c-1d0cffa1b6b3

📥 Commits

Reviewing files that changed from the base of the PR and between 43567cd and 35430c2.

📒 Files selected for processing (1)
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant