Skip to content

Add Apple Silicon GPU metrics via IOReport - #3092

Merged
dbwiddis merged 5 commits into
oshi:masterfrom
dbwiddis:mac-gpu
Mar 13, 2026
Merged

dbwiddis merged 5 commits into
oshi:masterfrom
dbwiddis:mac-gpu

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Mar 12, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds dynamic GPU metrics for Apple Silicon Macs using Apple's private IOReport framework, and improves VRAM reporting and IOAccelerator name matching in MacGraphicsCard. A GpuStats demo class is also added to validate the new metrics (on all platforms).

Changes

MacGraphicsCard — Apple Silicon VRAM and name matching

  • Added IS_APPLE_SILICON flag (os.arch == aarch64) to gate AS-specific code paths
  • Added resolveVram(): on Apple Silicon, where unified memory means system_profiler reports no dedicated VRAM, falls back to hw.memsize sysctl (total system memory) as the VRAM figure
  • Added VRAM_USED_KEY_AS = "In use system memory" and updated getVramUsed() to probe the AS key first on AS, with Intel key as fallback (and vice versa on Intel)
  • Added TRADEMARK_PATTERN covering Unicode ®/™ and ASCII (R)/(TM) variants; used in matchesName() to correctly match IOAccelerator model strings against card names that differ only by trademark symbols

IOReport.java + IOReportDriver.java + IOReportDriverTest.java — IOReport JNA mapping and driver

  • Added IOReport JNA interface mapping Apple's private IOReport framework, including:
    • IOReportCopyChannelsInGroup / IOReportMergeChannels
    • IOReportCreateSubscription / IOReportCreateSamples / IOReportCreateSamplesDelta
    • IOReportSimpleGetIntegerValue
    • Accessor functions required to read opaque channel entries: IOReportChannelGetGroup, IOReportChannelGetSubGroup, IOReportChannelGetChannelName, IOReportStateGetCount, IOReportStateGetNameForIndex, IOReportStateGetResidency
  • Added IOReportDriver which subscribes to the merged GPU Stats + Energy Model channel groups at lazy initialisation time and exposes three public methods:
    • sampleGpuTicks() — returns a GpuTicks snapshot with cumulative active ticks derived from the GPUPH channel (GPU Performance States subgroup); active = total − OFF ticks
    • sampleGpuUtilization() — delta-based utilization percentage from the same channel
    • samplePowerWatts() — delta-based GPU power in watts from the GPU Energy channel in the Energy Model group (values in µJ; conversion: µJ * 1000 / ns = W)
  • Added IOReportDriverTest with 6 tests covering tick monotonicity, non-negativity, and positive first-call values

MacGraphicsCard — wire IOReport and SMC into dynamic metrics

  • getGpuTicks() → IOReportDriver.sampleGpuTicks() on AS; timestamp-only stub on Intel
  • getGpuUtilization() → IOReportDriver.sampleGpuUtilization() on AS with PerformanceStatistics fallback; PerformanceStatistics on Intel
  • getTemperature() → SMC SMC_KEYS_GPU_TEMP_AS on AS; PerformanceStatistics "Temperature(C)" on Intel
  • getPowerDraw() → IOReportDriver.samplePowerWatts() on AS; -1 on Intel (not available)
  • getCoreClockMhz() → -1 (not exposed via any public API on Apple Silicon or Intel macOS)

GpuStats.java — demo

  • Added oshi-demo class that polls all graphics cards 10 times at 1-second intervals
  • Displays per-iteration: tick-based utilization (from two GpuTicks snapshots), API utilization, VRAM used, temperature, power draw, and core clock
  • Pre-seeds tick and power snapshots before the loop so all values are available from iteration 1

Notes

  • IOReport is a private Apple framework. The JNA mappings are for OSHI internal use only and are not considered stable API.
  • Channel entries in IOReport samples are opaque — string keys such as IOReportGroup are absent from the CF dictionary; data must be read via the dedicated accessor functions (IOReportChannelGetGroup, etc.).
  • Apple Silicon GPU clock frequency is not exposed via IOReport or any other public API; getCoreClockMhz() correctly returns -1.
  • On Apple Silicon, getVRam() returns total system memory (hw.memsize) as the unified memory pool serves as GPU memory.

Summary by CodeRabbit

  • New Features

    • Enhanced GPU metrics on macOS/Apple Silicon: real-time utilization, power draw (watts), tick sampling, temperature, and improved VRAM resolution.
    • Added a GpuStats demo app to monitor and display graphics card metrics over time.
  • Tests

    • Added macOS-specific unit tests validating GPU tick, utilization, and power sampling behavior.
  • Documentation

    • Changelog updated with new GPU-related entries.

@coderabbitai

coderabbitai Bot commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds 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

Cohort / File(s) Summary
IOReport JNA & Driver
oshi-core/src/main/java/oshi/jna/platform/mac/IOReport.java, oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java
New JNA interface for Apple's private IOReport API and a thread-safe driver that creates/merges subscriptions, samples current/delta data, parses channel states/energy, and exposes sampleGpuTicks(), sampleGpuUtilization(), and samplePowerWatts().
Mac Graphics Integration
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
Apple Silicon awareness: unified VRAM resolution, delegate GPU ticks/utilization/power to IOReportDriver on Apple Silicon, add getPowerDraw() and getCoreClockMhz(), normalize model/name matching (trademark stripping).
Tests & Demo
oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java, oshi-demo/src/main/java/oshi/demo/GpuStats.java
New macOS-gated unit tests validating GpuTicks monotonicity and power reporting; new demo GpuStats polling graphics cards (10×, 1s) and printing utilization, temperature, power, core clock, and VRAM.
Changelog
CHANGELOG.md
Added PR 3092 entry adjacent to existing GPU-related entry (separate bullet).

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
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped to IOReport's hidden gate,

I counted ticks and watched watts rate,
From silicon groves I fetched the score,
Now GPUs hum and metrics soar,
A carrot-sampled snapshot—encore! 🎩

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main addition: GPU metrics support for Apple Silicon using the IOReport framework.
Linked Issues check ✅ Passed The PR comprehensively addresses all coding objectives from #2112 (GPU information API placement and macOS retrieval) and #3090 (Apple Silicon GPU metrics via IOReport, VRAM resolution, SMC key probing, thread-safe driver).
Out of Scope Changes check ✅ Passed All changes are directly aligned with PR objectives: IOReport JNA/driver, MacGraphicsCard enhancements for Apple Silicon, VRAM resolution, GpuStats demo, and test coverage—no extraneous modifications detected.

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

📋 Issue Planner

Built with CodeRabbit's Coding Plans for faster development and fewer bugs.

View plan used: #3090

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
✨ Simplify code
  • Create PR with simplified code
📝 Coding Plan
  • Generate coding plan for human review comments

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

❤️ Share

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

@codecov

codecov Bot commented Mar 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 69.98%. Comparing base (0879577) to head (13fb2e2).
⚠️ Report is 2 commits behind head on master.

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.
📢 Have feedback on the report? Share it here.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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(). Unlike sampleGpuUtilization() or samplePowerWatts() 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0879577 and 33bb94a.

📒 Files selected for processing (5)
  • oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGraphicsCard.java
  • oshi-core/src/main/java/oshi/jna/platform/mac/IOReport.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). (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) * 100 as specified in the GpuTicks interface, 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 INSTANCE pattern with Native.load is standard JNA practice.


26-37: LGTM!

The IOReportSubscriptionRef correctly extends CFTypeRef with both default and Pointer constructors 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 sample reference after assigning to prevSampleUtil correctly 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. The extractChannelStates package-private visibility appropriately allows test access.


193-194: Comment text contains incorrect unit equivalence.

The formula energyUj * 1000.0 / dtNanos is 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 = W

oshi-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_SILICON flag using os.arch is 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 resolveVram helper correctly handles Apple Silicon's unified memory architecture by falling back to system memory when no dedicated VRAM is reported. Using chipsetName.contains("Apple") is a reasonable heuristic that should remain valid for future Apple chips.


136-143: LGTM!

Clean architecture delegation to IOReportDriver for 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 IOKit PerformanceStatistics if 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 IOReportDriver for 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_AS is defined in SmcUtil and correctly used in the code. No issues found.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java (1)

277-294: Consider making cleanup() reinitializable-safe (or explicitly terminal).

If cleanup() is invoked before JVM shutdown, ensureInit() won’t reinitialize because initAttempted remains true. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 33bb94a and e38b030.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java
  • 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). (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 CFDictionaryRef release 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
oshi-core/src/test/java/oshi/driver/mac/IOReportDriverTest.java (1)

20-73: Add a smoke test for sampleGpuUtilization() to cover all public sampling APIs.

sampleGpuUtilization() is currently untested in this class. A sentinel-or-range assertion (-1 or 0..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

📥 Commits

Reviewing files that changed from the base of the PR and between e38b030 and 13fb2e2.

📒 Files selected for processing (2)
  • oshi-core/src/main/java/oshi/driver/mac/IOReportDriver.java
  • 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 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() releasing prevSample*, subscribedChannels, and subscription is 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.

@dbwiddis
dbwiddis merged commit f0d52f2 into oshi:master Mar 13, 2026
13 of 14 checks passed
@dbwiddis
dbwiddis deleted the mac-gpu branch April 3, 2026 05:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Restore macOS Sensors and add GPU runtime stats via IOReport + updated SMC keys on Apple Silicon Adding GPU information

1 participant