Repository navigation
Add Apple Silicon GPU metrics via IOReport - #3092
Conversation
📝 WalkthroughWalkthroughAdds macOS IOReport JNA bindings and a synchronized IOReportDriver to sample GPU ticks, utilization, and power (Apple Silicon); integrates IOReport into MacGraphicsCard with unified‑memory VRAM handling; adds tests and a demo for GPU polling. Changes
Sequence Diagram(s)sequenceDiagram
participant App as Application / MacGraphicsCard
participant Driver as IOReportDriver
participant IOReport as IOReport (JNA)
participant HW as GPU Hardware / Kernel
App->>Driver: sampleGpuTicks()
activate Driver
Driver->>Driver: ensureInit() (lazy init, subscribe/merge channels)
Driver->>IOReport: IOReportCreateSubscription(...)
IOReport-->>Driver: subscription handle
Driver->>IOReport: IOReportCreateSamples(subscription,...)
IOReport-->>Driver: current sample dict
Driver->>IOReport: IOReportCreateSamplesDelta(prev, current)
IOReport-->>Driver: delta dict
Driver->>Driver: extractChannelStates(delta,"GPU Stats")
Driver-->>App: GpuTicks {timestamp, activeTicks}
deactivate Driver
sequenceDiagram
participant App as Application / MacGraphicsCard
participant Driver as IOReportDriver
participant IOReport as IOReport (JNA)
App->>Driver: sampleGpuUtilization()
activate Driver
Driver->>IOReport: IOReportCreateSamplesDelta(prev, current)
IOReport-->>Driver: delta dict (residency/perf states)
Driver->>Driver: compute utilization from residency deltas
Driver-->>App: utilization (0–100) or -1.0
deactivate Driver
App->>Driver: samplePowerWatts()
activate Driver
Driver->>IOReport: IOReportCreateSamplesDelta(prev, current)
IOReport-->>Driver: delta dict (energy model)
Driver->>Driver: extractGpuEnergyMicrojoules(delta) -> compute watts
Driver-->>App: watts or -1.0
deactivate Driver
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 📋 Issue PlannerBuilt with CodeRabbit's Coding Plans for faster development and fewer bugs. View plan used: ✨ 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✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #3092 +/- ##
==========================================
+ Coverage 69.38% 69.98% +0.59%
==========================================
Files 35 35
Lines 1839 1839
Branches 297 297
==========================================
+ Hits 1276 1287 +11
+ Misses 467 453 -14
- Partials 96 99 +3 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java (1)
48-59: Minor: Misleading comment.The comment "First call primes the subscription" is inaccurate for
sampleGpuTicks(). UnlikesampleGpuUtilization()orsamplePowerWatts()which require priming for delta calculations,sampleGpuTicks()returns cumulative values and doesn't need priming. The test logic itself is correct.📝 Suggested comment fix
`@Test` void testSampleGpuTicksMonotonic() throws InterruptedException { - // First call primes the subscription; second call returns a real delta. + // Cumulative ticks should be monotonically non-decreasing across samples. GpuTicks first = IOReportDriver.sampleGpuTicks();🤖 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/IOReportDriverTest.java` around lines 48 - 59, The comment above the testSampleGpuTicksMonotonic test is misleading; replace "First call primes the subscription; second call returns a real delta." with a concise, accurate note that IOReportDriver.sampleGpuTicks() returns cumulative tick values so the second sample is used to verify non-decreasing timestamps and active ticks (no priming needed). Update the comment near testSampleGpuTicksMonotonic and reference IOReportDriver.sampleGpuTicks() and GpuTicks to make intent clear.
🤖 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/IOReportDriver.java`:
- Around line 247-253: The subscription and subscribedChannels static resources
are never released, causing a leak; add cleanup that calls release() on the
stored subscription and subscribedChannels (e.g., subscription.release();
subscribedChannels.release();) with null checks and then nulls the static fields
to avoid double-release. Implement this either by registering a
Runtime.getRuntime().addShutdownHook that performs the releases or by adding a
public static cleanup/close method on IOReportDriver that callers can invoke;
ensure you reference the static fields subscription and subscribedChannels (and
CFDictionaryRef) so the correct objects are released and guard against multiple
calls.
In `@oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java`:
- Around line 40-46: The test testSampleGpuTicksFirstCallPositive should guard
against IOReport being unavailable on Intel Macs; modify the test to skip when
IOReport cannot initialize by adding an assumption (use assumeTrue) before
asserting—call IOReportDriver.sampleGpuTicks() or an availability helper on
IOReportDriver (e.g., an isAvailable/isInitialized method if present) and
assumeTrue(that IOReport is available) so the assertion on
ticks.getActiveTicks() only runs when IOReport is supported; alternatively,
change the assertion to greaterThanOrEqualTo(0L) if you prefer to allow zero as
a valid value.
---
Nitpick comments:
In `@oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java`:
- Around line 48-59: The comment above the testSampleGpuTicksMonotonic test is
misleading; replace "First call primes the subscription; second call returns a
real delta." with a concise, accurate note that IOReportDriver.sampleGpuTicks()
returns cumulative tick values so the second sample is used to verify
non-decreasing timestamps and active ticks (no priming needed). Update the
comment near testSampleGpuTicksMonotonic and reference
IOReportDriver.sampleGpuTicks() and GpuTicks to make intent clear.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 1a29a93c-ab93-4592-9586-736bb316d5f8
📒 Files selected for processing (5)
oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.javaoshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.javaoshi-core/src/main/java/oshi/jna/platform/mac/IOReport.javaoshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.javaoshi-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). (4)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Test JDK 21, windows-latest
- GitHub Check: Analyze (java)
🔇 Additional comments (24)
oshi-demo/src/main/java/oshi/demo/GpuStats.java (4)
1-27: LGTM!Clean demo structure with appropriate constants, private constructor for utility class, and clear Javadoc explaining the purpose.
55-60: LGTM!The seeding logic correctly primes both tick snapshots and power samples before the iteration loop, ensuring delta-based calculations have valid prior values.
68-71: LGTM!The tick-based utilization formula correctly implements
(delta activeTicks) / (delta timestamp) * 100as specified in theGpuTicksinterface, with proper guards against division by zero and negative deltas.
93-105: LGTM!Clean byte formatting helper with proper binary prefix handling and locale-independent formatting.
oshi-core/src/main/java/oshi/jna/platform/mac/IOReport.java (4)
1-24: LGTM!Clear interface declaration with appropriate warning about non-public APIs. The singleton
INSTANCEpattern withNative.loadis standard JNA practice.
26-37: LGTM!The
IOReportSubscriptionRefcorrectly extendsCFTypeRefwith both default andPointerconstructors required for JNA marshaling.
39-103: LGTM!Well-documented JNA method declarations with clear memory ownership semantics ("caller must release") and proper handling of reserved parameters.
105-154: LGTM!State accessor methods are cleanly declared with appropriate return types and parameter documentation.
oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java (5)
1-72: LGTM!Clean class structure with appropriate constants, clear documentation of channel groups and keys, and proper state field declarations for synchronized access.
79-102: LGTM!Solid implementation with proper resource management (finally block releases sample), defensive error handling returning zero-ticks on failure, and correct timestamp conversion to 100ns units.
110-151: LGTM!Well-structured delta-based utilization calculation with careful memory management. The pattern of nulling the local
samplereference after assigning toprevSampleUtilcorrectly prevents double-release in the outer finally block.
276-359: LGTM!Both extraction helpers correctly manage CF memory (releasing
channelsKey) and implement proper filtering logic for IOReport channel traversal. TheextractChannelStatespackage-private visibility appropriately allows test access.
193-194: Comment text contains incorrect unit equivalence.The formula
energyUj * 1000.0 / dtNanosis correct for converting µJ/ns to watts. However, the inline comment incorrectly states "1 µJ/ns = 1 mW" when it should be "1 µJ/ns = 1 kW" (or 1000 W).The unit conversion works because:
- energyUj is in microjoules (10⁻⁶ J)
- dtNanos is in nanoseconds (10⁻⁹ s)
- (µJ / ns) = (10⁻⁶ J) / (10⁻⁹ s) = 10³ W = 1 kW
Therefore, multiplying by 1000 correctly converts the ratio to watts, not megawatts.
Fix the comment to:
// 1 µJ/ns = 1 kW, so µJ/ns × 1000 = Woshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java (2)
1-20: LGTM!Clean test class setup with appropriate OS-specific conditional execution and standard imports.
61-68: LGTM!The test appropriately handles both the unavailable case (-1.0 sentinel) and valid readings, making it resilient across different macOS hardware configurations.
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java (9)
47-55: LGTM!Well-designed constants for Apple Silicon detection and trademark normalization. The
IS_APPLE_SILICONflag usingos.archis the standard approach for runtime architecture detection.
91-93: LGTM!Consistent application of
resolveVram()to both card creation points ensures uniform VRAM resolution across all graphics cards.Also applies to: 108-111
114-130: LGTM!The
resolveVramhelper correctly handles Apple Silicon's unified memory architecture by falling back to system memory when no dedicated VRAM is reported. UsingchipsetName.contains("Apple")is a reasonable heuristic that should remain valid for future Apple chips.
136-143: LGTM!Clean architecture delegation to
IOReportDriverfor Apple Silicon with appropriate fallback to zero-ticks for Intel, matching the documented behavior.
145-179: LGTM!Smart fallback chain: Apple Silicon first tries
IOReportDriver.sampleGpuUtilization(), then falls through to IOKitPerformanceStatisticsif IOReport returns unavailable (-1). This provides graceful degradation while preferring the more accurate IOReport metrics.
181-208: LGTM!The primary/fallback key pattern for VRAM lookup is well-designed, prioritizing the architecture-appropriate key while providing resilience through the fallback mechanism.
256-268: LGTM!Clean implementations with appropriate delegation to
IOReportDriverfor Apple Silicon power and explicit documentation for unavailable clock metrics.Note: If the unit conversion issue flagged in
IOReportDriver.samplePowerWatts()is confirmed, the power values returned here would also be affected.
333-340: LGTM!Robust name matching that handles trademark symbol variations (®, ™, (R), (TM)) and case differences, improving IOAccelerator service matching reliability.
215-229: Constant is properly defined.SmcUtil.SMC_KEYS_GPU_TEMP_ASis defined in SmcUtil and correctly used in the code. No issues found.
There was a problem hiding this comment.
🧹 Nitpick comments (2)
oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java (1)
277-294: Consider makingcleanup()reinitializable-safe (or explicitly terminal).If
cleanup()is invoked before JVM shutdown,ensureInit()won’t reinitialize becauseinitAttemptedremainstrue. Either reset init state in cleanup, or make terminal-only intent explicit.♻️ Suggested adjustment
static synchronized void cleanup() { @@ if (subscription != null) { subscription.release(); subscription = null; } + prevSamplePowerNanos = 0L; + ioReport = null; + initAttempted = false; }🤖 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/IOReportDriver.java` around lines 277 - 294, The cleanup() method currently releases resources (prevSampleUtil, prevSamplePower, subscribedChannels, subscription) but leaves the initAttempted flag true which prevents ensureInit() from reinitializing; update cleanup() to either reset initAttempted to false (making cleanup reinitializable-safe) and clear any other state needed for a fresh init, or explicitly document/throw to indicate cleanup is terminal; specifically modify IOReportDriver.cleanup() to set initAttempted = false (and any related state that ensureInit() relies on) so that ensureInit() can perform a new initialization, or alternatively make cleanup() final/terminal by renaming/documenting and not touching initAttempted.oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java (1)
64-69: Power test currently misses the delta path.Line 65 only exercises the priming call (
samplePowerWatts()first-call sentinel). Add a second sample after a short delay so the delta computation path is covered too.🧪 Suggested test tweak
- void testSamplePowerWattsValidOrSentinel() { - double watts = IOReportDriver.samplePowerWatts(); + void testSamplePowerWattsValidOrSentinel() throws InterruptedException { + // First call primes internal previous-sample state + IOReportDriver.samplePowerWatts(); + Thread.sleep(150); + double watts = IOReportDriver.samplePowerWatts(); // IOReport may not be available in all environments (e.g. Intel Mac, CI sandbox). // Accept either the sentinel -1.0 or a non-negative wattage. assertThat("Power should be -1 (unavailable) or a non-negative wattage", watts == -1d || watts >= 0d, is(true)); }🤖 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/IOReportDriverTest.java` around lines 64 - 69, Update the testSamplePowerWattsValidOrSentinel test to call IOReportDriver.samplePowerWatts() twice with a short pause (e.g., Thread.sleep(100)) between calls to exercise the delta path; keep the original acceptance criteria for each sample (value == -1d or value >= 0d) and add an assertion that the second sample is also either the sentinel -1d or non-negative so the delta computation branch in samplePowerWatts() is covered. Reference: test method testSamplePowerWattsValidOrSentinel and IOReportDriver.samplePowerWatts().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java`:
- Around line 277-294: The cleanup() method currently releases resources
(prevSampleUtil, prevSamplePower, subscribedChannels, subscription) but leaves
the initAttempted flag true which prevents ensureInit() from reinitializing;
update cleanup() to either reset initAttempted to false (making cleanup
reinitializable-safe) and clear any other state needed for a fresh init, or
explicitly document/throw to indicate cleanup is terminal; specifically modify
IOReportDriver.cleanup() to set initAttempted = false (and any related state
that ensureInit() relies on) so that ensureInit() can perform a new
initialization, or alternatively make cleanup() final/terminal by
renaming/documenting and not touching initAttempted.
In `@oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java`:
- Around line 64-69: Update the testSamplePowerWattsValidOrSentinel test to call
IOReportDriver.samplePowerWatts() twice with a short pause (e.g.,
Thread.sleep(100)) between calls to exercise the delta path; keep the original
acceptance criteria for each sample (value == -1d or value >= 0d) and add an
assertion that the second sample is also either the sentinel -1d or non-negative
so the delta computation branch in samplePowerWatts() is covered. Reference:
test method testSamplePowerWattsValidOrSentinel and
IOReportDriver.samplePowerWatts().
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: fb8ad7fa-3d77-4823-803d-366fe76ed4b5
📒 Files selected for processing (3)
CHANGELOG.mdoshi-core/src/main/java/oshi/driver/mac/IOReportDriver.javaoshi-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). (6)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, windows-latest
- 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 (3)
CHANGELOG.md (1)
6-7: Changelog entry looks correct and well-grouped.The new PR linkage is clear and consistent with adjacent entries.
oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java (1)
79-205: Solid defensive sampling and native resource handling.The synchronized sampling flow, sentinel fallbacks, and explicit
CFDictionaryRefrelease handling are implemented cleanly.Also applies to: 227-269
oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java (1)
41-48: Good use of assumption to avoid false failures on unsupported environments.This keeps the test valid across Intel Macs and constrained CI runners.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java (1)
20-73: Add a smoke test forsampleGpuUtilization()to cover all public sampling APIs.
sampleGpuUtilization()is currently untested in this class. A sentinel-or-range assertion (-1or0..100) would align with the contract and catch regressions.🧪 Proposed test
+ `@Test` + void testSampleGpuUtilizationValidRangeOrSentinel() throws InterruptedException { + double first = IOReportDriver.sampleGpuUtilization(); + assertThat("Utilization should be -1 (unavailable) or between 0 and 100", + first == -1d || (first >= 0d && first <= 100d), is(true)); + Thread.sleep(100); + double second = IOReportDriver.sampleGpuUtilization(); + assertThat("Utilization should remain -1 (unavailable) or between 0 and 100", + second == -1d || (second >= 0d && second <= 100d), is(true)); + }🤖 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/IOReportDriverTest.java` around lines 20 - 73, Add a smoke test method in IOReportDriverTest named testSampleGpuUtilizationValidOrSentinel that calls IOReportDriver.sampleGpuUtilization(), asserts the returned double is either the sentinel -1d or within 0..100 (e.g., assertThat(value == -1d || (value >= 0d && value <= 100d), is(true))), then optionally sleep briefly and call sampleGpuUtilization() again and assert the same sentinel-or-range contract to cover both initial and subsequent sampling paths.oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java (1)
95-96: Add debug logging on native sampling/init failures.These catch blocks currently return sentinels with no traceability, which makes field debugging hard when IOReport behavior changes. A debug log per failure path would preserve graceful degradation while improving diagnostics.
♻️ Proposed patch
import oshi.annotation.concurrent.ThreadSafe; import oshi.hardware.GpuTicks; import oshi.hardware.common.DefaultGpuTicks; import oshi.jna.platform.mac.IOReport; import oshi.jna.platform.mac.IOReport.IOReportSubscriptionRef; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; @@ public final class IOReportDriver { + private static final Logger LOG = LoggerFactory.getLogger(IOReportDriver.class); @@ } catch (Exception e) { + LOG.debug("IOReport sampleGpuTicks failed", e); return new DefaultGpuTicks(timestamp, 0L); @@ } catch (Exception e) { + LOG.debug("IOReport sampleGpuUtilization failed", e); return -1d; @@ } catch (Exception e) { + LOG.debug("IOReport samplePowerWatts failed", e); return -1d; @@ try { ioReport = Native.load("IOReport", IOReport.class); } catch (UnsatisfiedLinkError e) { + LOG.debug("IOReport native framework unavailable", e); return false; } @@ } catch (Exception e) { + LOG.debug("IOReport initialization failed", e); return false; } finally {Also applies to: 144-145, 198-199, 223-225, 258-259
🤖 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/IOReportDriver.java` around lines 95 - 96, In IOReportDriver, each catch block that currently swallows exceptions and returns sentinel objects (e.g., the catch returning new DefaultGpuTicks(timestamp, 0L)) should log the caught exception at debug level before returning so failures in native sampling/init are traceable; update the catch blocks in IOReportDriver (the ones returning DefaultGpuTicks and other sentinel return values) to call the class logger (e.g., LOG.debug(...) or equivalent) with a concise message and include the exception (e) to preserve stacktrace information while keeping the current graceful fallback behavior.
🤖 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/test/java/oshi/driver/mac/IOReportDriverTest.java`:
- Around line 52-53: Update the misleading test comment in IOReportDriverTest
around the calls to IOReportDriver.sampleGpuTicks(): change the wording that
currently claims the "second call returns a real delta" to state that
sampleGpuTicks() returns cumulative ticks and that the second call produces a
new cumulative sample (so the test compares successive cumulative values),
referencing the method name sampleGpuTicks() and the variable GpuTicks first to
locate the lines to edit.
---
Nitpick comments:
In `@oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java`:
- Around line 95-96: In IOReportDriver, each catch block that currently swallows
exceptions and returns sentinel objects (e.g., the catch returning new
DefaultGpuTicks(timestamp, 0L)) should log the caught exception at debug level
before returning so failures in native sampling/init are traceable; update the
catch blocks in IOReportDriver (the ones returning DefaultGpuTicks and other
sentinel return values) to call the class logger (e.g., LOG.debug(...) or
equivalent) with a concise message and include the exception (e) to preserve
stacktrace information while keeping the current graceful fallback behavior.
In `@oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java`:
- Around line 20-73: Add a smoke test method in IOReportDriverTest named
testSampleGpuUtilizationValidOrSentinel that calls
IOReportDriver.sampleGpuUtilization(), asserts the returned double is either the
sentinel -1d or within 0..100 (e.g., assertThat(value == -1d || (value >= 0d &&
value <= 100d), is(true))), then optionally sleep briefly and call
sampleGpuUtilization() again and assert the same sentinel-or-range contract to
cover both initial and subsequent sampling paths.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e2e381d3-4eac-4ded-ad7d-41e893cb96a1
📒 Files selected for processing (2)
oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.javaoshi-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 25, macos-latest
- GitHub Check: Test JDK 21, windows-latest
- GitHub Check: Test JDK 25, windows-latest
- GitHub Check: Analyze (java)
🔇 Additional comments (2)
oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java (1)
254-257: Native resource lifecycle handling looks solid.Line 256’s shutdown hook plus
cleanup()releasingprevSample*,subscribedChannels, andsubscriptionis a good fix for long-lived native-resource retention.Also applies to: 280-297
oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java (1)
41-48: Availability guard for Intel/sandboxed environments is well done.Using
Assumptions.assumeTrue(...)here avoids false negatives while still validating behavior when IOReport data is present.
Summary
Adds dynamic GPU metrics for Apple Silicon Macs using Apple's private
IOReportframework, and improves VRAM reporting and IOAccelerator name matching inMacGraphicsCard. AGpuStatsdemo class is also added to validate the new metrics (on all platforms).Changes
MacGraphicsCard— Apple Silicon VRAM and name matchingIS_APPLE_SILICONflag (os.arch == aarch64) to gate AS-specific code pathsresolveVram(): on Apple Silicon, where unified memory meanssystem_profilerreports no dedicated VRAM, falls back tohw.memsizesysctl (total system memory) as the VRAM figureVRAM_USED_KEY_AS = "In use system memory"and updatedgetVramUsed()to probe the AS key first on AS, with Intel key as fallback (and vice versa on Intel)TRADEMARK_PATTERNcovering Unicode®/™and ASCII(R)/(TM)variants; used inmatchesName()to correctly match IOAccelerator model strings against card names that differ only by trademark symbolsIOReport.java+IOReportDriver.java+IOReportDriverTest.java— IOReport JNA mapping and driverIOReportJNA interface mapping Apple's privateIOReportframework, including:IOReportCopyChannelsInGroup/IOReportMergeChannelsIOReportCreateSubscription/IOReportCreateSamples/IOReportCreateSamplesDeltaIOReportSimpleGetIntegerValueIOReportChannelGetGroup,IOReportChannelGetSubGroup,IOReportChannelGetChannelName,IOReportStateGetCount,IOReportStateGetNameForIndex,IOReportStateGetResidencyIOReportDriverwhich subscribes to the mergedGPU Stats+Energy Modelchannel groups at lazy initialisation time and exposes three public methods:sampleGpuTicks()— returns aGpuTickssnapshot with cumulative active ticks derived from theGPUPHchannel (GPU Performance Statessubgroup); active = total −OFFtickssampleGpuUtilization()— delta-based utilization percentage from the same channelsamplePowerWatts()— delta-based GPU power in watts from theGPU Energychannel in theEnergy Modelgroup (values in µJ; conversion:µJ * 1000 / ns = W)IOReportDriverTestwith 6 tests covering tick monotonicity, non-negativity, and positive first-call valuesMacGraphicsCard— wire IOReport and SMC into dynamic metricsgetGpuTicks()→IOReportDriver.sampleGpuTicks()on AS; timestamp-only stub on IntelgetGpuUtilization()→IOReportDriver.sampleGpuUtilization()on AS withPerformanceStatisticsfallback;PerformanceStatisticson IntelgetTemperature()→ SMCSMC_KEYS_GPU_TEMP_ASon AS;PerformanceStatistics "Temperature(C)"on IntelgetPowerDraw()→IOReportDriver.samplePowerWatts()on AS;-1on Intel (not available)getCoreClockMhz()→-1(not exposed via any public API on Apple Silicon or Intel macOS)GpuStats.java— demooshi-democlass that polls all graphics cards 10 times at 1-second intervalsGpuTickssnapshots), API utilization, VRAM used, temperature, power draw, and core clockNotes
IOReportis a private Apple framework. The JNA mappings are for OSHI internal use only and are not considered stable API.IOReportGroupare absent from the CF dictionary; data must be read via the dedicated accessor functions (IOReportChannelGetGroup, etc.).getCoreClockMhz()correctly returns-1.getVRam()returns total system memory (hw.memsize) as the unified memory pool serves as GPU memory.Summary by CodeRabbit
New Features
Tests
Documentation