Skip to content

Read Apple Silicon CPU temp from SMC die-aggregate keys - #3535

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:fix-3534-smc-cpu-die-aggregate
Jul 27, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:fix-3534-smc-cpu-die-aggregate

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #3534. OSHI read the macOS CPU temperature from five hardcoded per-core SMC FourCC keys (Tp09, Tp0T, Tp01, Tp05, Tp0D). These are chip-specific, and all five are absent on the M3 Pro (which exposes a different set: Tp06/Tp0E…, Te0…, Tp3P/Tp3X/Tp3T), so Sensors#getCpuTemperature() returned 0.

This reads the chip-independent, firmware-computed CPU-die aggregate keys that the SMC already exposes:

  • TCMb — CPU die average, preferred as primary
  • TCMz — CPU die max, secondary

Both are flt type and decode through the existing smcGetFirstTemperature path, which already applies the 15 °C plausibility floor from #3531 — no new native binding and no private API. This supersedes the IOHID-fallback idea explored in the issue: across every chip in the iSMC hardware dataset (M1→M5, A18, Intel T2) a usable SMC CPU key is always present — even the M3 Pro, which lacks the per-core keys, still exposes TCMb/TCMz — so IOHID would only have defended a case that does not occur, at the cost of undocumented private-API bindings reading a different (die-diode) sensor ~20-30 °C lower.

TCMb is preferred so the reported value stays close to the historical single-core reading rather than jumping ~20 °C to the die max.

New query order in queryCpuTemperature (both backends):

  1. SMC CPU-die aggregate keys — TCMb then TCMz (plausibility-guarded)
  2. SMC per-core keys (existing SMC_KEYS_CPU_TEMP_AS) — unchanged
  3. Intel TC0P — unchanged, plausibility-guarded

Scope: CPU temperature only. GPU is deferred to a follow-up — it has no analogous TGM* die aggregate, and MacGpuStats.getTemperature() already has a key-independent IOAccelerator fallback.

Changes

Changed in lockstep across the JNA (oshi-core) and FFM (oshi-core-ffm) backends so NativeComparisonTest.sensors() stays green:

  • SmcUtil / SmcUtilFFM — add SMC_KEYS_CPU_TEMP_AGGREGATE_AS = [TCMb, TCMz]
  • MacSensorsJNA / MacSensorsFFM — try the aggregate keys before the per-core keys
  • New JNA MacSensorsPlausibilityTest (twin of the existing FFM test) + an aggregate-keys-average-first contract test in both

Verification

  • mvn -pl oshi-core -am clean test — 1127 passed
  • mvn -pl oshi-core-ffm -am clean test — 1127 passed
  • mvn test -pl oshi-benchmark -Pnative-comparison — NativeComparisonTest.sensors() passes (FFM within 25% of JNA)
  • Real M3 Pro hardware (Mac15,7, macOS 26.5.2, JDK 26): getCpuTemperature() went from 0 → the TCMb value on both backends (paired same-JVM read: JNA TCMb=72.117 → getCpuTemperature()=72.117; FFM TCMb=73.521 → getCpuTemperature()=73.521), confirming it tracks the die average and not TCMz or 0.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed CPU temperature reporting on Apple Silicon so Sensors#getCpuTemperature no longer incorrectly returns 0 for chips with differing SMC CPU-die keys.
    • Improved temperature detection by prioritizing chip-independent aggregate CPU-die readings, with fallback to existing per-core readings.
    • Ensured implausible temperature sentinel values are not reported as valid readings.
  • Tests
    • Added/expanded tests to verify aggregate-key preference and plausibility handling for macOS CPU temperature.

@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: 0bebd1f5-0439-4181-895c-e908d9d64d38

📥 Commits

Reviewing files that changed from the base of the PR and between 0de069d and d487a85.

📒 Files selected for processing (7)
  • CHANGELOG.md
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
  • oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.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 (7)
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java
  • oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
  • CHANGELOG.md
  • oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (6)
  • GitHub Check: Analyze (java)
  • 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)

📝 Walkthrough

Walkthrough

Apple Silicon CPU temperature detection now probes firmware-computed aggregate CPU-die SMC keys before existing per-core keys in both JNA and FFM implementations. New macOS tests cover plausibility and key precedence, and the changelog records the fix.

Changes

Apple Silicon CPU temperature

Layer / File(s) Summary
Aggregate temperature key definitions
oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java, oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java
Adds ordered aggregate keys TCMb and TCMz, preferring average before maximum readings.
Aggregate-first sensor queries
oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.java, oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
Queries aggregate CPU-die temperatures first and falls back to existing per-core keys when no positive aggregate value is returned.
Plausibility and precedence validation
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java, oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java, CHANGELOG.md
Tests sentinel rejection, genuine readings, end-to-end CPU temperature plausibility, and aggregate-key ordering; documents the fix for issue 3535.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SystemInfo
  participant MacSensors
  participant SMC
  SystemInfo->>MacSensors: queryCpuTemperature()
  MacSensors->>SMC: read TCMb, then TCMz
  SMC-->>MacSensors: aggregate CPU-die temperature
  MacSensors->>SMC: read per-core keys if aggregate value is non-positive
  SMC-->>MacSensors: fallback temperature or unavailable
  MacSensors-->>SystemInfo: plausible temperature or unavailable
Loading

Possibly related PRs

  • oshi/oshi#3091: Added earlier Apple Silicon CPU temperature SMC-key support in the same code paths.
  • oshi/oshi#3398: Refactored SMC key constants and list-based temperature lookup used by this change.
  • oshi/oshi#3531: Added the plausibility guard used when selecting SMC temperature readings.

Poem

A bunny hops where cool chips gleam,
TCMb leads the thermal dream.
If TCMz waits, it joins the queue,
Per-core keys are fallback crew.
No more zero on silicon bright—
The sensors now report just right! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% 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 matches the main change: switching Apple Silicon CPU temperature reads to die-aggregate SMC keys.
Linked Issues check ✅ Passed The PR meets #3534 by preferring chip-independent aggregate keys first while keeping the existing plausibility and fallback behavior.
Out of Scope Changes check ✅ Passed The changes stay within scope, covering the new key constants, temperature query updates, changelog, and related tests.
✨ 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

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.82%. Comparing base (0ffc4fb) to head (d487a85).

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3535      +/-   ##
============================================
- Coverage     78.86%   78.82%   -0.04%     
- Complexity       76     3836    +3760     
============================================
  Files           698      698              
  Lines         24008    24008              
  Branches       3963     3963              
============================================
- Hits          18934    18925       -9     
- Misses         2886     2893       +7     
- Partials       2188     2190       +2     
Flag Coverage Δ
linux 35.26% <ø> (-0.01%) ⬇️
macos 36.21% <ø> (-0.04%) ⬇️
windows 43.49% <ø> (+0.01%) ⬆️

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: 1

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

100-105: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Exercise query selection, not just constant ordering.

These assertions pass even if either queryCpuTemperature() stops using aggregate keys or probes per-core keys first. Add deterministic SMC-read test seams that verify TCMb wins over TCMz and per-core values, and that unavailable aggregate readings fall back correctly.

  • oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java#L100-L105: test JNA aggregate-first selection and fallback behavior.
  • oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java#L100-L106: add the equivalent FFM behavior test.
🤖 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 100 - 105, The current tests only verify aggregate-key ordering,
not query selection. In
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java:100-105,
add deterministic SMC-read seams covering queryCpuTemperature() so TCMb is
selected before TCMz and per-core values, with unavailable aggregate readings
falling back correctly; in
oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java:100-106,
add the equivalent FFM behavior test. Preserve the existing key-order and
distinctness assertions.
🤖 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 `@CHANGELOG.md`:
- Line 8: Update the CHANGELOG entry describing Sensors#getCpuTemperature to
state that the firmware-computed die average key TCMb is preferred when
available, while TCMz or a per-core value may be returned when the average is
unavailable or implausible; do not imply TCMb is always returned.

---

Nitpick comments:
In
`@oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java`:
- Around line 100-105: The current tests only verify aggregate-key ordering, not
query selection. In
oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java:100-105,
add deterministic SMC-read seams covering queryCpuTemperature() so TCMb is
selected before TCMz and per-core values, with unavailable aggregate readings
falling back correctly; in
oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java:100-106,
add the equivalent FFM behavior test. Preserve the existing key-order and
distinctness assertions.
🪄 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: e837ec80-1a1c-4461-b70c-2f85de5444da

📥 Commits

Reviewing files that changed from the base of the PR and between 0ffc4fb and 0de069d.

📒 Files selected for processing (7)
  • CHANGELOG.md
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
  • oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-core/src/test/java/oshi/util/platform/mac/MacSensorsPlausibilityTest.java
📜 Review details
⏰ Context from checks skipped due to timeout. (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
🧰 Additional context used
🧠 Learnings (2)
📚 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-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
  • oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.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/MacSensorsJNA.java
🔇 Additional comments (6)
oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java (1)

65-73: LGTM!

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

79-86: LGTM!

oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.java (1)

7-7: LGTM!

Also applies to: 38-43

oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java (1)

7-7: LGTM!

Also applies to: 36-41

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

1-92: LGTM!

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

8-8: LGTM!

Comment thread CHANGELOG.md Resolved
OSHI read the macOS CPU temperature from five hardcoded per-core SMC
FourCC keys (Tp09, Tp0T, Tp01, Tp05, Tp0D). These are chip-specific and
all five are absent on the M3 Pro, so getCpuTemperature() returned 0.

Prefer the chip-independent, firmware-computed CPU-die aggregate keys
TCMb (die average) then TCMz (die max) before the per-core keys. Both
are flt type and decode through the existing smcGetFirstTemperature
path, which already applies the 15C plausibility floor from #3531 - no
new native binding or private API. TCMb is preferred so the reported
value stays close to the historical single-core reading (verified on an
M3 Pro: getCpuTemperature() == TCMb, both JNA and FFM backends).

Changed in lockstep across the JNA (oshi-core) and FFM (oshi-core-ffm)
backends so NativeComparisonTest.sensors() stays green. Adds a JNA twin
of the FFM plausibility test and an aggregate-keys-average-first
contract test to both.
@dbwiddis
dbwiddis force-pushed the fix-3534-smc-cpu-die-aggregate branch from 0de069d to d487a85 Compare July 27, 2026 18:46
@dbwiddis

Copy link
Copy Markdown
Member Author

Verified on M2 Max (Mac14,6, macOS 15, JDK 25). Works, and it does more here than fix the M3 case.

The aggregate keys stay live exactly where the per-core keys park

This is the machine where #3529/#3531 was diagnosed, so it has the idle-gating behaviour. At genuine deep idle the per-core keys are parked at their sentinels, but TCMb/TCMz read normally:

state   | TCMb(avg) TCMz(max) | Tp09      Tp01      Tp05      | getCpuTemperature()
--------------------------------------------------------------------------------------
IDLE    | 41.122    42.369    | 6.700     6.700     4.633     | 41.122
IDLE    | 42.905    53.659    | 6.700     6.700     4.633     | 42.905
IDLE    | 41.013    42.369    | 6.700     6.700     4.633     | 41.013
LOADED  | 48.148    53.159    | 46.859    47.473    45.308    | 48.148
LOADED  | 48.672    53.441    | 47.457    47.871    45.642    | 48.672
IDLE2   | 42.030    43.431    | 6.700     6.700     4.633     | 42.030
IDLE2   | 42.348    46.753    | 6.700     6.700     4.633     | 42.348

getCpuTemperature() returns the TCMb value in every row, confirming the aggregate-first ordering and that it is the average rather than TCMz.

This also recovers the idle behaviour #3531 had to give up. Before this PR an idle M2 Max reported unavailable, correctly, because every per-core key was parked. Now it reports a real ~41 °C. So the aggregate keys are not merely chip-independent — on this hardware they are immune to the cluster gating that caused the original bug.

Both backends agree exactly

IDLE    JNA=40.051  FFM=40.051  delta=0.000
IDLE    JNA=40.930  FFM=40.930  delta=0.000
LOADED  JNA=47.309  FFM=47.309  delta=0.000
LOADED  JNA=47.841  FFM=47.841  delta=0.000
  • ./mvnw clean install — full reactor green (1127 / 92 / 77 / 30)
  • ./mvnw test -pl oshi-benchmark -Pnative-comparison — sensors() [OK], 39 passed

One small correction to the description

The rationale says IOHID reads "~20-30 °C lower". On M2 Max, measured at the same moment, it is a smaller gap:

SMC  TCMb            40.5 .. 46.3
HID  PMU tdie* avg   34.3 .. 34.5

So ~6-12 °C here rather than 20-30. The direction is right and the conclusion is unaffected — the SMC path needs no private-API bindings and works on every chip in the dataset — but the magnitude may be M3-specific and might be worth softening to "reads lower" rather than a specific range.

LGTM otherwise.

@dbwiddis
dbwiddis merged commit 1c3ca5a into oshi:master Jul 27, 2026
16 checks passed
@dbwiddis
dbwiddis deleted the fix-3534-smc-cpu-die-aggregate branch July 27, 2026 20:39
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.

macOS: hardcoded Apple Silicon CPU temperature keys are wrong or absent on M1, M3 and M5

1 participant