Repository navigation
Add session-based GpuStats API with platform-specific implementations - #3095
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughMoves GPU metric access from static per-call getters to per-card, AutoCloseable GpuStats sessions; introduces platform implementations (macOS/Linux/Windows), replaces IOReportDriver with instance IOReportClient, updates GraphicsCard to createStatsSession(), and adjusts tests and demos accordingly. Changes
Sequence Diagram(s)mermaid Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
✨ Simplify code
📝 Coding Plan
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. Comment |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #3095 +/- ##
==========================================
- Coverage 69.49% 69.21% -0.28%
==========================================
Files 35 36 +1
Lines 1839 1871 +32
Branches 297 305 +8
==========================================
+ Hits 1278 1295 +17
- Misses 461 478 +17
+ Partials 100 98 -2 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (10)
oshi-demo/src/main/java/oshi/demo/GpuStatsDemo.java (1)
52-59: Demo correctly seeds tick snapshots; clarify the "priming" call.The seeding pattern is correct. The
stats.getPowerDraw()call on line 57 primes the power delta calculation (IOReportClient needs a previous sample to compute instantaneous power). Consider adding a brief comment explaining this:try (GpuStats stats = cards.get(i).createStatsSession()) { prev[i] = stats.getGpuTicks(); - stats.getPowerDraw(); // prime power delta + stats.getPowerDraw(); // prime power delta (first call returns -1, subsequent calls compute watts from energy delta) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-demo/src/main/java/oshi/demo/GpuStatsDemo.java` around lines 52 - 59, The seeding loop correctly captures initial GpuTicks snapshots but the call to stats.getPowerDraw() is used to prime the IOReportClient’s power-delta calculation and should be documented; update the GpuStatsDemo seeding block (methods/classes: GpuStats.createStatsSession(), GpuStats.getGpuTicks(), GpuStats.getPowerDraw(), and GpuTicks) by adding a brief inline comment explaining that getPowerDraw() is invoked to establish a previous power sample so subsequent instantaneous power deltas can be computed correctly.oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java (2)
52-56: Constructor may leaveioReportClientnull even on Apple Silicon ifIOReportClient.create()fails.Line 55 assigns
IOReportClient.create()which can returnnullif IOReport subscription fails. The code handles this correctly in metric methods (e.g., line 74 checksioReportClient != null), but consider logging a warning when creation fails on Apple Silicon so users know why metrics are unavailable.Suggested logging
MacGpuStats(boolean isAppleSilicon, String cardName) { this.isAppleSilicon = isAppleSilicon; this.cardName = cardName; - this.ioReportClient = isAppleSilicon ? IOReportClient.create() : null; + if (isAppleSilicon) { + this.ioReportClient = IOReportClient.create(); + if (this.ioReportClient == null) { + // IOReport subscription failed; metrics will fall back to perf stats + } + } else { + this.ioReportClient = null; + } }🤖 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/MacGpuStats.java` around lines 52 - 56, The MacGpuStats constructor currently sets this.ioReportClient = isAppleSilicon ? IOReportClient.create() : null but doesn't notify when creation fails; update the MacGpuStats(boolean isAppleSilicon, String cardName) constructor to check after calling IOReportClient.create() and, if isAppleSilicon is true and ioReportClient is null, emit a warning log (include cardName and that IOReport subscription failed so metrics will be unavailable) using the project's logging facility; keep existing null checks in metric methods unchanged.
258-265: Name matching logic may have false positives.Line 264 uses
normModel.contains(normName)which could match unrelated cards. For example, ifcardNameis "M1" andmodelis "M1 Pro", it would match, which is likely correct. But ifcardNameis "Pro" andmodelis "M1 Pro", it would also match incorrectly.Consider requiring the match in both directions or using word boundaries.
🤖 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/MacGpuStats.java` around lines 258 - 265, The current matchesName method (using TRADEMARK_PATTERN, normModel, normName, and cardName) allows false positives via normModel.contains(normName); change the check to use word-boundary matching instead of raw contains: build a safe regex with Pattern.quote(normName) wrapped in "\\b...\\b" and test against normModel (and/or test the reverse: normName against normModel) so only whole-word matches succeed; update the return to use equals(...) || wordBoundaryMatcherOn(normModel, normName) (and optionally also wordBoundaryMatcherOn(normName, normModel)) to avoid partial substring hits.oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGpuStats.java (3)
103-120: Temperature fallback threshold excludes edge case.Line 115 checks
milliC > 0, which would exclude a temperature reading of exactly 0°C. While unlikely for a GPU under normal operation, consider using>= 0for consistency with other sentinel checks, or document this as intentional.Same applies to line 134 for power (
microW > 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/linux/LinuxGpuStats.java` around lines 103 - 120, The getTemperature method (in class LinuxGpuStats) currently ignores a legitimate 0°C reading by checking milliC > 0; update that sentinel check to use >= 0 so a 0 value is accepted (mirror the NvmlUtil check pattern), and make the analogous change in the power-reading check that tests microW > 0 (likely in the getPower or related method) to microW >= 0; locate checks by the symbols getTemperature, hwmonPath, and any microW variable or getPower method and change the comparisons accordingly.
226-237: NVML device lookup is repeated on every metric call.
findNvmlDevice()is called ingetTemperature(),getPowerDraw(),getCoreClockMhz(),getMemoryClockMhz(), andgetFanSpeedPercent(). Each call invokesNvmlUtil.findDevice()which per the context snippet doesnvmlInit/nvmlUninitand string matching.Consider caching the NVML device ID at construction time or on first use to avoid repeated lookups.
Suggested caching pattern
+ // Lazily cached NVML device ID + private volatile String cachedNvmlDevice; + private volatile boolean nvmlDeviceLookedUp; + private String findNvmlDevice() { + if (nvmlDeviceLookedUp) { + return cachedNvmlDevice; + } if (!NvmlUtil.isAvailable()) { + nvmlDeviceLookedUp = true; return null; } if (!pciBusId.isEmpty()) { String id = NvmlUtil.findDevice(pciBusId); if (id != null) { + cachedNvmlDevice = id; + nvmlDeviceLookedUp = true; return id; } } - return NvmlUtil.findDeviceByName(cardName); + cachedNvmlDevice = NvmlUtil.findDeviceByName(cardName); + nvmlDeviceLookedUp = true; + return cachedNvmlDevice; }🤖 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/LinuxGpuStats.java` around lines 226 - 237, The NVML device lookup in LinuxGpuStats.findNvmlDevice is invoked on every metric method (getTemperature, getPowerDraw, getCoreClockMhz, getMemoryClockMhz, getFanSpeedPercent) and repeatedly calls NvmlUtil.findDevice/findDeviceByName (which does nvmlInit/nvmlUninit); change LinuxGpuStats to cache the resolved NVML device id either at construction or via a thread-safe lazy-initialized field (e.g., a private volatile String nvmlDeviceId) and update findNvmlDevice to return the cached id (performing the NvmlUtil lookup only once when nvmlDeviceId is null, using pciBusId and cardName as now); ensure subsequent metric methods use the cached nvmlDeviceId and handle NVML unavailability (null) the same way as today.
57-61:getGpuTicks()always returns 0 active ticks on Linux.This returns a valid
GpuTickswith timestamp butactiveTicks = 0L, meaning tick-based utilization calculations in callers (likeGpuStatsDemo) will always yield 0% or NaN. This appears intentional as Linux doesn't expose cumulative GPU ticks, but consider adding a Javadoc note or logging a debug message on first call indicating tick data is unavailable.oshi-core/src/test/java/oshi/hardware/GpuStatsTest.java (1)
100-122: Concurrent access test has a race condition and incomplete executor shutdown.
Lines 108-112: The check-then-act pattern
if (!stats.isClosed()) { stats.getGpuTicks(); ... }is racy. Another thread could callclose()between the check and the method calls. Sinceclose()is called on line 118 only afterinvokeAllcompletes, this particular test won't fail, but the pattern doesn't actually test concurrent access to metrics—it only tests that metrics can be read in parallel while the session remains open.Lines 117-121:
pool.shutdown()initiates orderly shutdown but doesn't wait. Should callawaitTermination()to ensure all tasks complete before proceeding.Suggested improvements
List<Future<Void>> futures = pool.invokeAll(tasks); pool.shutdown(); + pool.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS); stats.close(); for (Future<Void> f : futures) { f.get(); // rethrows any exception from the task }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core/src/test/java/oshi/hardware/GpuStatsTest.java` around lines 100 - 122, The test testConcurrentAccessDoesNotThrow has a racy check-then-act pattern and doesn't wait for executor termination; remove the pre-check that guards calls on the shared NoOpGpuStats instance and instead call stats.getGpuTicks(), stats.getTemperature(), and stats.getPowerDraw() directly inside each task to truly exercise concurrent reads while the session is open (the test already closes stats after invokeAll), and replace pool.shutdown() with a proper shutdown sequence that calls pool.shutdown() followed by pool.awaitTermination(timeout, TimeUnit.SECONDS) (and handle InterruptedException) to ensure all tasks have completed before stats.close() and future.get() are checked.oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java (2)
287-305: NVML and ADL device lookups repeated on every metric call.Similar to LinuxGpuStats,
findNvmlDevice()andfindAdlIndex()are called in multiple metric methods (getTemperature,getPowerDraw,getCoreClockMhz,getMemoryClockMhz,getFanSpeedPercent). Consider caching these values at construction or on first lookup.Suggested caching pattern
+ private volatile String cachedNvmlDevice; + private volatile boolean nvmlLookedUp; + private volatile int cachedAdlIndex = Integer.MIN_VALUE; + private String findNvmlDevice() { + if (nvmlLookedUp) { + return cachedNvmlDevice; + } if (!NvmlUtil.isAvailable()) { + nvmlLookedUp = true; return null; } // ... existing logic ... + nvmlLookedUp = true; + cachedNvmlDevice = result; return result; } private int findAdlIndex() { + if (cachedAdlIndex != Integer.MIN_VALUE) { + return cachedAdlIndex; + } if (!AdlUtil.isAvailable() || pciBusNumber < 0) { + cachedAdlIndex = -1; return -1; } - return AdlUtil.findAdapterIndex(pciBusNumber); + cachedAdlIndex = AdlUtil.findAdapterIndex(pciBusNumber); + return cachedAdlIndex; }🤖 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/WindowsGpuStats.java` around lines 287 - 305, The device lookups in findNvmlDevice() and findAdlIndex() are being invoked repeatedly from each metric getter; cache the results instead by introducing a cachedNvmlDevice (String) and cachedAdlIndex (int) on the class and populate them either in the constructor or lazily on first access (e.g., check if cachedNvmlDevice is null / cachedAdlIndex == Integer.MIN_VALUE then call NvmlUtil.findDevice(...) and AdlUtil.findAdapterIndex(...)). Replace direct calls in getTemperature, getPowerDraw, getCoreClockMhz, getMemoryClockMhz, and getFanSpeedPercent to use the cached fields and ensure the cache initialization honors the existing availability checks (NvmlUtil.isAvailable(), AdlUtil.isAvailable() and pciBusNumber / pciBusId logic) so behavior is unchanged.
97-113:getGpuUtilization()only uses LHM with no PDH fallback.This method returns -1 when LibreHardwareMonitor isn't running, even though PDH GPU Engine counters could potentially provide utilization data. If PDH-based utilization is desired as a fallback, consider adding it here.
However, if LHM-only is intentional (e.g., PDH doesn't expose direct utilization percentage), this is fine as documented.
🤖 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/WindowsGpuStats.java` around lines 97 - 113, getGpuUtilization() currently only attempts LibreHardwareMonitor via lhmParent and returns -1 if that fails; add a PDH-based fallback using the GPU Engine counters when LHM is not available or its query throws. Modify getGpuUtilization() (after checkOpen() and after the LHM try/catch or when lhmParent.isEmpty()) to call the existing PDH GPU engine counter logic (use the same PDH helper used elsewhere in this class or project—e.g., PdhUtil/PdhCounter methods that read "GPU Engine" percent counters) and return that value if present, otherwise keep returning -1; ensure to reference LhmSensor.querySensors, WmiUtil.getFloat and the PDH counter helper so the new code tries LHM first and PDH second.oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java (1)
83-126:toString()opens a stats session which may have performance implications.Opening a native session in
toString()could be expensive if called frequently (e.g., during logging or debugging). This is a behavioral change from the previous implementation.The implementation is correct—try-with-resources ensures proper cleanup, and the contract states
createStatsSession()never throws. However, consider documenting this overhead in the class Javadoc or adding a note that callers should cachetoString()results if needed repeatedly.🤖 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/AbstractGraphicsCard.java` around lines 83 - 126, The toString() implementation on AbstractGraphicsCard calls createStatsSession() and opens a native GpuStats session (via GpuStats and createStatsSession()), which can be expensive if invoked frequently; update the class Javadoc (or the toString() javadoc) to explicitly document that toString() opens a native stats session and may have performance implications and advise callers to avoid calling it in hot paths or to cache results if needed repeatedly, and include a brief note that createStatsSession() is used and GpuStats resources are acquired and released in a try-with-resources block.
🤖 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/mac/IOReportClient.java`:
- Around line 24-29: Replace the broken Javadoc link to IOReportDriver in the
IOReportClient class comment: edit the Javadoc block that currently contains
"{`@link` IOReportDriver}" and either change it to plain text "IOReportDriver" or
point it to an existing type (e.g., IOReportClient's parent or another valid
class) so Javadoc no longer references a non-existent class; ensure the rest of
the description about instance-based subscription behavior and relation to
oshi.hardware.GpuStats remains unchanged.
In `@oshi-core/src/main/java/oshi/hardware/GpuStats.java`:
- Around line 37-44: The JavaDoc for GpuTicks (and getGpuTicks()) currently
claims timestamp is a wall-clock time but implementations (NoOpGpuStats,
IOReportClient) use System.nanoTime(); update the API contract instead of
changing every implementation: change GpuTicks.timestamp Javadoc to state it is
a monotonic (elapsed) timestamp in 100-nanosecond units (derived from
System.nanoTime()) and update getGpuTicks() Javadoc to match; also add a brief
note in NoOpGpuStats and IOReportClient comments that they intentionally use
System.nanoTime()/100L so consumers know the timestamp is monotonic, not
wall-clock.
In `@oshi-core/src/test/java/oshi/hardware/GraphicsCardTest.java`:
- Around line 34-35: The test calls graphicsCard.createStatsSession() but never
closes the returned session, leaking native resources; update GraphicsCardTest
to capture the session returned by createStatsSession() and ensure it is closed
(either use try-with-resources around the session or call session.close() in a
finally block) so every created session is properly closed after the assertion.
---
Nitpick comments:
In `@oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java`:
- Around line 83-126: The toString() implementation on AbstractGraphicsCard
calls createStatsSession() and opens a native GpuStats session (via GpuStats and
createStatsSession()), which can be expensive if invoked frequently; update the
class Javadoc (or the toString() javadoc) to explicitly document that toString()
opens a native stats session and may have performance implications and advise
callers to avoid calling it in hot paths or to cache results if needed
repeatedly, and include a brief note that createStatsSession() is used and
GpuStats resources are acquired and released in a try-with-resources block.
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGpuStats.java`:
- Around line 103-120: The getTemperature method (in class LinuxGpuStats)
currently ignores a legitimate 0°C reading by checking milliC > 0; update that
sentinel check to use >= 0 so a 0 value is accepted (mirror the NvmlUtil check
pattern), and make the analogous change in the power-reading check that tests
microW > 0 (likely in the getPower or related method) to microW >= 0; locate
checks by the symbols getTemperature, hwmonPath, and any microW variable or
getPower method and change the comparisons accordingly.
- Around line 226-237: The NVML device lookup in LinuxGpuStats.findNvmlDevice is
invoked on every metric method (getTemperature, getPowerDraw, getCoreClockMhz,
getMemoryClockMhz, getFanSpeedPercent) and repeatedly calls
NvmlUtil.findDevice/findDeviceByName (which does nvmlInit/nvmlUninit); change
LinuxGpuStats to cache the resolved NVML device id either at construction or via
a thread-safe lazy-initialized field (e.g., a private volatile String
nvmlDeviceId) and update findNvmlDevice to return the cached id (performing the
NvmlUtil lookup only once when nvmlDeviceId is null, using pciBusId and cardName
as now); ensure subsequent metric methods use the cached nvmlDeviceId and handle
NVML unavailability (null) the same way as today.
In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java`:
- Around line 52-56: The MacGpuStats constructor currently sets
this.ioReportClient = isAppleSilicon ? IOReportClient.create() : null but
doesn't notify when creation fails; update the MacGpuStats(boolean
isAppleSilicon, String cardName) constructor to check after calling
IOReportClient.create() and, if isAppleSilicon is true and ioReportClient is
null, emit a warning log (include cardName and that IOReport subscription failed
so metrics will be unavailable) using the project's logging facility; keep
existing null checks in metric methods unchanged.
- Around line 258-265: The current matchesName method (using TRADEMARK_PATTERN,
normModel, normName, and cardName) allows false positives via
normModel.contains(normName); change the check to use word-boundary matching
instead of raw contains: build a safe regex with Pattern.quote(normName) wrapped
in "\\b...\\b" and test against normModel (and/or test the reverse: normName
against normModel) so only whole-word matches succeed; update the return to use
equals(...) || wordBoundaryMatcherOn(normModel, normName) (and optionally also
wordBoundaryMatcherOn(normName, normModel)) to avoid partial substring hits.
In `@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java`:
- Around line 287-305: The device lookups in findNvmlDevice() and findAdlIndex()
are being invoked repeatedly from each metric getter; cache the results instead
by introducing a cachedNvmlDevice (String) and cachedAdlIndex (int) on the class
and populate them either in the constructor or lazily on first access (e.g.,
check if cachedNvmlDevice is null / cachedAdlIndex == Integer.MIN_VALUE then
call NvmlUtil.findDevice(...) and AdlUtil.findAdapterIndex(...)). Replace direct
calls in getTemperature, getPowerDraw, getCoreClockMhz, getMemoryClockMhz, and
getFanSpeedPercent to use the cached fields and ensure the cache initialization
honors the existing availability checks (NvmlUtil.isAvailable(),
AdlUtil.isAvailable() and pciBusNumber / pciBusId logic) so behavior is
unchanged.
- Around line 97-113: getGpuUtilization() currently only attempts
LibreHardwareMonitor via lhmParent and returns -1 if that fails; add a PDH-based
fallback using the GPU Engine counters when LHM is not available or its query
throws. Modify getGpuUtilization() (after checkOpen() and after the LHM
try/catch or when lhmParent.isEmpty()) to call the existing PDH GPU engine
counter logic (use the same PDH helper used elsewhere in this class or
project—e.g., PdhUtil/PdhCounter methods that read "GPU Engine" percent
counters) and return that value if present, otherwise keep returning -1; ensure
to reference LhmSensor.querySensors, WmiUtil.getFloat and the PDH counter helper
so the new code tries LHM first and PDH second.
In `@oshi-core/src/test/java/oshi/hardware/GpuStatsTest.java`:
- Around line 100-122: The test testConcurrentAccessDoesNotThrow has a racy
check-then-act pattern and doesn't wait for executor termination; remove the
pre-check that guards calls on the shared NoOpGpuStats instance and instead call
stats.getGpuTicks(), stats.getTemperature(), and stats.getPowerDraw() directly
inside each task to truly exercise concurrent reads while the session is open
(the test already closes stats after invokeAll), and replace pool.shutdown()
with a proper shutdown sequence that calls pool.shutdown() followed by
pool.awaitTermination(timeout, TimeUnit.SECONDS) (and handle
InterruptedException) to ensure all tasks have completed before stats.close()
and future.get() are checked.
In `@oshi-demo/src/main/java/oshi/demo/GpuStatsDemo.java`:
- Around line 52-59: The seeding loop correctly captures initial GpuTicks
snapshots but the call to stats.getPowerDraw() is used to prime the
IOReportClient’s power-delta calculation and should be documented; update the
GpuStatsDemo seeding block (methods/classes: GpuStats.createStatsSession(),
GpuStats.getGpuTicks(), GpuStats.getPowerDraw(), and GpuTicks) by adding a brief
inline comment explaining that getPowerDraw() is invoked to establish a previous
power sample so subsequent instantaneous power deltas can be computed correctly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: b77ecbdd-11d6-45b3-8711-d29707dc7439
📒 Files selected for processing (17)
oshi-core/src/main/java/oshi/driver/mac/IOReportClient.javaoshi-core/src/main/java/oshi/hardware/GpuStats.javaoshi-core/src/main/java/oshi/hardware/GraphicsCard.javaoshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/common/NoOpGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.javaoshi-core/src/test/java/oshi/driver/mac/IOReportClientTest.javaoshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.javaoshi-core/src/test/java/oshi/hardware/GpuStatsTest.javaoshi-core/src/test/java/oshi/hardware/GraphicsCardTest.javaoshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.javaoshi-demo/src/main/java/oshi/demo/GpuStatsDemo.java
💤 Files with no reviewable changes (1)
- oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.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 11, macos-latest
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Analyze (java)
🔇 Additional comments (6)
oshi-demo/src/main/java/oshi/demo/GpuStatsDemo.java (1)
61-86: Session-per-iteration pattern is correct but potentially inefficient for real-world use.Creating a new
GpuStatssession per card per iteration (line 65) is fine for a demo but incurs overhead from native resource allocation/deallocation on each iteration. For production polling loops, consider keeping sessions open across iterations and documenting this trade-off.The demo code itself is correct and clearly demonstrates the API.
oshi-core/src/main/java/oshi/hardware/GraphicsCard.java (1)
67-77: Clean API design with clear contract.The
createStatsSession()documentation is well-written:
- Explicitly states it never returns null and never throws
- Documents that unsupported platforms return a no-op instance with sentinel values
- Javadoc example shows proper try-with-resources usage
oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java (1)
65-68: Default implementation returns NoOpGpuStats as documented.This correctly implements the contract from
GraphicsCard.createStatsSession()where platforms without native support return a no-op instance. Subclasses override this to provide platform-specific implementations.oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (1)
124-127:createStatsSession()correctly wires parameters to WindowsGpuStats.The parameter order matches the
WindowsGpuStatsconstructor signature:(luidPrefix, lhmParent, pciBusNumber, pciBusId, cardName). The session receives all identifiers needed for PDH, LHM, NVML, and ADL metric sources.oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java (1)
215-256:queryPerfStats()correctly manages IOKit and CoreFoundation resources.The method properly:
- Releases the iterator, keys, service entries, and property dictionaries in finally blocks
- Uses CFRetain on the stats dictionary before releasing the parent props dictionary (line 238-239)
- Returns null safely when no match is found
The pattern on lines 236-240 (creating a new
CFMutableDictionaryRef, setting its pointer, and calling CFRetain) is the correct JNA approach for retaining a nested dictionary value.oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java (1)
68-95:getGpuTicks()correctly aggregates PDH GPU Engine running times.The implementation:
- Filters instances by LUID prefix (case-insensitive)
- Groups by engine type to handle multiple engines of the same type
- Sums all running times across engine types
This correctly produces cumulative ticks matching the
GpuTickscontract.
There was a problem hiding this comment.
Actionable comments posted: 5
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/driver/mac/IOReportClient.java (1)
233-235:⚠️ Potential issue | 🟡 MinorMinor: Comment contains incorrect unit conversion.
The comment states "1 µJ/ns = 1 mW" but the correct conversion is 1 µJ/ns = 1 kW (since 10⁻⁶ J / 10⁻⁹ s = 10³ W). The formula
energyUj * 1000.0 / dtNanosis correct and produces watts.📝 Suggested fix
- // microjoules / nanoseconds * 1000 = watts (1 µJ/ns = 1 mW) + // µJ * 1000 / ns = W (dimensional: 10^-6 J * 10^3 / 10^-9 s = J/s = W) return energyUj * 1000.0 / dtNanos;🤖 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/mac/IOReportClient.java` around lines 233 - 235, The inline comment in IOReportClient referencing the energy-to-power conversion is incorrect: it says "1 µJ/ns = 1 mW" while the calculation in the method (return energyUj * 1000.0 / dtNanos) is correct and yields watts; update the comment near the return in the method of IOReportClient to state the correct conversion (1 µJ/ns = 1 kW or show the unit math) so it matches the implemented formula.
🧹 Nitpick comments (4)
oshi-core/src/test/java/oshi/hardware/GpuStatsTest.java (1)
101-122: Consider using try-finally for executor cleanup.If
invokeAll()throws an exception (e.g.,InterruptedException), the thread pool won't be shut down, potentially leaking threads. Additionally, the return value ofawaitTermination()is ignored.♻️ Suggested improvement
`@Test` void testConcurrentAccessDoesNotThrow() throws Exception { GpuStats stats = new NoOpGpuStats(); int threads = 8; ExecutorService pool = Executors.newFixedThreadPool(threads); - List<Callable<Void>> tasks = new ArrayList<>(); - for (int i = 0; i < threads; i++) { - tasks.add(() -> { - stats.getGpuTicks(); - stats.getTemperature(); - stats.getPowerDraw(); - return null; - }); - } - List<Future<Void>> futures = pool.invokeAll(tasks); - pool.shutdown(); - pool.awaitTermination(5L, TimeUnit.SECONDS); - stats.close(); - for (Future<Void> f : futures) { - f.get(); // rethrows any exception from the task + try { + List<Callable<Void>> tasks = new ArrayList<>(); + for (int i = 0; i < threads; i++) { + tasks.add(() -> { + stats.getGpuTicks(); + stats.getTemperature(); + stats.getPowerDraw(); + return null; + }); + } + List<Future<Void>> futures = pool.invokeAll(tasks); + for (Future<Void> f : futures) { + f.get(); // rethrows any exception from the task + } + } finally { + pool.shutdown(); + pool.awaitTermination(5L, TimeUnit.SECONDS); + stats.close(); } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core/src/test/java/oshi/hardware/GpuStatsTest.java` around lines 101 - 122, The testConcurrentAccessDoesNotThrow test should ensure the ExecutorService is always shut down and that awaitTermination's result is handled; wrap the pool.invokeAll(...) and futures processing in a try block and call pool.shutdown() in a finally block (or call shutdownNow() if awaitTermination(timeout) returns false) to avoid thread leaks, and preserve the existing stats.close() and futures.get() handling so any task exceptions still propagate; reference GpuStats/NoOpGpuStats, pool.invokeAll, pool.shutdown, pool.awaitTermination, and stats.close when making the change.oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java (1)
120-174: Consider extracting PDH adapter memory query logic.The LUID-based filtering pattern for
queryGpuAdapterMemoryCounters()is duplicated betweengetVramUsed()andgetSharedMemoryUsed(). A small helper could reduce duplication:private long queryAdapterMemory(GpuAdapterMemoryProperty property) { if (luidPrefix.isEmpty()) return -1L; var adapterData = GpuInformation.queryGpuAdapterMemoryCounters(); List<String> instances = adapterData.getA(); List<Long> values = adapterData.getB().get(property); if (values == null) return -1L; String luidLower = luidPrefix.toLowerCase(Locale.ROOT); for (int i = 0; i < Math.min(instances.size(), values.size()); i++) { if (instances.get(i).toLowerCase(Locale.ROOT).contains(luidLower)) { return values.get(i); } } return -1L; }This is a minor improvement and can be deferred.
🤖 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/WindowsGpuStats.java` around lines 120 - 174, Both getVramUsed() and getSharedMemoryUsed() duplicate the LUID-based PDH adapter memory query logic; extract that logic into a private helper (e.g., queryAdapterMemory(GpuAdapterMemoryProperty property)) that calls GpuInformation.queryGpuAdapterMemoryCounters(), looks up instances and the property's value list from the returned map, lowercases luidPrefix for matching, iterates up to Math.min(instances.size(), values.size()), and returns the matched value or -1L; then update getVramUsed() and getSharedMemoryUsed() to call this helper (keep existing LHM fallback in getVramUsed()).oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java (2)
149-153: Minor: Unsynchronized simple methods could see stale reads in theory.Methods
getSharedMemoryUsed(),getCoreClockMhz(),getMemoryClockMhz(), andgetFanSpeedPercent()are not synchronized, though they only read the volatileclosedflag. This is safe for visibility, but ifclose()is made synchronized per the earlier suggestion, these should also be synchronized for consistent locking semantics across the class.Also applies to: 200-216
🤖 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/MacGpuStats.java` around lines 149 - 153, The simple getter methods that read the volatile closed flag (getSharedMemoryUsed, getCoreClockMhz, getMemoryClockMhz, getFanSpeedPercent and any similar getters in the 200-216 region) should be declared synchronized to match the locking semantics of a synchronized close(); update each of those method signatures to add the synchronized modifier so they acquire the same monitor as close() while still returning the same values.
67-73: Consider synchronizingclose()for consistency with@ThreadSafecontract.The
closedfield is volatile, which guarantees visibility, but there's a subtle race: a thread inside a synchronized metric method (e.g.,getGpuUtilization) that has already passedcheckOpen()may proceed to callioReportClient.sampleGpuUtilization()while another thread concurrently executesclose(). This won't cause a crash (IOReportClient returns sentinels when closed), but could return -1 instead of throwingIllegalStateExceptionas theGpuStatsinterface documents.Synchronizing
close()would establish a happens-before relationship with the metric methods.♻️ Suggested fix
`@Override` -public void close() { +public synchronized void close() { closed = true; if (ioReportClient != null) { ioReportClient.close(); } }🤖 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/MacGpuStats.java` around lines 67 - 73, The close() method can race with synchronized metric methods (like getGpuUtilization) and should be synchronized to establish a happens-before relationship with those methods; update close() to acquire the same lock used by the metric methods (e.g., make close() synchronized or wrap its body in synchronized(this)) so that setting the volatile closed flag and calling ioReportClient.close() cannot interleave with checkOpen()/ioReportClient.sampleGpuUtilization(), ensuring callers get IllegalStateException per the GpuStats contract.
🤖 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/common/AbstractGraphicsCard.java`:
- Around line 88-131: The toString() build currently opens a GpuStats session
via createStatsSession() and directly calls stats.get* methods, allowing runtime
exceptions from session creation or sampling to escape; wrap the
try-with-resources block that obtains GpuStats (createStatsSession()) and all
stats.get* calls in a try/catch that catches Throwable (or Exception) and on
failure appends a safe marker (e.g., ", metricsUnavailable" or similar) to the
builder so toString() never throws; ensure the GpuStats resource is still closed
if created and keep references to methods like createStatsSession(), GpuStats,
getVramUsed(), getSharedMemoryUsed(), getGpuUtilization(), getTemperature(),
getPowerDraw(), getCoreClockMhz(), getMemoryClockMhz(), and getFanSpeedPercent()
to locate and modify the code.
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGpuStats.java`:
- Around line 77-83: In LinuxGpuStats (the block checking drivers "i915" or
"xe"), treat a read actual frequency of 0 as 0% rather than falling through to
-1. Change the condition around FileUtil.getLongFromFile(gt0Path +
"/rps_act_freq_mhz") and rps_max_freq_mhz to allow actual == 0 (e.g., check
actual >= 0 and max > 0), and explicitly return 0.0 when actual == 0; otherwise
compute Math.min(100.0, actual * 100.0 / max). Ensure negative reads still
produce the unknown sentinel (-1d).
- Around line 212-217: The RPM/PWM checks in LinuxGpuStats treat zero as
unavailable; update the logic so zero values are valid 0% rather than returning
-1. Specifically, in the method computing fan percentage (references: class
LinuxGpuStats, variables fanRpm and fanMax and the FileUtil.getLongFromFile call
for pwm1), change the conditions to accept fanRpm == 0 when fanMax > 0 (e.g.,
use >= 0 for fanRpm with fanMax still > 0) and accept pwm == 0 as a valid
reading (e.g., use pwm >= 0) so the computations return 0.0 for stopped fans;
keep existing unavailable sentinel (-1) only when readings are negative or
fanMax is not usable. Ensure the arithmetic still guards against division by
zero (fanMax > 0).
In `@oshi-demo/src/main/java/oshi/demo/GpuStatsDemo.java`:
- Around line 78-80: The tick utilization column prints Double.NaN as "NaN%"
which is inconsistent; update the System.out.printf call in GpuStatsDemo (the
printf that uses card.getName() and tickUtil) to use a string slot for the tick
column (e.g., replace the numeric %7.1f%% specifier with a %7s specifier) and
pass tickUtil >= 0 ? String.format(Locale.ROOT, "%5.1f%%", tickUtil) : "n/a" so
unavailable values print "n/a" like the other columns.
- Around line 52-85: The bug is that the code opens and closes a GpuStats
session for each seeding/read (using card.createStatsSession() inside both the
seeding loop and the iteration loop), which discards session-scoped native state
(e.g., macOS IOReportClient power baselines); instead, create one GpuStats
session per card for the whole polling window and reuse it across ITERATIONS.
Change the logic to allocate a GpuStats[] sessions (or similar) and call
card.createStatsSession() once per card to seed prev[i] and prime power, then
inside the for (int iter = 0; iter < ITERATIONS; iter++) loop reuse sessions[i]
to call getGpuTicks(), getGpuUtilization(), getPowerDraw(), etc., updating
prev[i] each iteration, and finally close all sessions after the polling loop
(ensure try/finally to close sessions).
---
Outside diff comments:
In `@oshi-core/src/main/java/oshi/driver/mac/IOReportClient.java`:
- Around line 233-235: The inline comment in IOReportClient referencing the
energy-to-power conversion is incorrect: it says "1 µJ/ns = 1 mW" while the
calculation in the method (return energyUj * 1000.0 / dtNanos) is correct and
yields watts; update the comment near the return in the method of IOReportClient
to state the correct conversion (1 µJ/ns = 1 kW or show the unit math) so it
matches the implemented formula.
---
Nitpick comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java`:
- Around line 149-153: The simple getter methods that read the volatile closed
flag (getSharedMemoryUsed, getCoreClockMhz, getMemoryClockMhz,
getFanSpeedPercent and any similar getters in the 200-216 region) should be
declared synchronized to match the locking semantics of a synchronized close();
update each of those method signatures to add the synchronized modifier so they
acquire the same monitor as close() while still returning the same values.
- Around line 67-73: The close() method can race with synchronized metric
methods (like getGpuUtilization) and should be synchronized to establish a
happens-before relationship with those methods; update close() to acquire the
same lock used by the metric methods (e.g., make close() synchronized or wrap
its body in synchronized(this)) so that setting the volatile closed flag and
calling ioReportClient.close() cannot interleave with
checkOpen()/ioReportClient.sampleGpuUtilization(), ensuring callers get
IllegalStateException per the GpuStats contract.
In `@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java`:
- Around line 120-174: Both getVramUsed() and getSharedMemoryUsed() duplicate
the LUID-based PDH adapter memory query logic; extract that logic into a private
helper (e.g., queryAdapterMemory(GpuAdapterMemoryProperty property)) that calls
GpuInformation.queryGpuAdapterMemoryCounters(), looks up instances and the
property's value list from the returned map, lowercases luidPrefix for matching,
iterates up to Math.min(instances.size(), values.size()), and returns the
matched value or -1L; then update getVramUsed() and getSharedMemoryUsed() to
call this helper (keep existing LHM fallback in getVramUsed()).
In `@oshi-core/src/test/java/oshi/hardware/GpuStatsTest.java`:
- Around line 101-122: The testConcurrentAccessDoesNotThrow test should ensure
the ExecutorService is always shut down and that awaitTermination's result is
handled; wrap the pool.invokeAll(...) and futures processing in a try block and
call pool.shutdown() in a finally block (or call shutdownNow() if
awaitTermination(timeout) returns false) to avoid thread leaks, and preserve the
existing stats.close() and futures.get() handling so any task exceptions still
propagate; reference GpuStats/NoOpGpuStats, pool.invokeAll, pool.shutdown,
pool.awaitTermination, and stats.close when making the change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 9c77612f-dc9c-4ae2-908e-c650586b7c69
📒 Files selected for processing (9)
oshi-core/src/main/java/oshi/driver/mac/IOReportClient.javaoshi-core/src/main/java/oshi/hardware/GpuStats.javaoshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.javaoshi-core/src/test/java/oshi/hardware/GpuStatsTest.javaoshi-core/src/test/java/oshi/hardware/GraphicsCardTest.javaoshi-demo/src/main/java/oshi/demo/GpuStatsDemo.java
🚧 Files skipped from review as they are similar to previous changes (2)
- oshi-core/src/test/java/oshi/hardware/GraphicsCardTest.java
- oshi-core/src/main/java/oshi/hardware/GpuStats.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 11, macos-latest
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Analyze (java)
🔇 Additional comments (23)
oshi-core/src/test/java/oshi/hardware/GpuStatsTest.java (6)
1-28: LGTM!Proper test class setup with appropriate imports for lifecycle, assertion, and concurrency testing.
30-45: LGTM!Comprehensive lifecycle test covering initial state, all sentinel values, and close behavior.
47-53: LGTM!Good coverage of the idempotent close contract required for safe use with try-with-resources.
55-68: LGTM!Thorough coverage of post-close exception behavior for all metric methods.
70-78: LGTM!Clean test validating the AutoCloseable contract with try-with-resources.
80-99: LGTM!Good integration test that validates real card sessions with proper resource cleanup via try-with-resources.
oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java (2)
15-17: Good callout ontoString()sampling cost.The added note clearly sets expectations that Line 15 can trigger native sampling work and should be avoided in hot paths.
70-73: Default no-op session implementation looks solid.Returning a fresh
NoOpGpuStatskeeps thecreateStatsSession()contract safe (never null, closable, isolated session state).oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java (7)
35-61: Well-structured session class with clear caching semantics.The use of sentinel values for lazy caching (
null/empty forcachedNvmlDevice,Integer.MIN_VALUE/-1 forcachedAdlIndex) is well-documented and provides clean single-initialization semantics. The package-private visibility appropriately restricts instantiation toWindowsGraphicsCard.createStatsSession().
63-71: LGTM!Session lifecycle is correctly implemented. The
close()method is idempotent, and the volatileclosedfield ensures visibility across threads.
73-100: LGTM!The implementation correctly filters PDH GPU Engine counters by LUID prefix and aggregates running times per engine type. The defensive
Math.min()guard against mismatched list sizes and case-insensitive matching are good practices.
176-284: LGTM!The NVML → ADL → LHM fallback chain is consistently implemented across all sensor methods. The additional LHM sensor name fallbacks for power ("GPU Package" / "GPU Power") and fan ("GPU Fan" / "GPU Fan 1") handle vendor-specific naming variations well.
292-321: Benign race condition in lazy caching is acceptable.Both
findNvmlDevice()andfindAdlIndex()have a check-then-act pattern on volatile fields that could cause redundant computation under contention. However, since the computed values are deterministic and assignment is atomic, this is a benign race—worst case is duplicate work on first access. The design appropriately trades a small possibility of redundant initialization for simpler code without locks.
323-338: LGTM!Clean helper method that consolidates the LHM WMI query pattern. The broad exception handling with DEBUG logging is appropriate for optional sensor queries that may fail due to WMI instability or missing sensors.
102-118: No changes needed.The
getGpuUtilization()method correctly returns the LHM Load sensor value in the range 0–100, which matches theGpuStatsinterface contract specifying "utilization in the range 0.0 to 100.0". Other GPU implementations (NVML and ADL) also return percentage values in this same range. Division by 100 is not required.oshi-core/src/main/java/oshi/driver/mac/IOReportClient.java (3)
69-113: LGTM!The factory method properly handles native library loading failures, channel acquisition, subscription creation, and resource cleanup in the finally block. The nullable return pattern is well-suited for this fallible initialization.
121-144: LGTM!The sampling method correctly handles the closed state, properly releases the sample in the finally block, and computes active ticks by subtracting OFF state from total.
251-266: LGTM!The close method is idempotent, releases all held CoreFoundation references in the correct order, and properly guards against double-release via the closed flag.
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java (2)
224-265: LGTM!The
queryPerfStats()method properly manages IORegistry iteration with cleanup in finally blocks. The pattern of releasing the current service and advancing to the next in the finally block ensures resources are freed even on exceptions. The early return withCF.CFRetain(stats)correctly retains the returned dictionary before releasing the parent props.
267-278: LGTM!The name matching logic handles trademark symbols cleanly and supports both exact match and word-boundary containment matching, which is appropriate for GPU model name variations.
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGpuStats.java (1)
229-245: NVML lookup strategy and tri-state caching look solid.PCI bus ID first, card-name fallback, and negative-result caching reduce repeated lookup overhead while keeping behavior predictable.
oshi-demo/src/main/java/oshi/demo/GpuStatsDemo.java (2)
13-25: Session-based API migration is clean and consistent here.The
GpuStatsimport, updated class name, and constructor visibility all align well with the new demo intent.
47-50: Separator generation is clear and works as expected.No concerns with this block.
aa9cb81 to
7d5c614
Compare
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
oshi-core/src/test/java/oshi/hardware/GpuStatsTest.java (1)
81-97: This real-card test still passes with the fallbackNoOpGpuStats.Every assertion in this block succeeds if
createStatsSession()accidentally returns the default no-op implementation, so the test does not actually protect the new platform-specific wiring. Consider an OS-guarded assertion that Linux/macOS/Windows cards do not hand backNoOpGpuStatswhen a realGraphicsCardis enumerated.
🤖 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/GpuStats.java`:
- Around line 37-45: The API getGpuTicks() currently cannot distinguish
unsupported devices from a genuine zero-active sample; update the contract and
types so callers can detect "unavailable" by defining and documenting a sentinel
inside GpuTicks (e.g., activeTicks == -1) or by returning an explicit
Optional/nullable result; specifically add a well-documented sentinel value to
the GpuTicks type (and its javadoc) and change the GpuStats.getGpuTicks()
javadoc to state that implementations MUST return that sentinel for unsupported
sessions (or return empty/nullable if you prefer), then update any
implementations that currently fabricate a zero sample to emit the sentinel
instead so downstream consumers can show "n/a" rather than 0.0%.
In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java`:
- Around line 62-64: The LOG.warn message in MacGpuStats that runs when
IOReportClient.create() fails is misleading because getGpuUtilization() still
falls back to queryPerfStats(); update the warning to accurately reflect the
fallback path by referencing IOReportClient.create() failure and stating that
GPU ticks and power will be unavailable while utilization will fall back to
queryPerfStats() via getGpuUtilization() -> queryPerfStats(); also adjust the
similar warning path around the queryPerfStats() block so messages clearly
distinguish the two cases (IOReport creation failure vs. queryPerfStats()
fallback/outcome) and include the symbols IOReportClient.create(),
getGpuUtilization(), queryPerfStats(), and class MacGpuStats to locate the
changes.
- Around line 268-279: matchesName currently matches only marketing names
causing two MacGpuStats to bind the same IOAccelerator; instead make MacGpuStats
bind by the stable registry identifier carried from MacGraphicsCard. Change the
logic around matchesName (or the MacGpuStats constructor) to accept and compare
the MacGraphicsCard registry identifier against the IOAccelerator's registry ID
(use the accelerator's registry/property accessor rather than cardName),
performing an exact ID match first and only falling back to the existing
name-fuzzy logic if no registry ID is available; update references to
matchesName, MacGpuStats, MacGraphicsCard, and IOAccelerator accordingly.
- Around line 233-258: The loop in MacGpuStats.queryPerfStats() advances the
iterator inside the finally block which causes an extra IORegistryEntry to be
taken (and not released) on successful return; fix by (1) removing service =
iter.next() from the finally block, (2) move advancement of the iterator to the
normal loop control (e.g., at the end of the while body) so the finally only
releases the current service, (3) wrap props handling in its own try/finally to
always call props.release(), and (4) ensure that before returning the
CFMutableDictionaryRef stats you release the current service (service.release())
so no native handles are leaked; refer to the variables and methods service,
iter, props, stats and the method queryPerfStats() when making these changes.
In `@oshi-demo/src/main/java/oshi/demo/GpuStatsDemo.java`:
- Around line 57-60: The seeding loop only primes power but not utilization, so
call getGpuUtilization() when creating each session: inside the loop that
iterates over cards and uses cards.get(i).createStatsSession(), after prev[i] =
sessions[i].getGpuTicks() and the existing sessions[i].getPowerDraw() call, also
invoke sessions[i].getGpuUtilization() to establish the utilization baseline for
the sessions array (so API Util% is valid on the first iteration).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 89d42456-e953-42f0-9c00-de899ac98e51
📒 Files selected for processing (9)
oshi-core/src/main/java/oshi/driver/mac/IOReportClient.javaoshi-core/src/main/java/oshi/hardware/GpuStats.javaoshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.javaoshi-core/src/test/java/oshi/hardware/GpuStatsTest.javaoshi-core/src/test/java/oshi/hardware/GraphicsCardTest.javaoshi-demo/src/main/java/oshi/demo/GpuStatsDemo.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). (4)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Analyze (java)
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@CHANGELOG.md`:
- Line 7: The CHANGELOG entry lists PR `#3092` with a trailing comma and no
description; update the CHANGELOG.md by either adding a clear description for PR
`#3092` (what it changes or fixes) or, if `#3092` is intentionally part of the same
change set as PR `#3095`, combine the two entries into one descriptive line
referencing both PR numbers (e.g., "PRs `#3092/`#3095: <description>"). Ensure the
final line removes the stray trailing comma and includes concise, meaningful
text for the PR reference(s).
- Line 8: Update the changelog entry to reflect the API refactor instead of a
simple addition: change the description that currently reads "Add GPU metrics to
GraphicsCard" to note that nine dynamic metric methods were removed from
GraphicsCard and replaced by a session-based GpuStats API (AutoCloseable)
accessed via createStatsSession(), which moves from per-call metric methods to a
lifecycle-managed stats session pattern; mention that this is an API-breaking
refactor so users must migrate to the new createStatsSession()/GpuStats usage.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 77bd1265-280e-490a-982d-60ca5f1759b3
📒 Files selected for processing (5)
CHANGELOG.mdoshi-core/src/main/java/oshi/hardware/GpuStats.javaoshi-core/src/main/java/oshi/hardware/GraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.javaoshi-demo/src/main/java/oshi/demo/PollGpuStats.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 25, windows-latest
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: Test JDK 25, macos-latest
- GitHub Check: Analyze (java)
🔇 Additional comments (14)
oshi-core/src/main/java/oshi/hardware/GpuStats.java (3)
1-80: Well-designed session API with comprehensive documentation.The interface is well-structured with clear lifecycle semantics, sentinel value documentation, and usage examples. The
@ThreadSafeannotation andAutoCloseableextension appropriately convey the intended usage pattern.
111-114: Sentinel value for unavailable tick data remains ambiguous.The documentation clarifies that
getActiveTicks()returns 0 when tick-level metrics are unavailable, but this still conflates "unsupported platform" with "GPU genuinely idle." Callers computing utilization will display 0% instead of "n/a" for unsupported platforms.
142-213: Consistent sentinel semantics for scalar metrics.The -1 sentinel value is appropriate for metrics like VRAM, temperature, power, and clock speeds where -1 cannot be a valid measurement. The documentation is clear and consistent across all methods.
oshi-demo/src/main/java/oshi/demo/PollGpuStats.java (3)
53-63: Session priming is now complete.The seeding loop correctly primes both power and utilization baselines, addressing the prior concern about
getGpuUtilization()returning "n/a" on the first iteration for macOS.
96-102: Proper resource cleanup in finally block.The finally block correctly handles partial initialization scenarios by checking for null before closing each session. This ensures no resource leaks even if an exception occurs during session creation.
105-116: formatBytes helper handles sentinel values correctly.The helper appropriately returns "n/a" for negative values (the -1 sentinel) and uses standard binary prefixes for memory formatting.
oshi-core/src/main/java/oshi/hardware/GraphicsCard.java (2)
9-29: Clear documentation for the session-based API migration.The Javadoc clearly explains the distinction between static identity fields and dynamic metrics accessed via sessions. The try-with-resources example and reference to
GpuStatsfor polling patterns guide users appropriately.
70-80: Robust factory method contract.The "never returns null and never throws" guarantee simplifies client code. The fallback to a no-op instance for unsupported platforms aligns with the PR's design intent for AIX, FreeBSD, OpenBSD, and Solaris.
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java (6)
58-66: Constructor with improved warning message.The warning message at lines 63-64 now correctly states that utilization will fall back to IOAccelerator PerformanceStatistics, addressing the prior concern about misleading logs.
68-79: Correct lifecycle management.The synchronized
close()with volatileclosedflag ensures proper visibility. ThecheckOpen()guard at the start of each metric method enforces the contract.
225-268: Iterator handling is now correct.The
queryPerfStats()method properly manages native resources: iterator advancement (line 260) is outside thefinallyblock, andprops.release()is wrapped in its owntry-finally(lines 250-252). This addresses the prior iterator leak concern.
270-281: Name-based matching may bind multiple sessions to the same accelerator.On systems with identical GPUs (e.g., dual AMD Radeon Pro 5700), both
MacGpuStatsinstances will match the firstIOAcceleratorservice with that model name, reporting duplicate metrics. A stable registry identifier fromMacGraphicsCardshould be used instead of fuzzy name matching.
103-119: CFStringRef lifecycle is managed correctly.Each
CFStringRefkey is released immediately after use, and theperfStatsdictionary is released in thefinallyblock. While wrapping each key in its owntry-finallywould be more defensive, the current pattern is correct and consistent with OSHI's existing style.
156-190: Temperature retrieval with proper fallback chain.The SMC connection is correctly closed in a
finallyblock (line 168), and the fallback toPerformanceStatisticsprovides coverage for non-Apple-Silicon Macs. Both resource handles are managed correctly.
There was a problem hiding this comment.
Actionable comments posted: 4
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)
171-181:⚠️ Potential issue | 🟡 MinorReset per-card fields at each new
*-displayblock.At Line 171, only
busInfois reset. If a later display block omitsproduct,vendor, orresources, prior-card values can leak into the new card record.Suggested fix
if (split[0].startsWith("*-display")) { // Save previous card if (cardNum++ > 0) { Triplet<String, String, String> drmInfo = findDrmInfo(busInfo); cardList.add(new LinuxGraphicsCard(name, deviceId, vendor, versionInfoList.isEmpty() ? Constants.UNKNOWN : String.join(", ", versionInfoList), vram, drmInfo.getA(), drmInfo.getB(), drmInfo.getC())); - versionInfoList.clear(); } + name = Constants.UNKNOWN; + deviceId = Constants.UNKNOWN; + vendor = Constants.UNKNOWN; + versionInfoList.clear(); + vram = 0L; busInfo = null;🤖 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 171 - 181, When starting a new *-display block in LinuxGraphicsCard parsing, reset all per-card state so prior values don't leak; in the branch handling split[0].startsWith("*-display") set name = null, deviceId = null, vendor = null, vram = null (and clear versionInfoList) in addition to busInfo = null so subsequent cards don't inherit product/vendor/resources from the previous card when those lines are omitted.
♻️ Duplicate comments (1)
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java (1)
279-290:⚠️ Potential issue | 🟠 MajorStop using fuzzy name matching as the primary accelerator lookup.
If two GPUs share the same marketing name,
matchesName()can bind bothMacGpuStatsinstances to the sameIOAcceleratorservice and duplicate stats. Please plumb a stable registry identifier fromMacGraphicsCardand exact-match that first, using the name fallback only when no stable ID is available.🤖 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/MacGpuStats.java` around lines 279 - 290, matchesName currently uses fuzzy name matching to bind MacGpuStats to IOAccelerator, causing duplicate bindings when GPUs share marketing names; instead, first attempt an exact match using a stable registry identifier exposed by MacGraphicsCard (e.g., a new or existing stableId/getRegistryId on MacGraphicsCard) inside the MacGpuStats binding logic (in methods that call matchesName or perform IOAccelerator lookup), only falling back to the existing matchesName name-based check when the stable ID is null/empty or no exact match is found; update MacGpuStats to prefer exact registry ID equality against the IOAccelerator property (and avoid binding if an exact-ID match is already claimed) and keep the current trademark-normalized name matching as the secondary fallback to preserve behavior when no stable ID exists.
🧹 Nitpick comments (2)
oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java (1)
116-118: Prefer try-with-resources intestCreateStatsSessionNeverNull.Using try-with-resources here keeps the test aligned with the API lifecycle contract and avoids future leaks if the stub changes.
Suggested tweak
`@Test` void testCreateStatsSessionNeverNull() { - assertThat(new StubGraphicsCard(-1d, -1d, -1L, -1L, -1d).createStatsSession(), is(notNullValue())); + try (GpuStats stats = new StubGraphicsCard(-1d, -1d, -1L, -1L, -1d).createStatsSession()) { + assertThat(stats, is(notNullValue())); + } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java` around lines 116 - 118, Replace the direct call to createStatsSession() in testCreateStatsSessionNeverNull with a try-with-resources block that calls new StubGraphicsCard(...).createStatsSession() and asserts the session is not null inside the block; this ensures the returned session (from StubGraphicsCard.createStatsSession()) is automatically closed and follows the API lifecycle contract to prevent leaks if the stub implementation changes.oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java (1)
150-179: Avoid duplicate PDH adapter-memory queries in the same poll cycle.
getVramUsed()andgetSharedMemoryUsed()each callqueryGpuAdapterMemoryCounters()independently. Pollers that read both metrics back-to-back pay two native queries per cycle.Also applies to: 298-316
🤖 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/WindowsGpuStats.java` around lines 150 - 179, Both getVramUsed() and getSharedMemoryUsed() independently call the native PDH adapter-memory query causing duplicate native work; change to a single cached PDH result per poll cycle: add a small cached-structure field (e.g., lastAdapterMemoryQueryResult with a poll identifier or timestamp and both DEDICATED_USAGE and SHARED_USAGE values) and update queryAdapterMemory()/queryGpuAdapterMemoryCounters() usage so the first call in a cycle performs the native query and populates the cache, and subsequent calls to getVramUsed() and getSharedMemoryUsed() return values from the cache; ensure cache invalidation when checkOpen() or the poll cycle changes and keep LhmSensor fallback logic in getVramUsed() unchanged if PDH returns <0.
🤖 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/common/AbstractGraphicsCard.java`:
- Around line 82-84: Update the Javadoc in AbstractGraphicsCard to narrow the
blanket statement that delta-based metrics always return -1 on first call:
clarify that interval-based backends (the ones that compute deltas across polls)
may return -1 on their first invocation for GpuStats#getGpuUtilization() and
GpuStats#getPowerDraw(), but note that some backends (e.g., Linux sysfs paths
and the macOS queryPerfStats() fallback) can provide a valid value on the
initial poll; keep the recommendation to use a persistent GpuStats session with
a polling loop for reliable delta values.
In `@oshi-core/src/main/java/oshi/hardware/common/NoOpGpuStats.java`:
- Around line 14-15: Update the Javadoc on class NoOpGpuStats to accurately
describe the sentinel behavior: state that while the session is open most
primitive getters return -1, the getGpuTicks() method returns a pair (0, 0) as
its sentinel, and after close() all getters throw an exception (i.e., the
session is closed and methods are no-op/illegal). Mention that close() is
idempotent and clarify which methods return -1 vs (0,0) vs throwing, referencing
the class name NoOpGpuStats and the methods getGpuTicks() and close() so readers
can find the implementation.
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGpuStats.java`:
- Around line 93-102: getVramUsed() currently returns -1 for NVIDIA because it
skips the NVML path; modify getVramUsed() to first call findNvmlDevice() / check
nvmlDevice (same approach used by temperature/power/clocks/fan getters) and
return NVML-retrieved VRAM when available, and only if no NVML device is present
fall back to the existing AMDGPU path that reads
FileUtil.getLongFromFile(drmDevicePath + "/mem_info_vram_used") (keep
checkOpen(), synchronized, and the drmDevicePath/driverName checks intact).
In `@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java`:
- Around line 327-333: When pciBusId is empty and you fall back to
NvmlUtil.findDeviceByName(cardName), update the logic to detect ambiguous
matches: use or add an NvmlUtil method that returns all matching device handles
(or exposes acquireHandleByName results), check if multiple handles match
cardName, and if so emit a warning via the existing logger and either fail the
fallback (leave id null) or choose a deterministic behavior; then set
cachedNvmlDevice based on the resolved/unambiguous id. Ensure references:
pciBusId, cardName, NvmlUtil.findDevice/findDeviceByName, acquireHandleByName,
and cachedNvmlDevice are updated so ambiguity is detected and logged instead of
silently binding the first match.
---
Outside diff comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java`:
- Around line 171-181: When starting a new *-display block in LinuxGraphicsCard
parsing, reset all per-card state so prior values don't leak; in the branch
handling split[0].startsWith("*-display") set name = null, deviceId = null,
vendor = null, vram = null (and clear versionInfoList) in addition to busInfo =
null so subsequent cards don't inherit product/vendor/resources from the
previous card when those lines are omitted.
---
Duplicate comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java`:
- Around line 279-290: matchesName currently uses fuzzy name matching to bind
MacGpuStats to IOAccelerator, causing duplicate bindings when GPUs share
marketing names; instead, first attempt an exact match using a stable registry
identifier exposed by MacGraphicsCard (e.g., a new or existing
stableId/getRegistryId on MacGraphicsCard) inside the MacGpuStats binding logic
(in methods that call matchesName or perform IOAccelerator lookup), only falling
back to the existing matchesName name-based check when the stable ID is
null/empty or no exact match is found; update MacGpuStats to prefer exact
registry ID equality against the IOAccelerator property (and avoid binding if an
exact-ID match is already claimed) and keep the current trademark-normalized
name matching as the secondary fallback to preserve behavior when no stable ID
exists.
---
Nitpick comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java`:
- Around line 150-179: Both getVramUsed() and getSharedMemoryUsed()
independently call the native PDH adapter-memory query causing duplicate native
work; change to a single cached PDH result per poll cycle: add a small
cached-structure field (e.g., lastAdapterMemoryQueryResult with a poll
identifier or timestamp and both DEDICATED_USAGE and SHARED_USAGE values) and
update queryAdapterMemory()/queryGpuAdapterMemoryCounters() usage so the first
call in a cycle performs the native query and populates the cache, and
subsequent calls to getVramUsed() and getSharedMemoryUsed() return values from
the cache; ensure cache invalidation when checkOpen() or the poll cycle changes
and keep LhmSensor fallback logic in getVramUsed() unchanged if PDH returns <0.
In `@oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java`:
- Around line 116-118: Replace the direct call to createStatsSession() in
testCreateStatsSessionNeverNull with a try-with-resources block that calls new
StubGraphicsCard(...).createStatsSession() and asserts the session is not null
inside the block; this ensures the returned session (from
StubGraphicsCard.createStatsSession()) is automatically closed and follows the
API lifecycle contract to prevent leaks if the stub implementation changes.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 48b87f21-bc50-43f3-9bf0-7ad45851ba78
📒 Files selected for processing (19)
oshi-core/src/main/java/oshi/driver/mac/IOReportClient.javaoshi-core/src/main/java/oshi/driver/windows/perfmon/GpuInformation.javaoshi-core/src/main/java/oshi/hardware/GpuStats.javaoshi-core/src/main/java/oshi/hardware/GpuTicks.javaoshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/common/DefaultGpuTicks.javaoshi-core/src/main/java/oshi/hardware/common/NoOpGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.javaoshi-core/src/main/java/oshi/jna/common/Nvml.javaoshi-core/src/test/java/oshi/driver/mac/IOReportClientTest.javaoshi-core/src/test/java/oshi/hardware/GpuStatsTest.javaoshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.javaoshi-demo/src/main/java/oshi/demo/PollGpuStats.java
💤 Files with no reviewable changes (1)
- oshi-core/src/main/java/oshi/hardware/common/DefaultGpuTicks.java
🚧 Files skipped from review as they are similar to previous changes (5)
- oshi-core/src/main/java/oshi/hardware/GpuStats.java
- oshi-core/src/test/java/oshi/driver/mac/IOReportClientTest.java
- oshi-demo/src/main/java/oshi/demo/PollGpuStats.java
- oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
- oshi-core/src/test/java/oshi/hardware/GpuStatsTest.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 25, windows-latest
- GitHub Check: Test JDK 11, 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 (9)
oshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdGraphicsCard.java (2)
2-2: Header metadata update looks correct.The copyright year range update is accurate and non-functional.
44-44: Javadoc link correction is good.The updated
@returnreference now points to the correct OpenBSD class path.oshi-core/src/main/java/oshi/hardware/GpuTicks.java (1)
29-62: Nice simplification of the tick model.Explicit active/idle counters make the delta-based session API much easier to reason about.
oshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.java (1)
101-151: Good hardening around dynamic sampling.Catching sampling failures and closing the session in
finallykeepstoString()safe for logging/debug paths.oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (1)
60-63:createStatsSession()wiring looks good.This cleanly moves Linux dynamic metrics behind a session boundary and keeps
LinuxGraphicsCardfocused on discovery metadata.oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java (1)
184-201: Great sentinel contract coverage for default no-op sessions.This test validates all session metrics and tick semantics in one place, which is exactly the lifecycle regression guard needed for the new API.
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (2)
124-127: Session factory integration is clean.
WindowsGraphicsCardnow correctly delegates runtime metrics toWindowsGpuStatswhile preserving static adapter discovery responsibilities.
331-336: Good defensive ordering around DXGI match consumption.Removing
dxgiMatchonly after successful card construction avoids accidental loss of candidates on intermediate failures.oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java (1)
80-129: Lifecycle guard + tick derivation implementation looks solid.The synchronized session methods with
checkOpen()and active/idle tick construction are consistent with the session-based contract.
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Actionable comments posted: 5
♻️ Duplicate comments (2)
CHANGELOG.md (1)
7-8:⚠️ Potential issue | 🟠 MajorDescribe this as a breaking GPU stats refactor, not a new feature.
#3092is still dangling without a description, and#3095still reads like a simple addition. This PR removes the old dynamicGraphicsCardmetric getters and replaces them withcreateStatsSession()/GpuStats, so the changelog should combine these PRs into one migration-oriented entry.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@CHANGELOG.md` around lines 7 - 8, The changelog entry incorrectly presents `#3092` and `#3095` as a simple feature add; update the entry to describe this as a breaking GPU stats refactor that replaces the old dynamic GraphicsCard metric getters with the new createStatsSession()/GpuStats API, combine the two PRs into a single migration-oriented note, remove the dangling/empty `#3092` description, and add a short migration hint for callers to switch from GraphicsCard getters to creating a GpuStats session via createStatsSession().oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java (1)
66-69:⚠️ Potential issue | 🟠 MajorMatch the
IOAcceleratorby stable registry identity, not model name.
matchesName()still selects the first accelerator whose normalized marketing name matchescardName. On machines with two identical GPUs, multipleMacGpuStatsinstances can bind the same service and return duplicated stats. Please pass a registry identifier fromMacGraphicsCardand use exact ID matching before falling back to name matching.Also applies to: 249-250, 279-289
🤖 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/MacGpuStats.java` around lines 66 - 69, Constructor MacGpuStats currently only stores cardName and uses matchesName() to bind IOAccelerator, which leads to duplicate binding when two identical GPUs exist; change MacGpuStats to accept and store a stable registry identifier (pass it from MacGraphicsCard), then update the accelerator-selection logic to first compare the accelerator's registry ID for an exact match against this stored ID and only if none match fall back to the existing name-based matchesName() check; update any callers that construct MacGpuStats (e.g., where MacGraphicsCard creates MacGpuStats) to supply the registry identifier so each MacGpuStats binds by unique ID instead of model name.
🧹 Nitpick comments (3)
oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java (1)
321-329: Short-circuit when there are zero name matches.If
matchCount == 0, Line 328 re-scans all devices viaacquireHandleByNameunnecessarily. Early return avoids duplicate NVML calls.♻️ Proposed refactor
int matchCount = countMatchesByName(gpuName); if (matchCount > 1) { LOG.warn("NVML name match for '{}' is ambiguous ({} devices match); use PCI bus ID for reliable" + " device identification", gpuName, matchCount); return null; } + if (matchCount == 0) { + return null; + } // Acquire a handle by name to confirm the device exists, then extract its bus ID. Pointer handle = acquireHandleByName(gpuName);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java` around lines 321 - 329, The code currently checks for matchCount > 1 but still calls acquireHandleByName(gpuName) when matchCount == 0, causing an unnecessary NVML scan; update the logic in the block that uses countMatchesByName(gpuName) so that if matchCount == 0 it returns null immediately (before calling acquireHandleByName), and keep the existing warning/return behavior for matchCount > 1 to avoid redundant NVML calls and only call acquireHandleByName when exactly one match is found.oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java (1)
132-146: Use PDH tick deltas as the fallback utilization source.Returning
-1whenever LibreHardwareMonitor isn't present leavesgetGpuUtilization()unavailable on stock Windows installs even thoughgetGpuTicks()already exposes cumulative PDH counters for the same adapter. Keeping a previousGpuTickssnapshot here would let the high-level API work without forcing callers to reimplement the delta math.🤖 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/WindowsGpuStats.java` around lines 132 - 146, The getGpuUtilization() method in WindowsGpuStats should use PDH tick deltas as a fallback instead of returning -1: when LHM sensor lookup fails or lhmParent is empty, call the existing getGpuTicks() to obtain the current cumulative GpuTicks, compare it to a stored previous snapshot (add a private field like prevGpuTicks) and compute the utilization as the delta busy ticks divided by the delta total ticks (guarding against zero-delta) to produce a percentage; update the prevGpuTicks with the current snapshot after computing the delta; keep the method synchronized to maintain thread safety and only return -1 if no prior snapshot exists or ticks cannot be read.oshi-core/src/test/java/oshi/driver/mac/IOReportClientTest.java (1)
23-30: Tighten this no-op create test.
testCreateReturnsNullOrNonNull()passes regardless of whatIOReportClient.create()does, so it won't catch regressions in availability handling or cleanup. I'd either fold it into another test or assert something observable about the non-null path.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@oshi-core/src/test/java/oshi/driver/mac/IOReportClientTest.java` around lines 23 - 30, The test testCreateReturnsNullOrNonNull() is a no-op and won't catch regressions; change it so that when IOReportClient.create() returns non-null you exercise an observable behavior and verify cleanup: call IOReportClient.create(), assert that the result is either null OR (if non-null) perform a lightweight usable operation on the client (e.g., a simple probe or API call appropriate for IOReportClient) and then call client.close() and assert the cleanup completed (no exception and/or a closed/invalid state if such a getter exists); alternatively fold this null-or-non-null check into an existing test that already asserts behavior on non-null IOReportClient.
🤖 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/common/AbstractGraphicsCard.java`:
- Around line 150-152: In AbstractGraphicsCard.toString(), the call to
stats.close() can throw and break the no-throw contract of toString; wrap the
stats.close() invocation in a try/catch (catch Exception or Throwable as
appropriate) and suppress or log the exception so cleanup remains best-effort
and the toString method never propagates an exception from stats.close().
In `@oshi-core/src/main/java/oshi/hardware/GpuStats.java`:
- Around line 24-30: The class Javadoc for GpuStats currently promises that
getGpuUtilization() and getPowerDraw() always return -1 on the first call;
update the wording to state that priming/delta-based behavior is
implementation-dependent (some implementations may return an immediate reading
on first call while others record a baseline and return -1), and adjust the same
wording in the other affected Javadoc blocks (the sections covering the one-shot
vs. polling explanation and the detailed method docs for getGpuUtilization() and
getPowerDraw()) so the public contract matches actual implementations.
In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java`:
- Around line 138-161: The code reads Apple Silicon "In use system memory"
inside getVramUsed() but leaves getSharedMemoryUsed() returning -1; move the
unified-memory read into getSharedMemoryUsed() by duplicating the perfStats
access pattern used in getVramUsed() (checkOpen(), perfStats = …, create
CFStringRef key, perfStats.getValue(key), CFNumberRef(result).longValue(),
release in finally) but use the shared-memory keys rather than VRAM keys (mirror
the primary/fallback logic you used with VRAM_USED_KEY_AS/VRAM_USED_KEY with the
appropriate shared-memory constants), and remove/stop returning system-memory
from getVramUsed() so getSharedMemoryUsed() returns the Apple Silicon unified
memory value or -1 if absent.
In `@oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java`:
- Around line 225-229: The NVML device-count failure is being collapsed into "0"
in countMatchesByName, which hides errors and lets findDeviceByName treat an
error as a valid non-ambiguous result; change countMatchesByName (and symmetric
logic near findDeviceByName) to surface errors instead of returning 0: when
Holder.LIB.nvmlDeviceGetCount_v2(countRef) != Nvml.NVML_SUCCESS return a
distinct error signal (e.g., throw an NvmlException or return a negative
sentinel) and update findDeviceByName to detect that error signal from
countMatchesByName and handle it as a failure (propagate/abort) rather than
proceeding to select a first match; reference the methods countMatchesByName,
findDeviceByName, and the call to Holder.LIB.nvmlDeviceGetCount_v2 when making
these changes.
In `@oshi-demo/src/main/java/oshi/demo/PollGpuStats.java`:
- Around line 96-101: The finally block in PollGpuStats iterates sessions and
calls s.close() but a thrown exception will abort the loop, preventing remaining
GpuStats from being closed; wrap each s.close() call in its own try/catch (catch
Throwable/Exception) inside the for (GpuStats s : sessions) loop, and log or
suppress the exception so cleanup is best-effort for all sessions while still
attempting to close every GpuStats instance.
---
Duplicate comments:
In `@CHANGELOG.md`:
- Around line 7-8: The changelog entry incorrectly presents `#3092` and `#3095` as a
simple feature add; update the entry to describe this as a breaking GPU stats
refactor that replaces the old dynamic GraphicsCard metric getters with the new
createStatsSession()/GpuStats API, combine the two PRs into a single
migration-oriented note, remove the dangling/empty `#3092` description, and add a
short migration hint for callers to switch from GraphicsCard getters to creating
a GpuStats session via createStatsSession().
In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.java`:
- Around line 66-69: Constructor MacGpuStats currently only stores cardName and
uses matchesName() to bind IOAccelerator, which leads to duplicate binding when
two identical GPUs exist; change MacGpuStats to accept and store a stable
registry identifier (pass it from MacGraphicsCard), then update the
accelerator-selection logic to first compare the accelerator's registry ID for
an exact match against this stored ID and only if none match fall back to the
existing name-based matchesName() check; update any callers that construct
MacGpuStats (e.g., where MacGraphicsCard creates MacGpuStats) to supply the
registry identifier so each MacGpuStats binds by unique ID instead of model
name.
---
Nitpick comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.java`:
- Around line 132-146: The getGpuUtilization() method in WindowsGpuStats should
use PDH tick deltas as a fallback instead of returning -1: when LHM sensor
lookup fails or lhmParent is empty, call the existing getGpuTicks() to obtain
the current cumulative GpuTicks, compare it to a stored previous snapshot (add a
private field like prevGpuTicks) and compute the utilization as the delta busy
ticks divided by the delta total ticks (guarding against zero-delta) to produce
a percentage; update the prevGpuTicks with the current snapshot after computing
the delta; keep the method synchronized to maintain thread safety and only
return -1 if no prior snapshot exists or ticks cannot be read.
In `@oshi-core/src/main/java/oshi/util/gpu/NvmlUtil.java`:
- Around line 321-329: The code currently checks for matchCount > 1 but still
calls acquireHandleByName(gpuName) when matchCount == 0, causing an unnecessary
NVML scan; update the logic in the block that uses countMatchesByName(gpuName)
so that if matchCount == 0 it returns null immediately (before calling
acquireHandleByName), and keep the existing warning/return behavior for
matchCount > 1 to avoid redundant NVML calls and only call acquireHandleByName
when exactly one match is found.
In `@oshi-core/src/test/java/oshi/driver/mac/IOReportClientTest.java`:
- Around line 23-30: The test testCreateReturnsNullOrNonNull() is a no-op and
won't catch regressions; change it so that when IOReportClient.create() returns
non-null you exercise an observable behavior and verify cleanup: call
IOReportClient.create(), assert that the result is either null OR (if non-null)
perform a lightweight usable operation on the client (e.g., a simple probe or
API call appropriate for IOReportClient) and then call client.close() and assert
the cleanup completed (no exception and/or a closed/invalid state if such a
getter exists); alternatively fold this null-or-non-null check into an existing
test that already asserts behavior on non-null IOReportClient.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: cdc52272-5cfa-409c-afc9-38789ab6ccee
📒 Files selected for processing (25)
CHANGELOG.mdoshi-core/src/main/java/oshi/driver/mac/IOReportClient.javaoshi-core/src/main/java/oshi/driver/windows/perfmon/GpuInformation.javaoshi-core/src/main/java/oshi/hardware/GpuStats.javaoshi-core/src/main/java/oshi/hardware/GpuTicks.javaoshi-core/src/main/java/oshi/hardware/GraphicsCard.javaoshi-core/src/main/java/oshi/hardware/common/AbstractGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/common/DefaultGpuTicks.javaoshi-core/src/main/java/oshi/hardware/common/NoOpGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/unix/openbsd/OpenBsdGraphicsCard.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.javaoshi-core/src/main/java/oshi/jna/common/Nvml.javaoshi-core/src/main/java/oshi/util/gpu/NvmlUtil.javaoshi-core/src/test/java/oshi/driver/mac/IOReportClientTest.javaoshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.javaoshi-core/src/test/java/oshi/hardware/GpuStatsTest.javaoshi-core/src/test/java/oshi/hardware/GraphicsCardTest.javaoshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.javaoshi-demo/src/main/java/oshi/demo/GpuStats.javaoshi-demo/src/main/java/oshi/demo/PollGpuStats.java
💤 Files with no reviewable changes (3)
- oshi-core/src/main/java/oshi/hardware/common/DefaultGpuTicks.java
- oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java
- oshi-demo/src/main/java/oshi/demo/GpuStats.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/platform/unix/openbsd/OpenBsdGraphicsCard.java (2)
2-2: Header metadata update looks correct.Line 2 updates the copyright range consistently with the current project timeline.
44-44: Javadoc type link correction is accurate.Line 44 now points to the OpenBSD package path, which improves API doc navigation and avoids cross-package confusion.
oshi-core/src/main/java/oshi/jna/common/Nvml.java (1)
58-62: Field order fix is correct for NVML struct mapping.Line 58–Line 62 now align JNA layout with NVML memory struct ordering (
total,free,used), so downstream reads likemem.usedremain semantically correct.oshi-core/src/main/java/oshi/driver/windows/perfmon/GpuInformation.java (1)
33-35: LGTM!The addition of
RUNNING_TIME_BASEis essential for the newWindowsGpuStats.getGpuTicks()implementation, which uses it to compute idle time astotalBase - totalActive. The PDH counter name"Running Time_Base"correctly follows the Windows naming convention for base counters, and the inline comment clearly documents its purpose.oshi-core/src/test/java/oshi/hardware/GraphicsCardTest.java (1)
34-36: Good lifecycle handling for stats sessions.This correctly closes each
GpuStatssession and avoids resource leakage in test runs.oshi-core/src/test/java/oshi/hardware/GpuStatsTest.java (1)
30-175: Strong lifecycle and contract coverage.The test matrix is solid: open/close semantics, post-close guards, real-card integration path, and concurrent access behavior are all exercised.
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java (1)
41-44: Session wiring and terminal-card guard look correct.
createStatsSession()is correctly delegated toMacGpuStats, and the final add guard avoids emitting a phantom card when parsing finds none.Also applies to: 83-87
oshi-core/src/main/java/oshi/hardware/common/NoOpGpuStats.java (1)
13-95: No-op session contract is implemented cleanly.Closed-state enforcement, sentinel semantics, and idempotent close are consistent with the API expectations.
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxGraphicsCard.java (1)
60-63: Nice hardening of Linux discovery + session creation.The new null/guard checks and parsing fixes improve resilience, and
createStatsSession()cleanly hooks dynamic sampling intoLinuxGpuStats.Also applies to: 95-111, 128-140, 170-209
oshi-core/src/test/java/oshi/hardware/common/AbstractGraphicsCardTest.java (1)
37-112: Good migration of unit tests to the session model.The stubbed
GpuStatspath and the NoOp sentinel assertions validate the new default/session behavior well.Also applies to: 116-120, 186-203
oshi-core/src/main/java/oshi/hardware/GraphicsCard.java (2)
10-30: Javadoc migration to session-based metrics is clear and actionable.The updated docs cleanly distinguish static identity fields from dynamic stats and provide a good try-with-resources usage pattern.
71-80:createStatsSession()contract is well-defined.The method-level contract is explicit about lifecycle ownership and fallback behavior, which improves API usability across platforms.
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGraphicsCard.java (3)
33-33: Import update matches the new API shape.
GpuStatsimport is correctly introduced for the session-based override.
124-127: Session creation wiring looks correct.
createStatsSession()cleanly delegates toWindowsGpuStatswith the adapter correlation fields needed for downstream metric providers.
321-336: Good defensive ordering for DXGI match consumption.Delaying
remainingDxgi.remove(dxgiMatch)until after successful card construction avoids prematurely losing a match if earlier steps fail.
Replaces the per-call dynamic GPU metric methods on
GraphicsCardwith a session-basedGpuStatsAPI that allows callers to open a sampling session, poll metrics over time, and close it explicitly via try-with-resources.Changes
Session API (
GpuStats Session API)GpuStatsinterface extendingAutoCloseablewith methods for GPU ticks, utilization, VRAM, temperature, power draw, clock speeds, and fan speedNoOpGpuStatsas the default no-op implementation returning sentinel valuescreateStatsSession()toGraphicsCardinterface andAbstractGraphicsCarddefaultPlatform implementations (
Implement Platform-Specific Sessions)IOReportClient(macOS) — instance-based IOReport subscription sampling GPU ticks, utilization, and power via theGPUPH/Energy Model channelsMacGpuStats,WindowsGpuStats,LinuxGpuStats— migrate all dynamic metric logic from the respectiveGraphicsCardimplementations into dedicated session classescreateStatsSession()intoMacGraphicsCard,WindowsGraphicsCard, andLinuxGraphicsCardAPI migration / cleanup (
Complete API Migration)GraphicsCardinterface and all platform implementationsIOReportDriver(superseded byIOReportClient)AbstractGraphicsCard.toString()to open a session via try-with-resourcesGraphicsCardTest, addGpuStatsTestandIOReportClientTest, rewriteAbstractGraphicsCardTestGpuStatsDemoto avoid name conflict withoshi.hardware.GpuStatsDesign notes
NoOpGpuStatsdefault — no changes neededIOReportClientuses dedicated IOReport accessor functions (IOReportChannelGetGroup,IOReportStateGetResidency, etc.) rather than raw channel parsingGPUPHchannel in the"GPU Performance States"subgroupenergyUj * 1000.0 / dtNanos= wattsSummary by CodeRabbit
New Features
Bug Fixes
Public API
Tests