Skip to content

Reject implausible Apple Silicon SMC temperatures - #3531

Merged
dbwiddis merged 4 commits into
oshi:masterfrom
dbwiddis:mac-smc-implausible-temperature
Jul 27, 2026
Merged

dbwiddis merged 4 commits into
oshi:masterfrom
dbwiddis:mac-smc-implausible-temperature

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

Fixes #3529.

Apple Silicon power-gates a CPU core cluster when it is idle. The SMC then reports a fixed parked value for each die sensor in that cluster instead of a reading — on an M2 Max, 6.7 °C for Tp01/Tp09 and 4.633 °C for Tp05/Tp0D. Those are below room ambient and cannot be die temperatures, but they are positive, so the > 0 test in smcGetFirstFloat accepted them. On a genuinely idle Mac, getCpuTemperature() reported 6.7 °C.

The change

smcGetFirstFloat becomes smcGetFirstTemperature and requires a reading of at least MIN_PLAUSIBLE_TEMPERATURE (20 °C), returning 0 for unavailable per the documented Sensors contract. The Intel TC0P fallback is held to the same floor. Applied to the JNA and FFM twins, and to the GPU path which shares the helper.

Verified on an M2 Max, identical on both implementations:

IDLE    getCpuTemperature() = 0.000    <- reported UNAVAILABLE
LOADED  getCpuTemperature() = 49.339

Why this shape, and not the alternatives

Everything below was measured on hardware rather than reasoned about; details and raw output are in #3529.

  • Not an FFM/JNA divergence. That was my original (wrong) diagnosis in the issue. Both implementations read byte-identical SMC payloads and agreed on all 19 interleaved samples — both were equally affected.
  • Not nondeterminism. The value tracks P-cluster power state exactly and reversibly. Sustained load brings the sensors live within ~1.6 s; they park again ~1.5 s after it stops. That is the entire explanation for the apparent run-to-run flakiness.
  • Retry rejected. At deep idle the parked state is 100% persistent across 40 samples, and a second read recovered 0/15 at delays of 0, 10, 50, 200 and 1000 ms. Even forcing 150 ms of CPU work first recovered 0/10 — one busy thread lands on an E-core, so the P-cluster stays gated.
  • Max-instead-of-first rejected. All five keys are one power domain and park together, so max(6.70, 0, 6.70, 4.63, 4.63) is still 6.70 — no better than the current behaviour.
  • Outlier/median detection rejected. Across 224 samples spanning a full idle→load→idle transition there were 0 mixed sets: the keys are always all parked or all live, so there is never a good reading to compare an outlier against.
  • Extending the key list rejected. Tp1* park too at genuine idle; they only looked live in an earlier sample taken on a still-warm machine.

On the floor, and the absence of a ceiling

The floor is a plausibility guard, not a hardware specification, and is documented as such. A sweep of all 288 temperature sensors found parked values from 0 to 16.6 °C, while idle Apple Silicon runs about 28–35 °C — so 20 °C clears every observed parked value with margin below any genuine reading.

There is deliberately no upper bound. Every bad value observed was at the low end (full range across all sensors: −68 to +80.28 °C), and there is no published Apple Tjmax to anchor one — the Linux kernel's Apple SMC hwmon driver applies no temperature validation at all. A ceiling near the ~100 °C throttling point risks discarding real readings exactly when they matter most.

Behaviour change

Users on an idle Apple Silicon Mac will now see 0 (unavailable) where they previously saw a confident 6.7 °C. That is the documented contract for unavailable data, and it replaces a wrong number with an honest one — but it is user-visible, so it has a CHANGELOG entry. Rejected values are logged at DEBUG with the key name, so anyone asking "why is my temperature 0" can find out.

Intel Macs are unaffected; they use TC0P, which is validated but does not park.

Tests

A plausibility invariant on both twins, enabled on macOS: the reading is either unavailable or at least the floor, never in between. This holds on CI runners too, where SMC access typically fails and returns 0.

Summary by CodeRabbit

  • Bug Fixes
    • Improved macOS CPU and GPU temperature reporting on Apple Silicon by ignoring idle-gated, implausibly low SMC readings using a plausibility threshold.
    • Sensors#getCpuTemperature now reports 0 (unavailable/parked) instead of returning fixed sentinel temperatures for idle core clusters.
  • Tests
    • Expanded macOS test coverage to ensure plausibility filtering accepts only NaN, 0, or temperatures at/above the threshold, while rejecting known parked/sentinel values (including verifying there’s no upper bound).

Apple Silicon power-gates a CPU core cluster when it is idle. The SMC then
reports a fixed parked value for each die sensor in that cluster instead of a
reading - on an M2 Max, 6.7 C for Tp01/Tp09 and 4.633 C for Tp05/Tp0D. Those are
below room ambient and cannot be die temperatures, but they are positive, so the
`> 0` test in smcGetFirstFloat accepted them. On a genuinely idle Mac,
getCpuTemperature therefore reported 6.7 C.

Renames smcGetFirstFloat to smcGetFirstTemperature and requires a reading of at
least MIN_PLAUSIBLE_TEMPERATURE (20 C), returning 0 for unavailable per the
documented Sensors contract. The Intel TC0P fallback is held to the same floor.
Applied to the JNA and FFM twins and to the GPU path, which shares the helper.

Findings from instrumenting an M2 Max, recorded in #3529:

- Not an FFM/JNA divergence. Both read byte-identical SMC payloads and agreed on
  every one of 19 interleaved samples, so both were equally affected.
- Not nondeterminism. The value tracks P-cluster power state exactly and
  reversibly; sustained load brings the sensors live within ~1.6s and they park
  again ~1.5s after it stops.
- Retry does not help. At deep idle the state is 100% persistent over 40 samples,
  and a second read recovered 0/15 at delays of 0, 10, 50, 200 and 1000 ms.
- Max instead of first-match does not help. All five keys are one power domain
  and park together, so the max of a parked set is still a parked value.
- Outlier detection has no signal. Across 224 samples spanning a full
  idle/load/idle transition there were 0 mixed sets: the keys are always all
  parked or all live, so there is never a good reading to compare an outlier
  against.

The floor is a plausibility guard, not a hardware specification. A sweep of all
288 temperature sensors found parked values from 0 to 16.6 C, and idle Apple
Silicon runs about 28-35 C, so 20 C clears every observed parked value with
margin below any genuine reading. No upper bound: every bad value observed was
at the low end, and a ceiling risks discarding real readings during thermal
throttling, which is when they matter most.

Users on an idle Apple Silicon Mac will now see 0 (unavailable) where they
previously saw a confident 6.7 C.
@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: 442778e5-f5d7-45ae-9875-31145159f11c

📥 Commits

Reviewing files that changed from the base of the PR and between c0a11ec and 53aa2ec.

📒 Files selected for processing (2)
  • oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java
  • oshi-core/src/test/java/oshi/hardware/platform/shared/SensorsTest.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-core/src/test/java/oshi/hardware/platform/shared/SensorsTest.java
  • oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (8)
  • 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: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)

📝 Walkthrough

Walkthrough

Apple Silicon macOS temperature handling now rejects implausibly low SMC readings, reports unavailable CPU values as zero where applicable, updates JNA and FFM CPU/GPU paths, and adds macOS-specific plausibility tests.

Changes

macOS temperature handling

Layer / File(s) Summary
Temperature threshold and selection
oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java, oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java
Replaces first-positive SMC selection with smcGetFirstTemperature, using a 15°C plausibility threshold and logging ignored nonzero readings below it.
Provider temperature integration
oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.java, oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java, oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java, oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java
Updates JNA and FFM CPU/GPU SMC paths to use the threshold-based helper; FFM fallback readings also apply the threshold.
Plausibility validation and release note
oshi-core/src/test/java/oshi/hardware/platform/shared/SensorsTest.java, oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java, CHANGELOG.md
Adds macOS-only assertions for unavailable, zero, or plausible CPU temperatures and documents the Apple Silicon fix.

Estimated code review effort: 2 (Simple) | ~15 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Sensors
  participant SmcUtil
  participant SMC
  participant IOAccelerator

  Sensors->>SmcUtil: Request Apple Silicon temperature
  SmcUtil->>SMC: Read candidate SMC keys
  SMC-->>SmcUtil: Return temperature values
  SmcUtil-->>Sensors: Return first plausible value or unavailable
  Sensors->>IOAccelerator: Read fallback GPU statistics
  IOAccelerator-->>Sensors: Return fallback temperature or -1
Loading

Possibly related issues

  • oshi/oshi issue 3534: Builds on this plausibility filtering and smcGetFirstTemperature behavior to address incorrect or missing Apple Silicon CPU temperature keys.

Possibly related PRs

  • oshi/oshi#3091: Introduces the Apple Silicon SMC key probing and helper path modified here.

Poem

A bunny found a chilly reading,
Too small for summer’s warmth and feeding.
“Zero,” said hare, “when sensors sleep,”
Plausible temperatures we’ll keep.
JNA and FFM now hop in tune!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.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 change: filtering implausible Apple Silicon SMC temperature readings.
Linked Issues check ✅ Passed The PR rejects sub-15°C Apple Silicon SMC readings, returns 0 for unavailable data, and adds coverage, matching #3529's goal.
Out of Scope Changes check ✅ Passed The JNA, GPU, changelog, and test updates are supporting changes for the same temperature-fix objective.
✨ 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.81%. Comparing base (10d81f7) to head (53aa2ec).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3531      +/-   ##
============================================
- Coverage     78.90%   78.81%   -0.09%     
- Complexity       76     3619    +3543     
============================================
  Files           698      698              
  Lines         24008    24008              
  Branches       3963     3963              
============================================
- Hits          18943    18923      -20     
- Misses         2879     2894      +15     
- Partials       2186     2191       +5     
Flag Coverage Δ
linux 35.27% <ø> (+0.01%) ⬆️
macos 36.21% <ø> (-0.04%) ⬇️
windows 43.50% <ø> (ø)

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.

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

31-35: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Add coverage for the changed GPU path.

This test exercises only Sensors#getCpuTemperature, while the PR also changes MacGpuStatsFFM#getTemperature and MacGpuStatsJNA#getTemperature. Add macOS GPU plausibility coverage for both implementations, or document why the IOAccelerator fallback does not need the same assertion.

🤖 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-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java`
around lines 31 - 35, Add macOS GPU temperature plausibility tests covering both
MacGpuStatsFFM#getTemperature and MacGpuStatsJNA#getTemperature, asserting each
returns unavailable or a value at least SmcUtilFFM.MIN_PLAUSIBLE_TEMPERATURE. If
the IOAccelerator fallback is intentionally exempt, document that rationale
instead of adding the assertion.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java`:
- Around line 31-35: Add macOS GPU temperature plausibility tests covering both
MacGpuStatsFFM#getTemperature and MacGpuStatsJNA#getTemperature, asserting each
returns unavailable or a value at least SmcUtilFFM.MIN_PLAUSIBLE_TEMPERATURE. If
the IOAccelerator fallback is intentionally exempt, document that rationale
instead of adding the assertion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 87f1f0cd-a871-4833-9b5c-5f5456333a2d

📥 Commits

Reviewing files that changed from the base of the PR and between 10d81f7 and cd37f13.

📒 Files selected for processing (9)
  • 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/MacGpuStatsFFM.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/MacGpuStatsJNA.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/hardware/platform/shared/SensorsTest.java
📜 Review details
⏰ Context from checks skipped due to timeout. (5)
  • 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: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (2)
📚 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
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.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-core/src/main/java/oshi/hardware/platform/mac/MacSensorsJNA.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.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-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacSensorsFFM.java
🔇 Additional comments (8)
oshi-core-ffm/src/main/java/oshi/ffm/util/platform/mac/SmcUtilFFM.java (1)

169-198: LGTM!

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

149-178: LGTM!

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

35-39: LGTM!

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

37-41: LGTM!

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

159-159: 🎯 Functional Correctness

Verify that the non-SMC GPU fallback cannot bypass the plausibility guard.

Both methods now reject sub-threshold SMC readings but then accept any positive IOAccelerator Temperature(C) value. Verify that fallback cannot return the same parked values; otherwise apply MIN_PLAUSIBLE_TEMPERATURE to the Apple Silicon fallback in both implementations.

  • oshi-core-ffm/src/main/java/oshi/hardware/platform/mac/MacGpuStatsFFM.java#L159-L159: validate the IOAccelerator fallback after SMC rejection.
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacGpuStatsJNA.java#L172-L172: apply the same validation to the JNA fallback.
oshi-core-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java (1)

1-30: LGTM!

oshi-core/src/test/java/oshi/hardware/platform/shared/SensorsTest.java (1)

17-22: LGTM!

Also applies to: 42-53

CHANGELOG.md (1)

7-7: LGTM!

@dbwiddis

Copy link
Copy Markdown
Member Author

On the GPU plausibility test suggestion — taking the second half of it (document the exemption), skipping the first (add the assertion), because the proposed assertion would be incorrect on two counts:

  1. Wrong sentinel. GpuStats#getTemperature documents "temperature in degrees Celsius, or -1 if unavailable", not 0 or NaN. An assertion of "unavailable or >= MIN_PLAUSIBLE_TEMPERATURE" written against 0 would read the real -1 return as a failure.
  2. Wrong source. The fallback reads Temperature(C) from the IOAccelerator performance-statistics dictionary — IOKit, not the SMC. It is not power-gated with the GPU cluster, so the SMC parking behaviour this PR fixes does not apply to it, and the floor deliberately does not either. Asserting the floor across the whole method would fail the first time that path returned a legitimate low reading.

The SMC half of the GPU path is covered: MacGpuStats{FFM,JNA}#getTemperature now call smcGetFirstTemperature, so it inherits the floor and the DEBUG logging.

Pushed dedffcd documenting the exemption in both twins, which is what the finding's own fallback branch asked for.

@dbwiddis

Copy link
Copy Markdown
Member Author

Cross-validated the 20 C floor against iSMC's sample reports — full SMC dumps from 13 machines spanning M1, M1 Pro/Max/Ultra, M2, M3 Pro/Max, M4, M4 Pro/Max, M5 Pro/Max, A18 and an Intel T2. That is far better coverage than the single M2 Max this PR was developed on.

The floor never changes a good reading

In every report where OSHI's CPU keys are present, the old > 0 selection and the new >= 20 selection pick the same value:

report OSHI keys found old first > 0 new first >= 20
a18 Tp09=91.43 Tp01=92.76 Tp05=94.28 91.43 91.43
m2 Tp09=37.67 Tp01=37.92 Tp05=37.05 37.67 37.67
m3-max Tp0T=57 Tp05=48 Tp0D=48 57 57
m4-max Tp09=Tp0T=Tp01=Tp05=Tp0D=40 40 40
m4 Tp09=37 Tp01=36 Tp05=36 Tp0D=36 37 37

No regression on any of them.

There is an empty band exactly where the floor sits

Across all 489 Tp*/Tg* readings in those reports:

below 20 C :  53 readings, highest = 5.20
>= 20 C    : 436 readings, lowest  = 21.00   (intel-t2:Tp5a)
             ^^^ nothing at all observed between 5.20 and 21.00

The sub-20 values are -4.0 (x15), 0.0 (x23), 2.5 (x6), 4.0 (x6), 5.2 (x3) — parked sentinels, and note they differ per model, which is why the PR rejects on a value floor rather than by matching sentinels. The -4.0 on an M4 Max is a useful find: parked values are not even guaranteed positive.

20 turns out to be the right number, not just a safe one

Combining with the M2 Max sweep in #3529, which saw a parked value as high as 16.6 C:

highest parked value observed anywhere : 16.6   (M2 Max sweep)
lowest genuine reading observed anywhere: 21.0   (intel-t2:Tp5a)

20 is inside the only gap that separates those two populations. A lower floor such as 15 would have admitted the 16.6 park; a higher one would start crowding real readings. Worth recording for anyone tempted to widen the key list later — the margin above the floor is about 1 C in the general Tp* space, even though it is much larger for the five keys OSHI actually reads.

The 20 C floor was justified by a 16.6 C value from the M2 Max sweep that I had
classified as a parked sentinel. It is not one: that sensor is TVMO, and ten
consecutive reads give ten distinct values drifting between 15.01 and 16.73,
which is a live sensor somewhere cool. A real sentinel is bit-identical on every
read, as Tp09's 6.6999998 is.

With that removed, the highest sentinel ever observed is 8.425 (M2 Max) and the
lowest genuine reading is 21.0 (intel-t2:Tp5a across 13 machines), so 15 sits
near the middle of the empty band instead of 1 C below the genuine population.

iSMC independently reaches the same diagnosis, calling these "firmware sentinels
from inactive sensor slots" with an observed range of -4 to 5.2, and applies a
minimum of 10 C scoped to temperature units only. 15 is chosen over their 10
because this sweep saw sentinels up to 8.425, higher than they report.

Extracts isPlausibleTemperature so the guard can be tested directly rather than
only through a live SMC connection, and table-tests it against sentinels and
genuine readings actually captured from hardware rather than invented values.
@dbwiddis

Copy link
Copy Markdown
Member Author

Correction to my previous comment, and the floor is now 15 C (c0a11ec).

I claimed 16.6 C was a parked sentinel on the M2 Max and used it to argue that 20 was the only value in the gap. That was wrong. The sensor is TVMO, and ten consecutive reads give ten distinct values:

TVMO   16.732  15.010  15.765  15.175  16.227  15.651  15.411  15.548  16.090  16.261
Tp09    6.700   6.700   6.700   6.700   6.700   6.700   6.700   6.700   6.700   6.700

A sentinel is bit-identical on every read, as Tp09 is. TVMO drifts continuously — it is a live sensor somewhere cool. My sweep had misclassified it because the heuristic was "load-responsive and below 20 C", which a genuinely cool sensor also satisfies.

Revised evidence

value source
highest sentinel observed 8.425 M2 Max sweep (Tp02/Tp0A family); iSMC reports max 5.2
lowest genuine reading observed 21.0 intel-t2:Tp5a, across 13 machines

The empty band is 8.425 → 21.0, so 20 sat about 1 C below the genuine population rather than in the middle. 15 is roughly central: 6.6 C above the highest sentinel, 6 C below the lowest genuine reading.

Prior art

iSMC reaches the same diagnosis independently — its isValidReading rejects "firmware sentinels from inactive sensor slots (observed: −4..5.2 °C)" with a minTempCelsius = 10.0 scoped to temperature units only, the same unit-scoping this PR uses. 15 rather than their 10 because this sweep observed sentinels up to 8.425, higher than they report, which leaves only 1.6 C of margin at 10.

Also in this push

isPlausibleTemperature is extracted so the guard can be tested directly instead of only through a live SMC connection. The new tests table-drive it against values actually captured from hardware — sentinels -4.0, 0.0, 2.5, 4.0, 4.633, 5.2, 6.033, 6.7, 7.425, 8.425 and genuine readings 21.0 … 110.0 — plus an assertion that the floor stays inside the empty band, so moving it onto either population fails loudly.

Re-verified end to end on the M2 Max: unavailable at deep idle, ~59 C under load.

Follow-up, not in this PR

iSMC commit 7e229fa reports that M4 performance-core keys are Tp1i/Tp1m/…, not the Tp01/Tp05 family. If so, SMC_KEYS_CPU_TEMP_AS reads the wrong sensors on M4 — a key-selection problem independent of this guard, worth its own issue.

@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-ffm/src/test/java/oshi/ffm/MacSensorsPlausibilityFFMTest.java`:
- Around line 63-64: Update the assertion in MacSensorsPlausibilityFFMTest so
MIN_PLAUSIBLE_TEMPERATURE is strictly greater than 8.425, or directly verify
that isPlausibleTemperature(8.425) returns false; do not retain the inclusive
boundary check.

In `@oshi-core/src/test/java/oshi/hardware/platform/shared/SensorsTest.java`:
- Around line 57-59: Resolve the conflicting temperature expectations in
SensorsTest: update the CPU upper-bound assertion in testSensors() to allow the
newly accepted 110.0 °C reading, or remove 110.0 from the genuine-reading cases
if CPU output must remain capped at 100 °C. Keep the test expectations
consistent with the intended SmcUtil.isPlausibleTemperature contract.
🪄 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: e8a79369-2b72-4c71-b8db-ebf326412a49

📥 Commits

Reviewing files that changed from the base of the PR and between dedffcd and c0a11ec.

📒 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/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/hardware/platform/shared/SensorsTest.java
🚧 Files skipped from review as they are similar to previous changes (3)
  • 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
📜 Review details
⏰ Context from checks skipped due to timeout. (8)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (1)
📚 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
🔇 Additional comments (4)
oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java (2)

149-172: LGTM!


174-191: LGTM!

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

1-5: LGTM!

Also applies to: 6-25, 27-39, 41-54, 69-77

oshi-core/src/test/java/oshi/hardware/platform/shared/SensorsTest.java (1)

17-22: LGTM!

Also applies to: 42-56, 60-61, 63-69

The boundary guard used >= 8.425, which would have accepted a floor of exactly
8.425 - at which point isPlausibleTemperature(8.425) returns true, contradicting
the sentinel-rejection test. Strictly greater.

110 C was listed among "genuine readings", but it was never observed on any
machine; it is a probe for the deliberate absence of an upper bound. Moved to
its own assertion so the observed-data arrays contain only observed data, and
so it no longer reads as a claim that hardware reports 110 C.
@dbwiddis

Copy link
Copy Markdown
Member Author

Both addressed in 53aa2ec, though the second differently than suggested.

Boundary assertion — valid, fixed. >= 8.425 would have accepted a floor of exactly 8.425, and since the predicate is celsius >= MIN_PLAUSIBLE_TEMPERATURE, that floor would make isPlausibleTemperature(8.425) return true — contradicting testObservedSentinelsAreRejected. The guard could not have caught that particular regression. Now strictly greater, with a comment explaining why.

The 110 C case — real inconsistency, but in my test data rather than in testSensors. The two assertions do not actually conflict at runtime: testSensors asserts a bound on what this machine reports, while the new test asserts the predicate's contract. No hardware reading of 110 is implied by one passing the other.

The genuine problem is that I filed 110 under GENUINE_READINGS, whose javadoc says these are readings observed on hardware. 110 was never observed anywhere — it is a probe for the deliberate absence of an upper bound. So it has moved to its own testNoUpperBoundIsApplied, leaving the observed-data arrays containing only observed data.

I did not change the 0-100 bound in testSensors. It predates this PR, it asserts what real hardware reports rather than what the predicate accepts, and the absence of a ceiling is intentional here: every bad value observed was at the low end, and a ceiling near the ~100 C throttling point would discard real readings exactly when they matter most.

@dbwiddis
dbwiddis merged commit 0ffc4fb into oshi:master Jul 27, 2026
16 checks passed
@dbwiddis
dbwiddis deleted the mac-smc-implausible-temperature branch July 27, 2026 06:17
dbwiddis added a commit that referenced this pull request Jul 27, 2026
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 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.

FFM CPU temperature on Apple Silicon is nondeterministic and diverges from JNA

1 participant