Repository navigation
Dedup NvmlUtil JNA/FFM twins behind a shared query skeleton - #3542
Conversation
Every NVML metric had the same shape in both bindings: reject a blank device id, pair nvmlInit_v2 with nvmlShutdown, acquire a fresh handle inside that scope, and fall back to a sentinel when any step fails. Only the native read differed, so the skeleton now lives in oshi-common and each backend supplies a one-line reader. New in oshi.util.common.gpu: - NvmlQuery holds the query skeleton behind an NvmlScope<H> interface each twin implements once, plus the shared identifier matching. The FFM scope opens and closes its Arena inside withDevice, so no MemorySegment escapes the exported package. - NvmlDeviceCache holds the enumerate-once-on-success bus ID cache, previously three statics duplicated per twin. Enumeration is retried until it succeeds so a transient NVML failure is not cached as "no devices", which is why the enumerator distinguishes null from empty. The twins keep only their native readers, and their internal device walks collapse behind forEachDevice/readBusIds/readName. NvmlUtilJNA 558 -> 493, NvmlUtilFFM 472 -> 440. Behavior changes, all deliberate: - findDeviceByName returned a different string per backend for the same device: JNA read pci.busId (32-byte, 8-hex-digit domain) while FFM read busIdLegacy (16-byte, 4-digit). Both bindings declare both fields identically, so this was a real divergence, masked downstream because acquireHandleByBusId matches by substring either way. Both now prefer the modern form and fall back to legacy, matching the order enumerateDeviceBusIds records them in. - NvmlQuery.matches rejects an empty candidate. Bidirectional containment previously let a device whose PCI bus ID or name read back blank match every query, since every string contains the empty string. Pre-existing in both twins. - The JNA enumeration debug log gains a backend tag, matching the format FFM already used. - findDeviceByName no longer calls ensureDevicesEnumerated. It was a no-op on that path; the enumerated set is only read by findDevice, which warms it itself. No CHANGELOG: deviceId is internal plumbing between the GpuStats base and NvmlUtil, never surfaced in the public GraphicsCard/GpuStats API. New portable NvmlQueryTest covers the lifecycle pairing including the exception path, every sentinel path, identifier matching, and the cache's retry-vs-cache semantics, with no NVML library present.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📜 Recent review details⏰ Context from checks skipped due to timeout. (7)
📝 WalkthroughWalkthroughNVML lifecycle, device caching, PCI matching, and metric access are centralized in ChangesNVML query refactor
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant NvmlUtilJNA
participant NvmlQuery
participant NVML
Client->>NvmlUtilJNA: request device metric
NvmlUtilJNA->>NvmlQuery: query(deviceId, SCOPE, reader, sentinel)
NvmlQuery->>NVML: initialize and acquire device
NvmlQuery->>NVML: read metric
NVML-->>NvmlQuery: result or failure
NvmlQuery->>NVML: uninitialize
NvmlQuery-->>NvmlUtilJNA: metric or sentinel
NvmlUtilJNA-->>Client: result
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #3542 +/- ##
============================================
+ Coverage 78.98% 79.00% +0.02%
- Complexity 76 3908 +3832
============================================
Files 699 701 +2
Lines 24159 24187 +28
Branches 4015 4019 +4
============================================
+ Hits 19082 19109 +27
- Misses 2883 2887 +4
+ Partials 2194 2191 -3
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
oshi-core/src/main/java/oshi/util/gpu/NvmlUtilJNA.java (1)
226-236: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
AtomicReferencehere is heavier than needed and diverges from the FFM twin.The visitor runs synchronously on the calling thread;
NvmlUtilFFM.acquireHandleByBusIduses a plainMemorySegment[1]. APointer[1]would keep the two backends symmetric, which is the point of this refactor.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@oshi-core/src/main/java/oshi/util/gpu/NvmlUtilJNA.java` around lines 226 - 236, Replace the AtomicReference used in the synchronous device visitor with a single-element Pointer array, matching the storage pattern in NvmlUtilFFM.acquireHandleByBusId. Update the found-handle assignment and return access accordingly, while preserving the existing bus-ID matching and traversal behavior.oshi-common/src/main/java/oshi/util/common/gpu/NvmlQuery.java (1)
112-120: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value
matchBusIdreturns an arbitrary form when the set holds both bus ID variants.Both backends add the modern and legacy IDs of each device into a
HashSet, so iteration order is unspecified andfindDevicemay return the legacy form for one device and the modern form for another.findDeviceByNameexplicitly prefers the modern form; consider making this path consistent (e.g. preferring the longest / domain-qualified match) so callers get a stable canonical identifier.♻️ Prefer the most qualified match
public static String matchBusId(Set<String> busIds, String fragment) { String needle = fragment.toLowerCase(Locale.ROOT); + String best = null; for (String id : busIds) { - if (matches(id, needle)) { - return id; + if (matches(id, needle) && (best == null || id.length() > best.length())) { + best = id; } } - return null; + return best; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@oshi-common/src/main/java/oshi/util/common/gpu/NvmlQuery.java` around lines 112 - 120, Update NvmlQuery.matchBusId to avoid returning the first HashSet match when both legacy and modern bus IDs match; select the most qualified canonical identifier, preferring the longest/domain-qualified form. Preserve case-insensitive matching and return null when no IDs match, so findDevice consistently receives the modern form.oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/NvmlUtilFFM.java (1)
141-148: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMagic buffer sizes for the bus ID reads.
32and16are the NVMLNVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE/..._V2_SIZEvalues; naming them (or deriving them fromPCI_INFO_LAYOUT's element sizes) would keep this in sync if the layout ever changes.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/NvmlUtilFFM.java` around lines 141 - 148, Update readBusIds to replace the literal 32 and 16 buffer lengths with named constants for the NVML PCI bus ID buffer sizes, or derive them from the corresponding PCI_INFO_LAYOUT element sizes. Use those symbols in both NvmlFunctions.readString calls so the reads remain synchronized with the layout.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@oshi-common/src/test/java/oshi/util/common/gpu/NvmlQueryTest.java`:
- Around line 121-128: Update the case-insensitivity assertion in
testMatchBusIdReturnsTheEnumeratedForm to pass a mixed-case bus ID fragment,
while preserving the expected canonical enumerated result.
---
Nitpick comments:
In `@oshi-common/src/main/java/oshi/util/common/gpu/NvmlQuery.java`:
- Around line 112-120: Update NvmlQuery.matchBusId to avoid returning the first
HashSet match when both legacy and modern bus IDs match; select the most
qualified canonical identifier, preferring the longest/domain-qualified form.
Preserve case-insensitive matching and return null when no IDs match, so
findDevice consistently receives the modern form.
In `@oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/NvmlUtilFFM.java`:
- Around line 141-148: Update readBusIds to replace the literal 32 and 16 buffer
lengths with named constants for the NVML PCI bus ID buffer sizes, or derive
them from the corresponding PCI_INFO_LAYOUT element sizes. Use those symbols in
both NvmlFunctions.readString calls so the reads remain synchronized with the
layout.
In `@oshi-core/src/main/java/oshi/util/gpu/NvmlUtilJNA.java`:
- Around line 226-236: Replace the AtomicReference used in the synchronous
device visitor with a single-element Pointer array, matching the storage pattern
in NvmlUtilFFM.acquireHandleByBusId. Update the found-handle assignment and
return access accordingly, while preserving the existing bus-ID matching and
traversal behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 645243ad-1db2-40fe-8a58-4bbe3d6a1e32
📒 Files selected for processing (8)
oshi-common/src/main/java/module-info.javaoshi-common/src/main/java/oshi/util/common/gpu/NvmlDeviceCache.javaoshi-common/src/main/java/oshi/util/common/gpu/NvmlQuery.javaoshi-common/src/main/java/oshi/util/common/gpu/package-info.javaoshi-common/src/test/java/module-info.testoshi-common/src/test/java/oshi/util/common/gpu/NvmlQueryTest.javaoshi-core-ffm/src/main/java/oshi/ffm/util/gpu/NvmlUtilFFM.javaoshi-core/src/main/java/oshi/util/gpu/NvmlUtilJNA.java
📜 Review details
⏰ Context from checks skipped due to timeout. (6)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.
Applied to files:
oshi-common/src/main/java/module-info.javaoshi-common/src/main/java/oshi/util/common/gpu/package-info.javaoshi-common/src/main/java/oshi/util/common/gpu/NvmlQuery.javaoshi-common/src/main/java/oshi/util/common/gpu/NvmlDeviceCache.java
📚 Learning: 2026-07-06T19:25:59.225Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3432
File: oshi-common/src/main/java/oshi/util/ExceptionUtil.java:26-56
Timestamp: 2026-07-06T19:25:59.225Z
Learning: In this repo’s SLF4J 1.x-compatible logging code, do not flag cases where a logger call uses SLF4J 1.6+ implicit-cause handling—e.g., `log.error("...{}", value, t)` (or similar with a single `{}` placeholder) where `t` is passed as the final/trailing argument. SLF4J will attach `t` as the log event’s cause with the full stack trace; this is equivalent to SLF4J 2.x’s fluent `atLevel(...).setCause(t).log(...)` and is intentionally used to preserve SLF4J 1.x runtime compatibility.
Applied to files:
oshi-common/src/main/java/oshi/util/common/gpu/package-info.javaoshi-common/src/main/java/oshi/util/common/gpu/NvmlQuery.javaoshi-common/src/main/java/oshi/util/common/gpu/NvmlDeviceCache.javaoshi-core/src/main/java/oshi/util/gpu/NvmlUtilJNA.javaoshi-core-ffm/src/main/java/oshi/ffm/util/gpu/NvmlUtilFFM.java
🔇 Additional comments (9)
oshi-common/src/main/java/oshi/util/common/gpu/NvmlQuery.java (1)
76-103: LGTM!oshi-common/src/main/java/oshi/util/common/gpu/NvmlDeviceCache.java (1)
29-59: LGTM!oshi-common/src/main/java/oshi/util/common/gpu/package-info.java (1)
1-8: LGTM!oshi-common/src/main/java/module-info.java (1)
61-61: LGTM!oshi-common/src/test/java/module-info.test (1)
41-42: LGTM!oshi-core/src/main/java/oshi/util/gpu/NvmlUtilJNA.java (2)
76-96: LGTM!Also applies to: 132-190, 199-215, 247-331
364-373: LGTM!Also applies to: 389-422, 430-492
oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/NvmlUtilFFM.java (2)
49-68: LGTM!Also applies to: 77-85, 103-132, 157-240, 246-294, 319-369, 377-439
42-46: 🩺 Stability & AvailabilityNo change needed for
NvmlFunctionsinitialization.
NvmlFunctionscatches allThrowables from library lookup/downcall handle creation during static init and storesAVAILABLE = false, so the addedNvmlFunctions.PCI_INFO_LAYOUTconstants do not change this path.> Likely an incorrect or invalid review comment.
- matchBusId returned whichever of a device's two enumerated bus ID forms set iteration reached first, so a bare fragment could resolve to the legacy or the modern form depending on HashSet order, and could differ between the JNA and FFM bindings. It now returns the longest match: the modern form carries the full eight-digit domain, so that consistently yields the domain-qualified id and agrees with what findDeviceByName returns. New test asserts both insertion orders so the result cannot depend on iteration again. - The FFM PCI bus ID read lengths are derived from PCI_INFO_LAYOUT instead of repeating 32 and 16 as literals, so they cannot drift from the struct definition. - The JNA device visitors capture their result in a single-element array rather than an AtomicReference, matching the FFM twin; the walk is synchronous, so the atomic implied concurrency that is not there. - The matchBusId case-insensitivity assertion used a fragment with no letters in it, so it proved nothing. It now uses a hex-letter bus ID.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@oshi-common/src/main/java/oshi/util/common/gpu/NvmlQuery.java`:
- Around line 118-122: Update NvmlQuery.matchBusId to return no match
immediately when fragment is null or empty, before lowercasing or iterating
busIds. Preserve the existing longest matching bus ID behavior for non-empty
fragments and avoid relying on matches() to reject an empty needle.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 0abe55cb-87c5-4364-a4ad-3b95f1d0d732
📒 Files selected for processing (4)
oshi-common/src/main/java/oshi/util/common/gpu/NvmlQuery.javaoshi-common/src/test/java/oshi/util/common/gpu/NvmlQueryTest.javaoshi-core-ffm/src/main/java/oshi/ffm/util/gpu/NvmlUtilFFM.javaoshi-core/src/main/java/oshi/util/gpu/NvmlUtilJNA.java
🚧 Files skipped from review as they are similar to previous changes (3)
- oshi-common/src/test/java/oshi/util/common/gpu/NvmlQueryTest.java
- oshi-core-ffm/src/main/java/oshi/ffm/util/gpu/NvmlUtilFFM.java
- oshi-core/src/main/java/oshi/util/gpu/NvmlUtilJNA.java
📜 Review details
⏰ Context from checks skipped due to timeout. (8)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Analyze (java)
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: Test JDK 21, ubuntu-latest
- GitHub Check: Test JDK 26, ubuntu-latest
- GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
- GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.
Applied to files:
oshi-common/src/main/java/oshi/util/common/gpu/NvmlQuery.java
📚 Learning: 2026-07-06T19:25:59.225Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3432
File: oshi-common/src/main/java/oshi/util/ExceptionUtil.java:26-56
Timestamp: 2026-07-06T19:25:59.225Z
Learning: In this repo’s SLF4J 1.x-compatible logging code, do not flag cases where a logger call uses SLF4J 1.6+ implicit-cause handling—e.g., `log.error("...{}", value, t)` (or similar with a single `{}` placeholder) where `t` is passed as the final/trailing argument. SLF4J will attach `t` as the log event’s cause with the full stack trace; this is equivalent to SLF4J 2.x’s fluent `atLevel(...).setCause(t).log(...)` and is intentionally used to preserve SLF4J 1.x runtime compatibility.
Applied to files:
oshi-common/src/main/java/oshi/util/common/gpu/NvmlQuery.java
Every string contains the empty string, so an empty fragment satisfied the bidirectional containment test against every enumerated id and resolved to the longest of them; a null fragment threw from toLowerCase. Both findDevice callers guard their argument before calling, so this was unreachable within OSHI, but matchBusId is public in an exported package. The matches() guard covers a blank candidate read back from a device, not a blank fragment supplied by a caller, so matchBusId now checks its own input rather than depending on matches() for it. Every other matches() caller receives a needle already guarded upstream, so its contract is unchanged.
Item 9a of the cross-OS consistency audit: the GPU family. NvmlUtil was the largest remaining duplication cluster in the project (100 + 82 Sonar duplicated lines).
What was duplicated
Every NVML metric had the same shape in both bindings — reject a blank device id, pair
nvmlInit_v2withnvmlShutdown, acquire a fresh handle inside that scope, fall back to a sentinel when any step fails. Only the native read differed. On top of that, each twin repeated its own device-enumeration walk three or four times.What changed
New in
oshi.util.common.gpu:NvmlQueryholds the query skeleton behind anNvmlScope<H>interface each twin implements once, plus the shared identifier matching. The FFM scope opens and closes itsArenainsidewithDevice, so noMemorySegmentescapes the exported package.NvmlDeviceCacheholds the enumerate-once-on-success bus ID cache, previously three statics duplicated per twin. Enumeration is retried until it succeeds so a transient NVML failure is not cached as "no devices" — which is why the enumerator distinguishesnullfrom empty.The twins keep only their native readers, and their internal device walks collapse behind
forEachDevice/readBusIds/readName.NvmlUtilJNA558 → 493,NvmlUtilFFM472 → 440.The public static API of both twins is unchanged, so no caller was touched.
Behavior changes, all deliberate
findDeviceByNamereturned a different string per backend for the same device. JNA readpci.busId(32-byte, 8-hex-digit domain,00000000:01:00.0) while FFM readbusIdLegacy(16-byte, 4-digit,0000:01:00.0). Both bindings declare both fields identically, so this was a real divergence — masked downstream only becauseacquireHandleByBusIdmatches by substring in either direction. Both now prefer the modern form and fall back to legacy, matching the orderenumerateDeviceBusIdsrecords them in.NvmlQuery.matchesrejects an empty candidate. Bidirectional containment previously let a device whose PCI bus ID or name read back blank match every query, since every string contains the empty string. Pre-existing in both twins.findDeviceByNameno longer callsensureDevicesEnumerated()— it was a no-op on that path; the enumerated set is only read byfindDevice, which warms it itself.No CHANGELOG entry:
deviceIdis internal plumbing between theGpuStatsbase andNvmlUtil, never surfaced in the publicGraphicsCard/GpuStatsAPI.Testing
New portable
NvmlQueryTest(10 cases) covers the lifecycle pairing including the exception path, every sentinel path, identifier matching, and the cache's retry-vs-cache semantics — all without an NVML library present. This is the first test coverage this code has had.Local gate green: spotless, checkstyle, install, forbiddenapis, javadoc, clean full-reactor build, 1385 tests across all modules, and
NativeComparisonTest40/40 on an M2 Max.Summary by CodeRabbit