Repository navigation
Hoist the macOS GpuStats session into a common base - #3543
Conversation
The two macOS GpuStats twins duplicated an entire session: lifecycle and closed-state guarding, card-name normalization and matching, VRAM key selection, the temperature cascade with its absence latch, and every sentinel-returning metric. Only two native reads actually differed. New in oshi.hardware.common.platform.mac: - MacGpuStats holds the session. Subclasses implement queryPerfStats and queryGpuTemperatureFromSmc and inherit the rest. - IOReportSampler is the five-method shape IOReportClient and IOReportClientFFM already had; both now declare implements. Their internals wrap genuinely different native APIs and are untouched. The CoreFoundation dictionary types differ between the bindings, so the hook boundary is "read these keys in one registry walk" rather than passing a dictionary up. queryPerfStats returns null when the card's statistics cannot be read at all, and an empty map when the dictionary was present but held none of the requested keys. That distinction is load-bearing: getTemperature latches a card as having no sensor only on the second case, never on the first, which can be transient after a driver reset or an eGPU unplug. MacGpuStatsJNA 311 -> 125, MacGpuStatsFFM 300 -> 117. Behavior changes: - FFM now gates the IOReport subscription behind isAppleSilicon, as JNA already did. The IOReport GPU channels do not exist on Intel, so FFM was attempting a subscription there that could never yield a sample and that JNA never made. FFM also gains JNA's warning when an Apple Silicon subscription fails. - The temperature-absence latch is now one set shared by both bindings rather than one per twin. Only one backend is active per JVM, so this is inert in practice. No CHANGELOG: no user-observable behavior changes on Apple Silicon, and on Intel the affected path only ever returned sentinels. New MacGpuStatsTest stubs both hooks and the sampler, covering the Intel no-subscription rule, sampler-versus-accelerator precedence, core utilization scaling, the VRAM key swap in both directions, both latch behaviors, close and checkOpen, and name normalization. Validated live on an M2 Max: both backends return plausible utilization, power, temperature, VRAM and tick values through the new base, so the IOReport, SMC and IOAccelerator paths are all exercised on real hardware. NativeComparisonTest graphicsCards passes.
|
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. (6)
📝 WalkthroughWalkthroughIntroduces a shared macOS GPU statistics session, an IOReport sampling interface, JNA/FFM adapters, architecture-specific fallbacks, lifecycle handling, and tests for metrics, temperature, name matching, and closure. ChangesmacOS GPU statistics
Estimated code review effort: 4 (Complex) | ~45 minutes 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 #3543 +/- ##
============================================
- Coverage 79.08% 79.01% -0.08%
- Complexity 3714 3932 +218
============================================
Files 701 701
Lines 24187 24187
Branches 4019 4019
============================================
- Hits 19129 19111 -18
- Misses 2870 2890 +20
+ Partials 2188 2186 -2
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 (1)
oshi-common/src/test/java/oshi/hardware/common/platform/mac/MacGpuStatsTest.java (1)
232-237: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePrefer
assertThrowsover the manual try/catch.
org.junit.jupiter.api.Assertions.assertThrowsexpresses the intent directly and produces a better failure message than a thrownAssertionError.♻️ Proposed refactor
- try { - gpu.getGpuUtilization(); - throw new AssertionError("reading a closed session should throw"); - } catch (IllegalStateException expected) { - // Every metric guards on the closed flag. - } + // Every metric guards on the closed flag. + assertThrows(IllegalStateException.class, gpu::getGpuUtilization, + "reading a closed session should throw");Add the import:
import static org.junit.jupiter.api.Assertions.assertThrows;🤖 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/test/java/oshi/hardware/common/platform/mac/MacGpuStatsTest.java` around lines 232 - 237, Update the closed-session test in MacGpuStatsTest to use JUnit’s assertThrows for the gpu.getGpuUtilization() call, replacing the manual try/catch and AssertionError while preserving the expected IllegalStateException assertion.
🤖 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-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java`:
- Around line 98-103: Update the CFRetain handling in the stats dictionary
creation flow so a failed CoreFoundationFunctions.CFRetain(statsSeg) leaves
result null and does not construct CFMutableDictionaryRef from statsSeg. Only
assign result after a successful retain, preserving queryPerfStats ownership and
close behavior.
---
Nitpick comments:
In
`@oshi-common/src/test/java/oshi/hardware/common/platform/mac/MacGpuStatsTest.java`:
- Around line 232-237: Update the closed-session test in MacGpuStatsTest to use
JUnit’s assertThrows for the gpu.getGpuUtilization() call, replacing the manual
try/catch and AssertionError while preserving the expected IllegalStateException
assertion.
🪄 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: e010f680-35eb-42be-90f5-cbf321147279
📒 Files selected for processing (7)
oshi-common/src/main/java/oshi/hardware/common/platform/mac/IOReportSampler.javaoshi-common/src/main/java/oshi/hardware/common/platform/mac/MacGpuStats.javaoshi-common/src/test/java/oshi/hardware/common/platform/mac/MacGpuStatsTest.javaoshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.javaoshi-core/src/main/java/oshi/driver/mac/IOReportClient.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java
📜 Review details
⏰ Context from checks skipped due to timeout. (7)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Analyze (java)
- GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: Test JDK 26, ubuntu-latest
- GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (3)
📚 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/hardware/common/platform/mac/IOReportSampler.javaoshi-common/src/main/java/oshi/hardware/common/platform/mac/MacGpuStats.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/hardware/common/platform/mac/IOReportSampler.javaoshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.javaoshi-core/src/main/java/oshi/driver/mac/IOReportClient.javaoshi-common/src/main/java/oshi/hardware/common/platform/mac/MacGpuStats.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.javaoshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).
Applied to files:
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java
🪛 ast-grep (0.45.0)
oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacGpuStats.java
[warning] 83-83: Regular expression is compiled from a non-literal, possibly user-controlled value. A crafted regex (or input matched against one) can trigger catastrophic backtracking and hang the thread (ReDoS). Use a hardcoded literal pattern, wrap untrusted text with Pattern.quote(...), or validate/length-limit the input and enforce a matching timeout before passing it to Pattern.compile / String.matches / String.replaceAll / String.replaceFirst.
Context: Pattern.compile("\b" + Pattern.quote(normCardName) + "\b")
Note: [CWE-1333] Inefficient Regular Expression Complexity.
(redos-non-literal-regex-java)
🔇 Additional comments (7)
oshi-common/src/main/java/oshi/hardware/common/platform/mac/IOReportSampler.java (1)
1-48: LGTM!oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacGpuStats.java (1)
1-260: LGTM!oshi-core/src/main/java/oshi/driver/mac/IOReportClient.java (1)
16-19: LGTM!Also applies to: 35-35, 122-122, 159-159, 208-208, 262-262
oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java (1)
28-28: LGTM!Also applies to: 40-40, 114-114, 143-143, 192-192, 245-245
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java (1)
7-8: LGTM!Also applies to: 22-81
oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java (1)
8-9: LGTM!Also applies to: 22-77
oshi-common/src/test/java/oshi/hardware/common/platform/mac/MacGpuStatsTest.java (1)
121-231: LGTM!Also applies to: 240-256
props.getValue follows the CoreFoundation Get rule, so the statistics dictionary belongs to props; the retain is what lets it outlive props.close(). The wrapper was built unconditionally, so a throwing CFRetain left queryPerfStats releasing a reference that was never taken, over-releasing a dictionary still owned by props. Build the wrapper inside the try instead, so a failed retain leaves result null and the walk moves on to the next accelerator entry. Pre-existing: this shape is byte-identical on master and was carried over verbatim by the base-class extraction. The JNA twin is unaffected because its CFRetain does not declare throws Throwable and so has no swallowing catch. Restored a logger to the class, dropped during the extraction, so the failure is visible at debug level. Also use assertThrows for the closed-session assertion, matching the idiom already used in MacCentralProcessorTest and elsewhere in the module.
CodeQL Code Quality reported seven java/index-out-of-bounds findings (severity error) across the two test files added in #3543 and #3546. Each finding is the same shape: a private varargs helper walks its arguments in fixed-size groups, striding by two or three, but bounds the loop on the first index of the group rather than the last. Reading namesAndIds[i + 1] under a loop guarded only by i < namesAndIds.length runs off the end whenever the caller passes a partial group. Unlike the useless-null-check and dereferenced-value-may-be-null findings on these files, this one is not a false positive. Every call site today passes a complete multiple, so nothing can throw as written, but the helpers make no such guarantee and the finding will resurface each time the files move. Bounding each loop on the last index it reads is what CodeQL's range analysis needs to see, and it turns a would-be ArrayIndexOutOfBoundsException into one fewer row for a caller that miscounts -- which a test's own assertions will catch immediately. The two production stride loops were checked and left alone: ParseUtil.hexStringToByteArray already rejects odd-length input with an explicit (len & 0x1) != 0 guard, and HkeyPerformanceDataUtil.buildCounterIndexMap starts at i = 1 and reads backwards to i - 1, so both indices are always in range. Neither was flagged. Test-only, so no CHANGELOG entry.
Item 9b of the cross-OS consistency audit, following #3542. The two macOS
GpuStatstwins duplicated an entire session — lifecycle and closed-state guarding, card-name normalization and matching, VRAM key selection, the temperature cascade with its absence latch, and every sentinel-returning metric. Only two native reads actually differed.What changed
New in
oshi.hardware.common.platform.mac:MacGpuStatsholds the session. Subclasses implementqueryPerfStatsandqueryGpuTemperatureFromSmcand inherit everything else.IOReportSampleris the five-method shapeIOReportClientandIOReportClientFFMalready had; both now declareimplements. Their internals wrap genuinely different native APIs and are untouched.The CoreFoundation dictionary types differ between the bindings, so the hook boundary is "read these keys in one registry walk" rather than passing a dictionary up.
queryPerfStatsreturnsnullwhen the card's statistics cannot be read at all, and an empty map when the dictionary was present but held none of the requested keys. That distinction is load-bearing:getTemperaturelatches a card as having no sensor only on the second case, never on the first, which can be transient after a driver reset or an eGPU unplug.MacGpuStatsJNA311 → 125,MacGpuStatsFFM300 → 117.Behavior changes
isAppleSilicon, as JNA already did. The IOReport GPU channels do not exist on Intel, so FFM was attempting a subscription there that could never yield a sample and that JNA never made. FFM also gains JNA's warning when an Apple Silicon subscription fails.No CHANGELOG: no user-observable change on Apple Silicon, and on Intel the affected path only ever returned sentinels.
Testing
New
MacGpuStatsTest(11 cases) stubs both hooks and the sampler: the Intel no-subscription rule, sampler-versus-accelerator precedence, core utilization scaling against the residency divisor, the VRAM key swap in both directions, both latch behaviors, close andcheckOpen, and name normalization.Validated live on an M2 Max — both backends drive the new base against real hardware, exercising the IOReport utilization and power deltas, GPU ticks, SMC temperature, and the IOAccelerator VRAM lookup:
(Values differ because these are instantaneous samples taken under a second apart on a live system.)
Local gate green: spotless, checkstyle, install, forbiddenapis, javadoc, clean full-reactor build, 1398 tests, and
NativeComparisonTest40/40.Noted, not fixed here
GpuTickshastoStringbut noequals/hashCode, so comparing two instances falls back to identity.NativeComparisonTestonly avoids this viausingRecursiveComparison(). Happy to do that as a standalone change if wanted.Summary by CodeRabbit