Skip to content

Make the compared CPU frequency and thread times reproducible - #3562

Merged
dbwiddis merged 2 commits into
oshi:masterfrom
dbwiddis:comparison-determinism
Aug 2, 2026
Merged

dbwiddis merged 2 commits into
oshi:masterfrom
dbwiddis:comparison-determinism

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 2, 2026 •

Copy link
Copy Markdown
Member

Two comparison-test flakes with the same shape: an assertion comparing values that are not reproducible by construction.

Linux getMaxFreq() folded in a live reading

queryMaxFreq() took the max of the cpufreq policy value, lshw, and a live getCurrentFreq() reading. On a host with no cpufreq sysfs and no lshw — most CI VMs — the first two return -1 and the live reading is the only input, so getMaxFreq() reported whatever the CPU happened to be clocked at the first time it was asked. The JNA and FFM backends sample at different instants, so they disagreed by more than the 5% processorFrequencies allows whenever turbo moved between the two calls.

The live reading is replaced by the vendor frequency, which is parsed from the CPU model name and is constant:

long vendorFreq = getProcessorIdentifier().getVendorFreq();
long maxFreq = LongStream.of(policyMax, lshwMax, vendorFreq).max().orElse(-1L);
return maxFreq > 0L ? maxFreq : -1L;

A maximum derived from a fluctuating measurement was not a maximum, and callers polling getMaxFreq() were entitled to a stable answer. Where no source reports one the result is now -1, the documented unknown value, rather than a sample. The two existing tests already guard on max >= 0 and vendorFreq > 0, so neither needed changing — and the comparison now passes untouched, since both backends compute from identical stable inputs.

FreeBSD thread user time is not monotonic

currentThreadUpdateAttributes asserted user time is monotonically nondecreasing. On FreeBSD it is not:

=> AssertionError: [FFM thread userTime]
   Expecting actual: 250L to be greater than or equal to: 260L

BsdOSThread derives it as TIME - SYSTIME, and ps rounds each column to a centisecond. The two cross their rounding boundaries at different instants, so the difference can fall by one 10 ms quantum while both underlying values only rise. The observed drop was exactly 10 ms — one quantum. Not a backend divergence: BsdOSThread is shared oshi-common code, so FFM just lost the coin flip, and only the FreeBSD branch is exposed (the other BSDs take the CPUTIME/TIME branches where user time is a single un-differenced column).

Kernel time keeps its own assertion, since it reads SYSTIME directly. User time is asserted as part of the sum, which is exactly the TIME column by construction and therefore monotonic. Widening the bound by 10 ms instead would have passed the flake but also hidden a genuine decrease.

BsdOSProcess (lines 205-206) derives user time identically, so the process-level assertion carried the same latent defect and is fixed alongside it, though only the thread assertion had fired.

Notes

CHANGELOG covers the Linux change only; the comparison-test fix is test-only.

Full gate green on all 8 modules: spotless, checkstyle, install, forbiddenapis, javadoc, 1504 tests successful / 0 failed, plus a -Paggregate-coverage test-compile so the comparison sources build. The comparison tests themselves only run under that profile in CI.

Summary by CodeRabbit

  • Bug Fixes

    • Improved Linux maximum CPU frequency reporting by selecting the highest reliable value from available system hardware information.
    • Returns an unavailable indicator when no maximum frequency can be determined.
    • Prevents fluctuating live frequency readings from being incorrectly reported as the processor’s maximum speed.
  • Documentation

    • Added release notes documenting the improved Linux CPU frequency resolution.

Two comparison-test flakes with the same shape: an assertion comparing
values that are not reproducible by construction.

Linux getMaxFreq folded a live getCurrentFreq() reading into the max
alongside the cpufreq policy and lshw values. On a host with no cpufreq
sysfs and no lshw -- most CI VMs -- those two return -1 and the live
reading is the only input, so getMaxFreq() reported whatever the CPU
happened to be clocked at the first time it was asked. The JNA and FFM
backends sample at different instants, so they disagreed by more than
the 5% the comparison allows whenever turbo moved between them.

The live reading is replaced by the vendor frequency, which is parsed
from the CPU model name and is constant. A maximum derived from a
fluctuating measurement was not a maximum, and callers polling
getMaxFreq() were entitled to a stable answer. Where no source reports
one the result is now -1, the documented unknown value, rather than a
sample: the two existing assertions already guard on max >= 0 and
vendorFreq > 0. This also makes the comparison pass without touching it,
since both backends now compute from identical stable inputs.

The thread and process time assertions asserted user time is
monotonically nondecreasing. On FreeBSD it is not, because BsdOSThread
and BsdOSProcess derive it as (TIME - SYSTIME) and ps rounds each column
to a centisecond. The two columns cross their rounding boundaries at
different instants, so the difference can fall by one 10 ms quantum
while both underlying values only rise -- observed as 260 -> 250, one
quantum exactly.

Kernel time is still asserted on its own, since it reads SYSTIME
directly. User time is asserted as part of the sum, which is exactly the
TIME column by construction and so is monotonic. Widening the bound by
10 ms instead would have hidden a genuine decrease. The process-level
assertion had the same latent defect and is fixed alongside the thread
one, though only the thread assertion had fired.
@coderabbitai

coderabbitai Bot commented Aug 2, 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: de2d9388-ba6e-4cee-9d60-5b6076d11b22

📥 Commits

Reviewing files that changed from the base of the PR and between a3e234c and 4a4ce71.

📒 Files selected for processing (1)
  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (8)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)

📝 Walkthrough

Walkthrough

Linux maximum-frequency resolution now uses static policy, lshw, and vendor-frequency sources. Process and thread tests now validate kernel and combined timing monotonicity. The changelog records the frequency behavior.

Changes

Linux maximum-frequency resolution

Layer / File(s) Summary
Maximum-frequency source selection
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java, CHANGELOG.md
queryMaxFreq() selects the greatest positive value from cpufreq policy, lshw, and vendor frequency. It returns -1L when no maximum is available. The changelog documents this behavior.

Process and thread timing validation

Layer / File(s) Summary
Monotonic timing assertions
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
Process and thread refresh checks validate nondecreasing kernel time and combined kernel-plus-user time. Standalone user-time checks are removed.

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

Possibly related PRs

  • oshi/oshi#3120: Refactors the Linux frequency-query architecture used by LinuxCentralProcessor.queryMaxFreq().
  • oshi/oshi#3288: Introduces related process and thread timing monotonicity assertions.

Poem

A rabbit checks the clocks at dawn,
Linux finds the peak frequency strong.
Kernel times hop in line,
Combined times remain fine,
-1L appears when peaks are gone.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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 changes to make CPU frequency and thread-time comparisons reproducible.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 Aug 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.00000% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.27%. Comparing base (140a84b) to head (4a4ce71).

Files with missing lines Patch % Lines
...e/common/platform/linux/LinuxCentralProcessor.java 50.00% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3562      +/-   ##
============================================
- Coverage     79.34%   79.27%   -0.07%     
+ Complexity     4037     3797     -240     
============================================
  Files           706      706              
  Lines         24292    24294       +2     
  Branches       4063     4065       +2     
============================================
- Hits          19275    19260      -15     
- Misses         2823     2841      +18     
+ Partials       2194     2193       -1     
Flag Coverage Δ
linux 36.76% <50.00%> (-0.01%) ⬇️
macos 37.70% <0.00%> (-0.04%) ⬇️
windows 44.61% <0.00%> (-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

🤖 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-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java`:
- Around line 624-631: Update queryMaxFreq() so its vendor fallback never uses
getProcessorIdentifier().getVendorFreq(), because that value may originate from
the live /proc/cpuinfo reading passed by queryProcessorId(). Use only the stable
model-name frequency or another separately tracked stable value, and return -1L
when policyMax, lshwMax, and the stable vendor source are unavailable.
🪄 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: 6f554998-9f6f-4c46-87aa-a6c741bada4f

📥 Commits

Reviewing files that changed from the base of the PR and between 140a84b and a3e234c.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
📜 Review details
⏰ Context from checks skipped due to timeout. (7)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, ubuntu-latest
🧰 Additional context used
📓 Path-based instructions (4)
oshi-common/src/main/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

oshi-common/src/main/java/**/*.java: Keep oshi-common pure Java 8 with no JNA, FFM, or native library loading references; shared parsing, conversion, filtering, caching, and validation logic belongs here rather than duplicated in implementation modules.
Use oshi.util.ParseUtil methods instead of banned numeric parsing APIs such as Integer.parseInt, Long.parseLong, Double.parseDouble, and Integer.decode.

Files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

**/*.java: Do not use org.slf4j.event.**; use oshi.util.LogLevel instead.
Add the imports needed by code, and let Spotless own formatting and import ordering.
Verify native struct offsets, field widths, and sysctl/ioctl constants against the target operating system's real headers rather than inferring them from another OS.

Files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
**/src/main/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

**/src/main/java/**/*.java: Every public member must have Javadoc, and code and Javadoc—including {@link ...}—must use imported simple class names rather than fully qualified names.
New classes should declare an appropriate concurrency annotation from oshi.annotation.concurrent, matching the modeled class when applicable.
Memoize constant or expensive, slowly changing system-call results with oshi.util.Memoizer, following surrounding patterns and using defaultExpiration() when values must refresh.
Place reusable per-OS acquisition and parsing helpers in oshi/driver/<os>/; keep parsing logic out of HAL classes where practical.
Prefer native calls for system information; on Linux prefer FileUtil for /proc and /sys, while on other platforms ExecutingCommand is acceptable when native APIs do not expose the information.
Do not commit generated output, target/, or IDE files.

Files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
**/src/test/java/**/*Test.java

📄 CodeRabbit inference engine (AGENTS.md)

**/src/test/java/**/*Test.java: Use JUnit 5 and Hamcrest; do not add Mockito. Extract parsing into methods accepting fixture data such as List<String> or String, and test those methods separately from acquisition.
Assert hardware-independent invariants such as non-null values, types, ordering, and plausible ranges rather than specific hardware values; allow zero and empty results.
Avoid timing-sensitive assertions comparing live readings, including CPU frequency, tick counters, and uptime.
Do not assume platform-specific hardware exists; tests must tolerate absent batteries, sensors, GPUs, sound cards, and processors.

Files:

  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
🧠 Learnings (4)
📚 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/hardware/common/platform/linux/LinuxCentralProcessor.java
📚 Learning: 2026-04-12T19:34:56.879Z
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:34:56.879Z
Learning: In OSHI’s Java platform implementations, `PhysicalProcessor.getEfficiency()` / `EfficiencyClass` follow the same convention as Windows `PROCESSOR_RELATIONSHIP.EfficiencyClass`: a *higher* numeric efficiency class value represents *greater performance* and *less efficiency* (typically P-cores higher than E-cores). When reviewing, do not treat cases where P-cores are assigned higher efficiency/class values as a bug—this is intentional cross-platform consistency.

Applied to files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.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/hardware/common/platform/linux/LinuxCentralProcessor.java
📚 Learning: 2026-07-30T00:35:22.638Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3547
File: oshi-common/src/main/java/oshi/hardware/common/platform/unix/BsdFirmware.java:82-82
Timestamp: 2026-07-30T00:35:22.638Z
Learning: In OSHI, treat changes as “API-breaking” only when they affect classes (or relevant API surface) annotated with `PublicAPI`. Public classes/members that are not annotated with `PublicAPI` should be reviewed as internal implementation details, even if they are public (e.g., classes like `oshi.hardware.common.platform.unix.BsdFirmware`). Also, respect intentional visibility decisions used for tests—e.g., methods like `BsdFirmware.parseDmesg(List<String>)` may be intentionally package-private to support tests within the same package; avoid widening visibility or altering signatures unless the related `PublicAPI` contract requires it.

Applied to files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
🔇 Additional comments (2)
CHANGELOG.md (1)

6-6: LGTM!

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

470-477: 📐 Maintainability & Code Quality

Keep these assertions consistent with oshi-benchmark’s assertion library.

oshi-benchmark already imports and uses AssertJ in NativeComparisonTest, WmiComparisonTest, RegistryComparisonTest, and comparison helpers. These lines do not violate an unsupported “JUnit 5 and Hamcrest only” rule.

			> Likely an incorrect or invalid review comment.

CodeRabbit caught that getVendorFreq() is not always name-derived, which
defeats the point of the previous commit.

queryProcessorId discards /proc/cpuinfo's "cpu MHz" value only when the
model name carries a frequency of its own:

    if (cpuName.contains("Hz")) {
        cpuFreq = -1L;          // ProcessorIdentifier parses "@ x.xGHz"
    } else {
        cpuFreq = max(cpuinfoFreq, lshwCapacity);
    }

and ProcessorIdentifier takes that through verbatim when it is positive.
"cpu MHz" is the current frequency, not a maximum, so on a host with no
lshw and a model name with no frequency in it -- an AMD part, which is
much of the CI fleet -- getVendorFreq() returns a live reading and
getMaxFreq() was still not reproducible.

Gating on the same cpuName.contains("Hz") condition queryProcessorId
uses keeps the fallback name-derived, and leaves it -1 where the name
has no frequency. Reading the name here rather than reparsing it avoids
duplicating the "@ (.*)$" pattern that ProcessorIdentifier already
applies, and parseHertz is not usable on the whole name because it
scans with find() and would latch onto any Hz-like substring.

Nothing is lost by dropping the lshw value from this path: queryMaxFreq
already queries Lshw.queryCpuCapacity() separately.
@dbwiddis
dbwiddis merged commit b3d76d3 into oshi:master Aug 2, 2026
16 checks passed
@dbwiddis
dbwiddis deleted the comparison-determinism branch August 2, 2026 17:58
dbwiddis added a commit that referenced this pull request Aug 2, 2026
Four things that had been waiting for one push, since a .java change
queues the shared cfarm boxes and a stream of small pushes queues them
repeatedly.

coverity.yaml: drop `cov-build --version || true`. cov-build has no
--version flag, so every scan logged "[COMMAND LINE ERROR] Undefined
option 'version'" before carrying on. The tool directory name already
carries the version, which is what the surrounding comment is really
pointing at, so that comment moves to the echo that does the job.

Memoizer: the @SuppressWarnings left behind by the S3077 probe said
"probe: is the annotation honored here". It is -- the scan came back
clean -- so the comment now says why the field is exempt rather than
what was being tested.

sonar.yaml: add an optional `branch` dispatch input. Sonar only runs on
push to master, which is why iterating on anything Sonar-visible meant
pushing exploratory commits to master, each one queueing cfarm. With
this, `gh workflow run sonar.yaml --ref <branch> -f branch=<branch>`
reports under that branch instead. The value is passed through the
environment rather than interpolated into the script, so a dispatch
input cannot inject shell; leaving it empty keeps today's behaviour.

NativeComparisonTest.diskStores: sum reads and writes instead of
comparing them individually. AIX has no separate write counter --
AixHWDiskStore apportions one combined transfer count between the two by
block ratio -- so a shift in the read/write mix moves each part on its
own while only the total is guaranteed to rise. This is the flake that
failed cfarm on #3562's merge, and the same failure is in the 2026-07-28
run, four days before that PR, so it is not a regression from it. Third
of the same family as the FreeBSD thread time and Linux maxFreq fixes.

Byte counters keep their individual assertions: those are read straight
from the platform. NativeFreeComparisonTest is untouched -- it is Linux
and NetBSD only, where reads come from /proc/diskstats directly and are
not apportioned.
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