Repository navigation
Make the compared CPU frequency and thread times reproducible - #3562
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📜 Recent review details⏰ Context from checks skipped due to timeout. (8)
📝 WalkthroughWalkthroughLinux maximum-frequency resolution now uses static policy, ChangesLinux maximum-frequency resolution
Process and thread timing validation
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
CHANGELOG.mdoshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.javaoshi-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: Keeposhi-commonpure 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.
Useoshi.util.ParseUtilmethods instead of banned numeric parsing APIs such asInteger.parseInt,Long.parseLong,Double.parseDouble, andInteger.decode.
Files:
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
**/*.java
📄 CodeRabbit inference engine (AGENTS.md)
**/*.java: Do not useorg.slf4j.event.**; useoshi.util.LogLevelinstead.
Add the imports needed by code, and let Spotless own formatting and import ordering.
Verify native struct offsets, field widths, andsysctl/ioctlconstants 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.javaoshi-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 fromoshi.annotation.concurrent, matching the modeled class when applicable.
Memoize constant or expensive, slowly changing system-call results withoshi.util.Memoizer, following surrounding patterns and usingdefaultExpiration()when values must refresh.
Place reusable per-OS acquisition and parsing helpers inoshi/driver/<os>/; keep parsing logic out of HAL classes where practical.
Prefer native calls for system information; on Linux preferFileUtilfor/procand/sys, while on other platformsExecutingCommandis 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 asList<String>orString, 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 QualityKeep these assertions consistent with
oshi-benchmark’s assertion library.
oshi-benchmarkalready imports and uses AssertJ inNativeComparisonTest,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.
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.
Two comparison-test flakes with the same shape: an assertion comparing values that are not reproducible by construction.
Linux
getMaxFreq()folded in a live readingqueryMaxFreq()took the max of the cpufreq policy value,lshw, and a livegetCurrentFreq()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, sogetMaxFreq()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%processorFrequenciesallows 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:
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 onmax >= 0andvendorFreq > 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
currentThreadUpdateAttributesasserted user time is monotonically nondecreasing. On FreeBSD it is not:BsdOSThreadderives it asTIME - SYSTIME, andpsrounds 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:BsdOSThreadis sharedoshi-commoncode, so FFM just lost the coin flip, and only the FreeBSD branch is exposed (the other BSDs take theCPUTIME/TIMEbranches where user time is a single un-differenced column).Kernel time keeps its own assertion, since it reads
SYSTIMEdirectly. User time is asserted as part of the sum, which is exactly theTIMEcolumn 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-coveragetest-compile so the comparison sources build. The comparison tests themselves only run under that profile in CI.Summary by CodeRabbit
Bug Fixes
Documentation