Skip to content

Discover Apple Silicon GPU temperature SMC keys at runtime - #3536

Merged
dbwiddis merged 4 commits into
oshi:masterfrom
dbwiddis:fix-3534-gpu-smc-key-discovery
Jul 27, 2026
Merged

dbwiddis merged 4 commits into
oshi:masterfrom
dbwiddis:fix-3534-gpu-smc-key-discovery

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #3535, which fixed the CPU side. GPU temperature reads a fixed list of four SMC keys, SMC_KEYS_GPU_TEMP_AS = [Tg05, Tg0D, Tg0f, Tg0j], and returns the first plausible one.

Nothing is broken today — those four cover every Apple Silicon machine in the iSMC hardware dataset. But the list survives by luck, not design: on an M2 Max only Tg0f and Tg0j exist, and six of that machine's sixteen GPU sensors appear in no published key table at all. It also reports one arbitrary cluster out of the 8–84 a modern chip exposes.

There is no GPU analogue of #3535's TCMb/TCMz firmware die aggregate, so that solution does not transfer.

What this does

Binary-searches the SMC's sorted key index for the Tg block, keeps the keys matching the GPU naming convention, and reports the hottest plausible reading. ~14 ms once, cached for the JVM lifetime.

Measured across the dataset, decoding raw flt bytes for the older report format:

report today (first of 4) this PR (max) keys found
a18 66.4 68.1 8
m1-pro 62.9 63.6 4
m3-max 41.0 43.0 32
m4-pro 56.0 57.2 22
m5-pro 38.0 41.0 42
m1-max / m3-pro 45.7 / 38.2 unchanged 8 / 18

The mask is derived from data

Character 3 is always a digit, but character 4 is uppercase in only 42% of published keys, lowercase in 43%, a digit in 15%:

mask this M2 Max iSMC's 100 known GPU keys
^Tg[0-9a-z][A-Z]$ 6/16 42/100
^Tg[0-9][0-9A-Za-z]$ 16/16 100/100

The narrower mask misses Tg0f — the only one of the original four present on this hardware. Zero false positives: every Tg* key in the dataset is a GPU sensor.

Design notes

  • The index logic lives in oshi-common, not SmcUtil, whose static IOKit.INSTANCE field makes any of its members unloadable off a Mac. Passing an IntFunction keeps the two connection handle types out of the shared code, so the binary search, mask, config parsing and aggregation are unit-tested on any OS — that is where the edge cases are (18 tests: block at index 0/last/middle/absent, read failures transient and permanent, unsorted input, duplicates, #KEY garbage).
  • Caches which keys exist, not which currently read plausibly. Existence is a hardware property; plausibility is not, since an idle sensor reports a sentinel below ambient. Filtering at discovery time would let one unlucky first call cache an empty set and disable GPU temperature for the JVM lifetime.
  • Not Memoizer, which caches whatever the supplier returned including a failure — a transient smcOpen failure would be permanent. A failed discovery falls back without caching so a later call retries.
  • No data-type filter. smcGetFloat already decodes every temperature encoding the SMC uses and returns 0 otherwise, which the plausibility floor rejects. The check cost a second read per key and would have wrongly excluded a sensor reported as sp78.
  • Max, not average. Each cluster exposes a pair of sensors at different die locations. Averaging would combine two different measurements, and separating them needs the per-chip table this avoids. Verified the pair is not instantaneous/peak-hold — both members rose 44.8/51.4 → 56.1/62.6 under load and fell together afterwards, so the max tracks the hotter location rather than a latched peak.

SMC_KEYS_GPU_TEMP_AS is kept as the fallback when the index cannot be read, widened from 4 to the 14 keys most common across published M1–M5 and A18 dumps. oshi.os.mac.sensors.gputemperature.keys overrides discovery entirely, parsed lazily so GlobalConfig.set() still takes effect.

The Intel IOAccelerator Temperature(C) fallback is absent on Apple Silicon, so it is now tried once per card then latched off rather than repeating an IOKit registry walk every call.

Why not IOReport or IOHID

Both were investigated on hardware and eliminated, detail in #3534:

  • IOReport GPU Stats → Temperature is a driver stub. All 64 channels read 0 as root, under GPU load, and in the raw RawElements blob, byte-identical across samples.
  • IOHID measures the wrong thing: under Metal load the SMC GPU sensors rose +21 °C while the best HID sensor moved +5 °C. It is a damped board/PMU sensor, and the gap widens with load, so it is not a correctable offset.

Verification

  • Full reactor: 1146 + 95 + 80 + 30 tests, 0 failures. Spotless, checkstyle, forbidden-apis, javadoc clean.
  • ./mvnw test -pl oshi-benchmark -Pnative-comparison — sensors() and the new gpuTemperatureKeys() both pass. The latter asserts the two backends discover identical key lists; since each runs its own binary search, list equality is the sharpest available parity check.
  • M2 Max, idle → Metal load → idle: getTemperature() = 47.8 → 66.5 → 55.1 °C. Discovery finds all 16 keys in both backends.

Summary by CodeRabbit

  • New Features

    • macOS now discovers Apple Silicon GPU temperature sensor keys dynamically for broader hardware support.
    • GPU temperature selection now prefers the hottest available GPU cluster.
    • Added an optional configuration (oshi.os.mac.sensors.gputemperature.keys) to override which SMC temperature keys are used.
  • Bug Fixes

    • Improved reliability when GPU temperature data is unavailable by reducing repeated lookups and tightening fallback behavior when sensors/perf stats are missing.

dbwiddis added 2 commits July 27, 2026 15:02
GPU temperature read a fixed list of four SMC keys and returned the first
plausible one. Those keys are chip-specific: on an M2 Max only two of the four
exist, and six of that machine's sixteen GPU sensors appear in no published key
table at all. The list happens to cover every Apple Silicon machine in the iSMC
hardware dataset, so nothing is broken today, but it survives by luck and
reports one arbitrary cluster out of the 8 to 84 a modern chip exposes.

Discovery instead binary searches the SMC's sorted key index for the Tg block
and keeps the keys matching the GPU naming convention, then reports the hottest
plausible reading. On an M2 Max that finds all 16 keys in ~14 ms, cached for the
JVM lifetime, and raises the reported value 0-3 C across the dataset.

The naming mask is derived from data rather than assumed. The third character is
always a digit, but the fourth is uppercase in only 42% of published keys,
lowercase in 43% and a digit in 15%, so ^Tg[0-9][0-9A-Za-z]$ matches all 100
known GPU keys where a mask requiring an uppercase fourth character matches 42
and misses Tg0f - the only one of the original four present on this hardware.

Notes on the design:

- The index logic lives in oshi-common rather than SmcUtil, whose static
  IOKit.INSTANCE field makes any of its members unloadable off a Mac. Passing an
  IntFunction keeps the two connection handle types out of the shared code and
  lets the binary search, mask, config parsing and aggregation be unit tested on
  any OS; that is where the edge cases are.
- Discovery caches which keys *exist*, not which currently read plausibly.
  Existence is a property of the hardware; plausibility is not, because an idle
  sensor reports a sentinel below ambient. Filtering at discovery time would let
  one unlucky first call cache an empty set and disable GPU temperature for the
  lifetime of the JVM. Plausibility is applied per read instead.
- Not memoized with Memoizer, which caches whatever the supplier returned
  including a failure; a transient smcOpen failure would be permanent. A failed
  discovery falls back without caching so a later call retries.
- No data-type filter. smcGetFloat already decodes every temperature encoding
  the SMC uses and returns 0 otherwise, which the plausibility floor rejects, so
  the check cost a second read per key and would have wrongly excluded a sensor
  reported as sp78.
- Maximum rather than average. Each cluster exposes a pair of sensors at
  different die locations, offset a few degrees; averaging the discovered set
  would combine two different measurements, and separating them needs the
  per-chip table this avoids. Verified the pair is not instantaneous/peak-hold:
  both members rose 44.8/51.4 to 56.1/62.6 under load and fell together
  afterwards, so the maximum tracks the hotter location, not a latched peak.

SMC_KEYS_GPU_TEMP_AS is kept as the fallback for a machine whose index cannot be
read, widened from 4 to the 14 keys most common across published M1 through M5
and A18 sensor dumps.

The Intel IOAccelerator Temperature(C) fallback is absent on Apple Silicon, so
it is now tried once per card and latched off rather than repeating an IOKit
registry walk on every call. Keyed by card, since one card lacking the sensor
says nothing about another.

SmcDump now uses the new enumeration primitive instead of its own copy.

Verified on an M2 Max: discovery finds all 16 keys, getTemperature tracks an
idle to Metal load to idle cycle at 47.8 / 66.5 / 55.1 C, and the JNA and FFM
backends discover identical key lists.
Same discovery, cache and aggregation as the JNA twin, so
NativeComparisonTest stays green. Kept as a separate commit so the twin diff
reviews side by side.

The new surface needed no private-to-public promotion in SmcUtilFFM: every
method returns String, List or double, so no MemorySegment or Arena leaks into
the exported package. Implemented with ForeignFunctions.callInArenaOrDefault,
using the MacSystem.SMC_DATA32 layout element that already existed.

Adds a logger to MacGpuStatsFFM, which unlike its JNA twin had none.

NativeComparisonTest gains gpuTemperatureKeys(), asserting the two backends
discover identical key lists. Since each runs its own binary search over the SMC
index, list equality is the sharpest available check that they agree.
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5f7afa92-00c9-4beb-853e-c79f6bfb499e

📥 Commits

Reviewing files that changed from the base of the PR and between 2e5e09d and b6bebb4.

📒 Files selected for processing (2)
  • oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java
  • oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java
  • oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (7)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)

📝 Walkthrough

Walkthrough

Apple Silicon GPU temperature handling now discovers SMC keys at runtime, supports configured overrides, selects the hottest plausible GPU reading, and shares discovery helpers across JNA and FFM implementations. Tests cover indexing, hardware behavior, backend parity, and missing IOAccelerator temperature keys.

Changes

GPU temperature discovery

Layer / File(s) Summary
Shared SMC key-index utilities
oshi-common/src/main/java/oshi/util/common/platform/mac/*, oshi-common/src/test/java/oshi/util/common/platform/mac/*, oshi-common/src/main/java/oshi/util/GlobalConfig.java, oshi-common/src/main/resources/oshi.properties
Adds bounded SMC index lookup, GPU-key validation, configured-key parsing, maximum-plausible aggregation, configuration properties, module exports, and unit coverage.
JNA and FFM GPU key discovery
oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java, oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java, oshi-demo/src/main/java/oshi/demo/SmcDump.java, CHANGELOG.md
Adds lazy discovery, caching, fallback keys, configuration overrides, SMC metadata helpers, and shared demo usage.
Temperature selection and absence handling
oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java, oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java, oshi-core/src/test/java/oshi/util/platform/mac/*, oshi-core-ffm/src/test/java/oshi/ffm/*, oshi-benchmark/src/test/java/oshi/comparison/*
Uses maximum plausible GPU temperatures, caches structurally absent IOAccelerator temperature keys per card, and validates discovery, plausibility, caching, and backend parity.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MacGpuStats
  participant SmcUtil
  participant SmcKeyIndex
  participant AppleSMC
  MacGpuStats->>SmcUtil: getGpuTemperatureKeys()
  SmcUtil->>AppleSMC: read `#KEY` and indexed key names
  SmcUtil->>SmcKeyIndex: findKeys(Tg, GPU key predicate)
  SmcKeyIndex-->>SmcUtil: discovered key list
  SmcUtil->>AppleSMC: read GPU temperatures
  SmcUtil-->>MacGpuStats: maximum plausible temperature
Loading

Possibly related PRs

  • oshi/oshi#3091: Shares the Apple Silicon SMC GPU temperature and SmcDump key-enumeration code paths.
  • oshi/oshi#3109: Provides the FFM SMC access foundation extended by GPU key discovery.
  • oshi/oshi#3531: Shares the plausibility filtering used by GPU temperature selection.

Poem

A rabbit found keys in the SMC,
And chose the hottest GPU to see.
JNA and FFM shared the trail,
While fallback lists stood by the rail.
“Discover!” the bunny cried with glee—
“Let runtime temperatures hop free!”

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.33% 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 change: runtime discovery of Apple Silicon GPU temperature SMC keys.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@codecov

codecov Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.83784% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.85%. Comparing base (1c3ca5a) to head (b6bebb4).

Files with missing lines Patch % Lines
...ava/oshi/util/common/platform/mac/SmcKeyIndex.java 87.83% 3 Missing and 6 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3536      +/-   ##
============================================
- Coverage     78.87%   78.85%   -0.03%     
- Complexity     3621     3838     +217     
============================================
  Files           698      699       +1     
  Lines         24008    24082      +74     
  Branches       3963     3985      +22     
============================================
+ Hits          18937    18989      +52     
- Misses         2886     2899      +13     
- Partials       2185     2194       +9     
Flag Coverage Δ
linux 35.42% <87.83%> (+0.16%) ⬆️
macos 36.36% <87.83%> (+0.11%) ⬆️
windows 43.63% <87.83%> (+0.12%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 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

🤖 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/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java`:
- Around line 197-201: Remove the PERF_STATS_TEMP_ABSENT.add(normCardName) call
from the null perfStats branch in MacGpuStatsJNA.java at lines 197-201 and
MacGpuStatsFFM.java at lines 189-193. Keep returning -1d for transient
queryPerfStats() misses, and retain latching only when the temperature key is
confirmed absent.

In `@oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java`:
- Around line 79-90: Ensure the fallback GPU temperature key lists include the
documented M2 Max sensor key "Tg0f". Add it beside "Tg0j" in
SMC_KEYS_GPU_TEMP_AS in
oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java (lines 79-90) and
the corresponding list in
oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java (lines
94-105), keeping both backends identical.
🪄 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: 48505d0d-1c8f-4a44-acd6-428d4d5c32da

📥 Commits

Reviewing files that changed from the base of the PR and between 1c3ca5a and 37bc126.

📒 Files selected for processing (15)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
  • oshi-common/src/main/java/module-info.java
  • oshi-common/src/main/java/oshi/util/GlobalConfig.java
  • oshi-common/src/main/java/oshi/util/common/platform/mac/SmcKeyIndex.java
  • oshi-common/src/main/java/oshi/util/common/platform/mac/package-info.java
  • oshi-common/src/main/resources/oshi.properties
  • oshi-common/src/test/java/oshi/util/common/platform/mac/SmcKeyIndexTest.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
  • oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java
  • oshi-demo/src/main/java/oshi/demo/SmcDump.java
📜 Review details
⏰ Context from checks skipped due to timeout. (6)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
🧰 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/util/common/platform/mac/package-info.java
  • oshi-common/src/main/java/oshi/util/GlobalConfig.java
  • oshi-common/src/main/java/oshi/util/common/platform/mac/SmcKeyIndex.java
  • oshi-common/src/main/java/module-info.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/platform/mac/package-info.java
  • oshi-common/src/main/java/oshi/util/GlobalConfig.java
  • oshi-common/src/main/java/oshi/util/common/platform/mac/SmcKeyIndex.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-demo/src/main/java/oshi/demo/SmcDump.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
🔇 Additional comments (19)
oshi-common/src/main/java/module-info.java (1)

61-61: LGTM!

oshi-common/src/main/java/oshi/util/common/platform/mac/SmcKeyIndex.java (3)

75-116: LGTM!


126-175: LGTM!


183-237: LGTM!

oshi-common/src/main/java/oshi/util/common/platform/mac/package-info.java (1)

1-9: LGTM!

oshi-common/src/main/resources/oshi.properties (1)

305-311: LGTM!

oshi-common/src/test/java/oshi/util/common/platform/mac/SmcKeyIndexTest.java (1)

1-219: LGTM!

oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java (1)

12-29: LGTM!

Also applies to: 116-169

oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java (1)

12-28: LGTM!

Also applies to: 114-168

oshi-common/src/main/java/oshi/util/GlobalConfig.java (1)

159-164: LGTM!

oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java (1)

92-113: LGTM!

Also applies to: 234-274, 276-297, 299-360

oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java (1)

107-128: LGTM!

Also applies to: 257-325, 327-387

oshi-demo/src/main/java/oshi/demo/SmcDump.java (1)

43-49: LGTM!

CHANGELOG.md (1)

9-9: LGTM!

oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java (2)

57-63: LGTM!

Also applies to: 181-181


202-213: LGTM!

oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java (2)

52-61: LGTM!

Also applies to: 173-173


194-205: LGTM!

oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)

343-351: LGTM!

Widening the fallback by frequency across published sensor dumps used a
threshold of four machines, which silently dropped Tg0f - one of the four keys
OSHI read before this PR, and the only one of them present on the M2 Max this
work was verified on. The widened list was therefore a regression on that
hardware whenever discovery could not complete. The list now leads with all four
historical keys, and a test asserts that so it cannot happen again.

Also stops latching the IOAccelerator temperature lookup when queryPerfStats()
itself returns null. That means no matching accelerator entry was found, which
can be transient - a driver reset or an unplugged eGPU - and latching would
disable the sensor for the rest of the JVM. Latch only when the dictionary is
present and has no Temperature(C) key, which is the structural case and the one
that actually occurs on Apple Silicon.
@dbwiddis

Copy link
Copy Markdown
Member Author

Both valid, both fixed in 2e5e09d.

Tg0f missing from the fallback — a regression I introduced

This one was a real bug, not a nit. Widening the fallback list used "keys appearing on at least 4 of the 13 machines in the corpus", and Tg0f falls below that threshold — so widening the list dropped one of the four keys OSHI shipped before this PR, and specifically the only one of the four present on the M2 Max this work was verified on. Whenever discovery could not complete, the new fallback would have reported less than the old hardcoded list on that hardware.

The list now leads with all four historical keys and then the frequency-derived additions:

"Tg05", "Tg0D", "Tg0f", "Tg0j",   // the four read before discovery existed
"Tg0C", "Tg04", "Tg0K", "Tg0L", "Tg0d", "Tg0e", "Tg1k", "Tg0X", "Tg0S", "Tg0y", "Tg0z"

Added testFallbackKeysIncludeTheHistoricalFour to both twins so the fallback can never again be narrowed below the previous behaviour. Ordering is cosmetic now that the aggregation is a max rather than first-match, but leading with the historical four makes the superset property obvious at a glance.

Latching on a null queryPerfStats()

Agreed, and the distinction is the one the plan intended but the code overshot. A null return means no matching IOAccelerator entry was found, which can be transient — a driver reset, an unplugged eGPU — whereas a dictionary that is present but has no Temperature(C) key is structural. Latching the former would disable the sensor for the rest of the JVM on a recoverable condition.

Now latched only on the structural case, which is also the one that actually occurs on Apple Silicon: PerformanceStatistics is present there and simply has no Temperature(C) key, so the common path still latches after one attempt.

Full reactor green (1146 / 96 / 81 / 30), and -Pnative-comparison still passes sensors() and gpuTemperatureKeys().

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java (1)

123-129: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not require list identity on the retryable discovery path.

These tests call discovery without first confirming SMC availability, then require the second call to return the same List instance. If the first discovery fails transiently, the implementation must retry rather than cache that failure, so a later successful call may legitimately return a different list and these tests will fail on valid macOS environments.

Test cache identity only after a confirmed successful discovery, or assert stable contents while separately verifying retry behavior.

🤖 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/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java`
around lines 123 - 129, The GPU temperature discovery tests should not require
list identity when discovery may have failed transiently. In
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java
lines 123-129 and
oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java lines
121-129, update testGpuTemperatureKeysAreDiscovered to verify cache identity
only after confirmed successful discovery, or replace the unconditional
sameInstance assertion with stable-content and retry-behavior checks.
🤖 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.

Outside diff comments:
In
`@oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java`:
- Around line 123-129: The GPU temperature discovery tests should not require
list identity when discovery may have failed transiently. In
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java
lines 123-129 and
oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java lines
121-129, update testGpuTemperatureKeysAreDiscovered to verify cache identity
only after confirmed successful discovery, or replace the unconditional
sameInstance assertion with stable-content and retry-behavior checks.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 931d3047-9d7c-4956-bcea-216e60821cc7

📥 Commits

Reviewing files that changed from the base of the PR and between 37bc126 and 2e5e09d.

📒 Files selected for processing (6)
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
  • oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java
🚧 Files skipped from review as they are similar to previous changes (4)
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
📜 Review details
⏰ Context from checks skipped due to timeout. (6)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🔇 Additional comments (4)
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java (2)

13-13: LGTM!


137-150: LGTM!

Also applies to: 157-170, 172-180

oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java (2)

13-13: LGTM!


136-149: LGTM!

Also applies to: 156-169, 171-179

testGpuTemperatureKeysAreDiscovered asserted that two calls return the same List
instance, described as proving the result is cached. That assertion passes
vacuously on the path worth checking: when discovery cannot complete, both calls
return the shared SMC_KEYS_GPU_TEMP_AS constant, so identity holds even though
nothing was cached. It also had a narrow flake window, since a first call that
failed followed by one that succeeded would return different instances.

Now asserts that repeated calls agree on content unconditionally, and asserts
instance identity only when the result is not the fallback constant, which is
exactly the case where caching was supposed to happen.
@dbwiddis

Copy link
Copy Markdown
Member Author

Fixed in a9f2e3c. Valid, though the more interesting problem is not the flake window.

The assertion claimed to prove the result is cached, but it passes vacuously on exactly the path worth checking: when discovery cannot complete, getGpuTemperatureKeys() deliberately returns the shared SMC_KEYS_GPU_TEMP_AS constant without caching, so both calls return the same instance and sameInstance holds even though nothing was cached. The test would have reported success on a machine where caching never happened.

The flake window you identified is real too, just narrow — a first call that fails followed by one that succeeds returns different instances.

Now:

List<String> second = SmcUtil.getGpuTemperatureKeys();
assertThat("Repeated calls must agree", second, is(equalTo(keys)));
// A completed discovery is cached; a failed one deliberately is not, and returns the shared fallback
// constant instead. Asserting identity unconditionally would pass vacuously in that case.
if (!keys.equals(SmcUtil.SMC_KEYS_GPU_TEMP_AS)) {
    assertThat("A completed discovery must be cached, not repeated", second, is(sameInstance(keys)));
}

Content stability is checked unconditionally; identity only where caching was supposed to occur. Mirrored in both twins. Full reactor green (1146 / 96 / 81 / 30).

@dbwiddis
dbwiddis merged commit 2c72f54 into oshi:master Jul 27, 2026
15 of 16 checks passed
@dbwiddis
dbwiddis deleted the fix-3534-gpu-smc-key-discovery branch July 27, 2026 23:04
dbwiddis added a commit that referenced this pull request Jul 29, 2026
* Harden the macOS SMC fan speed and CPU voltage paths

The temperature work in #3531, #3535 and #3536 left behind a generic key
index scanner, a plausibility guard idiom and a config override pattern.
The fan and voltage paths were never revisited and still read single
hardcoded keys with no discovery, no plausibility guard and no test
coverage. This applies that machinery to both.

Fan speeds came from FNum alone: read the count, then format F%dAc for
each index. That is a latent bug for a count of eleven or more, because
String.format("F%dAc", 10) produces the five-character "F10Ac" and
smcReadKey passes the key through ParseUtil.strToLong(key, 4), which
reads only the first four bytes. "F10Ac" and "F10A" both encode to
0x46313041, so a corrupt or spoofed FNum makes OSHI read a different key
and report its value as a fan speed, with no exception and no log. Keys
are now discovered from the sorted key index, as the GPU keys are, and
reconciled against FNum: discovery is authoritative where it found
anything, a positive FNum still implies the conventionally named keys
where it did not, and MAX_FANS bounds the synthesis so every key stays
four characters. The count is scanned rather than probed directly
because smcGetDataType returns an empty string for both "absent" and
"read failed", and findKeys already distinguishes those.

CPU voltage read VP0C, then VC0C/1000 if that returned zero, with the
divisor tied to the key rather than to its encoding. It is now scaled
from the key's SMC data type and held to a plausibility floor. fpe2 is
fourteen integer and two fractional bits, so it resolves to a quarter of
a unit: read as volts a 1.2 V core rail could only be expressed as 1.00
or 1.25, while read as millivolts it resolves to 0.25 mV over 0 to
16.4 V. Millivolts is the only self-consistent reading, so the existing
divisor is kept, now derived from the type so a key whose encoding
differs from the one expected still reads correctly. The floor makes the
choice fail safe either way: a wrongly divided reading lands near
0.0012 V and is rejected as unavailable rather than returned as a
believable wrong number.

Voltage keys are deliberately not discovered, unlike the fan and GPU
keys. Tg is a semantic prefix, where every match is a GPU cluster
sensor; V is not. An M3 Pro's V block mixes a 0.75 V core voltage from
VP0C with a 20.2 V supply rail from VD0R and a 0.86 V VPsC, under no
naming rule that separates them, so a prefix scan could report a rail
voltage as the CPU's. That is worse than reporting nothing, so the two
named keys stay and oshi.os.mac.sensors.cpuvoltage.keys is the escape
hatch, handing the guess to the user rather than making it in OSHI. A
test asserts the defaults are unchanged so the pattern is not "completed"
later.

New in oshi-common, so both backends share it and it is testable off a
Mac: SmcKeyIndex gains isFanSpeedKey, MAX_FANS, fanSpeedKeys and
reconcileFanKeys, and a new SmcSensorValues holds toRpm, the voltage
floor and scaleVoltage.

toRpm preserves a zero reading rather than discarding it. iSMC drops
readings below 0.005, which applied here would drop both fans on an idle
M3 Pro, where F0Ac and F1Ac read 0.0 while F0Mn and F0Mx report 1350 and
5349: the fans are present and readable but not spinning. Sensors
documents an empty array as "no fans detected" and a zero entry as "a
fan reading zero or unmeasurable", so dropping them would turn two
stopped fans into no fans.

Also removes the per-instance numFans field. The key list in SmcUtil is
now the single process-wide cache, matching gpuTemperatureKeys, and
queryFanSpeeds resolves it before opening a connection because discovery
opens its own.

No CHANGELOG: on testable hardware nothing changes. The FNum truncation
is only reachable through a corrupt or spoofed fan count, and the
voltage scaling is unchanged for every data type observed. Verified on
an M3 Pro (Mac15,7, macOS 26.5.2): FNum reads 2, getFanSpeeds returns
[0, 0] before and after, and getCpuVoltage reads a plausible core
voltage on both backends. The Intel fpe2 branch and every non-M3-Pro fan
topology are untested for want of hardware.

The two new properties are documented in oshi.properties. New tests:
eight fan cases in SmcKeyIndexTest including both null-versus-empty rows
of reconcileFanKeys and a case pinning every synthesized key at four
characters, a new SmcSensorValuesTest, eight matching cases in each of
the MacSensorsPlausibility twins, and a fanSpeedKeys comparison in
NativeComparisonTest. That last one compares the two backends'
discovered key lists, which is sharper than comparing rpm; the fan
readings themselves are only compared when both are nonzero, since a fan
spinning up between the sequential JNA and FFM reads would otherwise
fail assertWithinRatio's one-value-zero branch.

* Derive the fan max key from the discovered key, not the loop index

Both MacSensorsPlausibility twins built the F%dMx hardware-maximum key from
the loop index, which assumes fan numbering is contiguous from F0Ac. Discovery
returns keys in index order, so a machine numbering its fans non-contiguously
would have been compared against a different fan's maximum. Take the digit
from the discovered key itself instead.

Test-only; no production behavior change. Reported by CodeRabbit on #3545.
dbwiddis added a commit that referenced this pull request Jul 30, 2026
* Share the SMC key resolution between the two backends

The sensor work in #3531, #3535, #3536 and #3545 grew SmcUtil and
SmcUtilFFM in parallel, and Sonar reported 253 duplicated lines between
them. All of it was in key-list management rather than the native calls.

Both backends had the same three-step resolution twice over, once for GPU
temperature and once for fan speeds: a configuration property naming the
keys outright, then discovery from the key index, then a fallback that
must not be cached so a later call retries. That is four copies of the
same double-checked-locking skeleton, four volatile fields and four S3077
suppressions. It is now one SmcKeyCache in oshi-common, so each backend
supplies only the discovery, and three of those suppressions are gone.

smcGetFirstTemperature and smcGetFirstVoltage were both first-plausible
scans over a key list, differing only in how a reading is obtained: the
voltage path needs a second read for the key's data type in order to
scale it. Moving the scan to SmcKeyIndex.firstPlausible, symmetric with
the maxPlausible already there, leaves each backend with just the read.

SmcUtil drops from 596 to 518 lines and SmcUtilFFM from 622 to 545, with
no change to the public surface of either.

Adding a test to oshi.util.common.platform.mac needed an opens line in
module-info.test, which the package had never had. That is why the two
existing tests there were public and carried S5786 suppressions claiming
JPMS required it. With the package opened that is no longer true, so both
are now package-private and both suppressions are removed.

* Stop the voltage test attributing a missing key to Intel

The assumption skipped with "VP0C unavailable (Intel)", inferring the
chip from the key's absence. That inference is wrong: VP0C reads 0.75 V
on an M3 Pro but is absent on an M2 Max, so the test skips on Apple
Silicon while reporting Intel, which is what hid that getCpuVoltage
returns 0 on that machine.

The skip itself is right, since there is nothing to assert when the key
does not exist. Only the stated reason changes, to name the absent key
rather than guess the hardware. A sweep of all 53 V keys on the M2 Max
found no identified core voltage, so 0 may well be the correct answer
there; that is worth its own investigation rather than a key added on one
machine's evidence.
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.

1 participant