Skip to content

Improve coverage: cpuid parsing, comparison test toggles - #3211

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:improve-oshi-common-coverage
Apr 29, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:improve-oshi-common-coverage

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Apr 29, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Extract cpuid -1r parsing in LinuxCentralProcessor to a testable static parseCpuidOutput() method with unit tests using fixture data
  • Enable PROCSTATE_SUSPENDED and COMMANDLINE_BATCH toggles in NativeComparisonTest to exercise suspended-state thread logic and Win32ProcessCached command line queries
  • Add currentProcessUpdateAttributes() test comparing updateAttributes, command line, CWD, and environment variables for the current process
  • Enhance sessions() test to compare session details (user, device, host, login time) field-by-field on Linux

What was tested

  • spotless:apply — pass
  • checkstyle:check — 0 violations
  • install (compile + test + package) — pass
  • forbiddenapis:check — pass

Summary by CodeRabbit

  • Tests

    • Enabled Windows-specific detection and batched command-line checks in test setup
    • Added validation of process attribute updates and cross-implementation consistency
    • Expanded session tests to compare implementations and enforce tight login-time tolerance
    • Added processor ID parsing tests, including malformed and empty-input cases
  • Refactor

    • Optimized processor ID detection on Linux for improved accuracy

@coderabbitai

coderabbitai Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Refactors CPUID parsing into a new static helper and updates LinuxCentralProcessor to use it; expands benchmark tests to enable Windows-specific flags, add a currentProcessUpdateAttributes test comparing JNA/FFM, and strengthen session list comparisons on Linux.

Changes

Cohort / File(s) Summary
Benchmark test enhancements
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
Enabled Windows suspended-state and batched command-line flags in setup(). Added currentProcessUpdateAttributes() to compare OSProcess.updateAttributes() behavior across JNA and FFM and expanded sessions() to store both implementations, assert equal sizes, and on Linux match sessions by userName\|terminalDevice to compare host and constrain loginTime diffs ≤ 1s.
Linux CPU parsing refactor
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java, oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.java
Added static parseCpuidOutput(List<String>) to extract processor ID from cpuid -1r output. getProcessorID() now delegates to this helper and falls back when it returns null. Added unit tests for successful parse, missing leaf, malformed/incomplete line, and empty input.

Sequence Diagram(s)

(Skipped — changes are refactor + tests without multi-component control-flow requiring a sequence diagram.)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

In cpuid lines a secret sings,
Tests align like tiny wings,
JNA and FFM compare their tunes,
Sessions matched beneath the moons,
Code parsed, assertions bright — rejoice! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.82% 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 changes: cpuid parsing extraction and comparison test configuration toggles.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
✨ Simplify code
  • Create PR with simplified code

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
Review rate limit: 6/8 reviews remaining, refill in 11 minutes and 48 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

@dbwiddis
dbwiddis force-pushed the improve-oshi-common-coverage branch from a04a7ed to 5991e30 Compare April 29, 2026 00:06

@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

Caution

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

⚠️ Outside diff range comments (1)
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java (1)

604-617: ⚠️ Potential issue | 🟠 Major

Guard against partial CPUID matches returning malformed IDs.

If the 0x00000001 line is present but one register token is missing, this currently returns a partial ID instead of falling back. Please only return when both eax and edx were parsed.

Proposed fix
 static String parseCpuidOutput(List<String> cpuidLines) {
     for (String checkLine : cpuidLines) {
         if (checkLine.contains("eax=") && checkLine.trim().startsWith("0x00000001")) {
-            String eax = "";
-            String edx = "";
+            String eax = null;
+            String edx = null;
             for (String register : ParseUtil.whitespaces.split(checkLine)) {
                 if (register.startsWith("eax=")) {
                     eax = ParseUtil.removeMatchingString(register, "eax=0x");
                 } else if (register.startsWith("edx=")) {
                     edx = ParseUtil.removeMatchingString(register, "edx=0x");
                 }
             }
-            return edx + eax;
+            if (eax != null && edx != null) {
+                return edx + eax;
+            }
         }
     }
     return null;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java`
around lines 604 - 617, In parseCpuidOutput(List<String> cpuidLines) the code
can return a malformed partial ID when the "0x00000001" line is found but one of
the register tokens (eax or edx) is missing; modify the loop in parseCpuidOutput
so that after parsing tokens it only returns edx + eax when both eax and edx are
non-empty (i.e., both were successfully parsed via
ParseUtil.removeMatchingString); if either is empty, do not return and continue
scanning other lines or fall back to the existing default behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java`:
- Around line 537-548: The test currently uses a relative check via
assertWithinRatio on epoch millisecond loginTime (in NativeComparisonTest.java,
within the loop comparing OSSession f and JNA session j), which is too
permissive; replace the assertWithinRatio(f.getLoginTime(), j.getLoginTime(),
0.01, ...) call with an absolute delta check (e.g., assertWithinDelta or an
explicit Math.abs(f.getLoginTime() - j.getLoginTime()) <= allowedMillis) and
choose a reasonable absolute threshold such as 5000 ms (or another
project-appropriate value) in the assertion message "session[...].loginTime" to
ensure login times are compared by an absolute millisecond difference rather
than a percentage.

---

Outside diff comments:
In
`@oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java`:
- Around line 604-617: In parseCpuidOutput(List<String> cpuidLines) the code can
return a malformed partial ID when the "0x00000001" line is found but one of the
register tokens (eax or edx) is missing; modify the loop in parseCpuidOutput so
that after parsing tokens it only returns edx + eax when both eax and edx are
non-empty (i.e., both were successfully parsed via
ParseUtil.removeMatchingString); if either is empty, do not return and continue
scanning other lines or fall back to the existing default behavior.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 66edf027-bbbd-4fc2-a837-ea2c0b39aa0e

📥 Commits

Reviewing files that changed from the base of the PR and between f18b5da and a04a7ed.

📒 Files selected for processing (7)
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxFirmwareTest.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsGlobalMemoryTest.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxOperatingSystemTest.java
📜 Review details
🧰 Additional context used
🧠 Learnings (8)
📚 Learning: 2026-04-19T01:28:47.155Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3174
File: oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java:237-257
Timestamp: 2026-04-19T01:28:47.155Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java`, the WMI comparison tests (e.g., `testProcessor`) intentionally validate only index 0 and a few representative fields per WMI data type (String, uint16, uint32, uint64). Exhaustive row-by-row comparison is deliberately avoided for numerically heavy multi-row tables. The design rationale is: matching row counts + a few selected fields covering each data type is sufficient to verify JNA vs FFM driver parity. Do not suggest looping over all rows for these tests.

Applied to files:

  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.java
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsGlobalMemoryTest.java
📚 Learning: 2026-04-14T23:28:18.252Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3160
File: oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxSensorsTest.java:34-40
Timestamp: 2026-04-14T23:28:18.252Z
Learning: In oshi/oshi, `vcgencmd` (used in `LinuxSensors.queryCpuTemperatureFromVcGenCmd()` and related methods) is a Raspberry Pi-specific binary. It will never be present on standard x86/amd64 CI runners or developer machines. Tests that pass `isPi=true` to `LinuxSensors` and assert 0/empty returns are deterministic in practice; do not flag them as potentially flaky due to `vcgencmd` availability.

Applied to files:

  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxFirmwareTest.java
📚 Learning: 2026-04-18T03:18:06.205Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3170
File: oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java:177-183
Timestamp: 2026-04-18T03:18:06.205Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java`, GPU engine PDH instance counts (from `GpuInformationJNA.queryGpuEngineCounters()` / `GpuInformationFFM.queryGpuEngineCounters()`) are highly volatile — counts can differ dramatically (e.g., 53 vs 40) even between queries taken milliseconds apart. Do not assert instance count equality or exact instance list matching between JNA and FFM results. The only reliable assertion is that both are empty or both are non-empty (`assertThat(ffm.getA().isEmpty()).isEqualTo(jna.getA().isEmpty())`).

Applied to files:

  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.java
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsGlobalMemoryTest.java
📚 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
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.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-04-15T04:56:18.352Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3163
File: oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java:97-103
Timestamp: 2026-04-15T04:56:18.352Z
Learning: In CoreFoundationTest.java (oshi-core-java25/src/test/java/oshi/ffm/mac/CoreFoundationTest.java), asserting exact CFGetRetainCount deltas (+1 after retain, -1 after release) is intentional and considered reliable for freshly created CF objects (e.g., CFStringRef via CFStringRef.createCFString) where the test holds sole ownership. Do not flag these assertions as flaky — the Apple "avoid CFGetRetainCount" advisory applies to shared/framework-managed objects, not exclusively owned objects in unit tests.

Applied to files:

  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
📚 Learning: 2026-04-06T04:45:51.516Z
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:51.516Z
Learning: In the oshi/oshi project, the public API is strictly limited to interfaces and classes in the `oshi`, `oshi.hardware`, and `oshi.software.os` packages. All platform-specific code under subpackages like `oshi.software.os.linux`, `oshi.hardware.platform.linux`, etc., is considered implementation detail — not public API. Do not flag changes to platform-specific classes (e.g., making `LinuxOperatingSystem` abstract, narrowing constructor visibility, adding abstract methods) as public API breaks.

Applied to files:

  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxOperatingSystemTest.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.java
📚 Learning: 2026-03-29T20:01:06.452Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java11/src/main/java/module-info.java:10-17
Timestamp: 2026-03-29T20:01:06.452Z
Learning: In the oshi project, `oshi-core-java25/src/main/java/module-info.java` intentionally does NOT export `oshi.util.platform.unix.freebsd`, `oshi.util.platform.unix.openbsd`, or `oshi.util.platform.unix.solaris`, because the FFM (Foreign Function & Memory) implementation only supports Windows, macOS, and Linux. This differs from `oshi-core-java11/src/main/java/module-info.java` which exports all Unix platform packages. The asymmetry is by design.

Applied to files:

  • oshi-common/src/test/java/oshi/software/common/os/linux/LinuxOperatingSystemTest.java
  • oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.java
🔇 Additional comments (12)
oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxFirmwareTest.java (2)

18-18: Good move to use the shared constant import.

Using Constants here removes literal drift risk and keeps test expectations aligned with core constants.


75-75: Nice assertion hardening with Constants.UNKNOWN.

This makes the invalid-date fallback check consistent with production semantics and easier to maintain.

oshi-common/src/test/java/oshi/hardware/common/platform/windows/WindowsGlobalMemoryTest.java (3)

15-21: Nice full-range coverage for memoryType(int)

Great addition. The loop on Lines 19–21 cleanly verifies all 24 defined base memory-type codes and keeps this table-driven test easy to extend.


31-60: Expanded SMBIOS mapping checks look solid

This is a strong coverage improvement. The added assertions across Lines 34–60 exercise previously untested SMBIOS branches and align with the current smBiosMemoryType(int) mapping.


70-73: Good call testing SMBIOS gap values explicitly

The new gap checks on Lines 71–73 make the unknown/default behavior explicit and protect against accidental future regressions.

oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOperatingSystem.java (2)

373-445: Good parser extraction for testability.

Splitting file reads from parse logic here keeps behavior intact while making the parsing paths directly testable and easier to reason about.


454-454: Visibility widening is reasonable in this module.

Making these helpers package-visible to support focused tests is a pragmatic tradeoff in this platform-specific implementation layer. Based on learnings: In the oshi/oshi project, the public API is strictly limited to interfaces and classes in the oshi, oshi.hardware, and oshi.software.os packages; platform-specific subpackages are implementation detail.

Also applies to: 503-503

oshi-common/src/test/java/oshi/software/common/os/linux/LinuxOperatingSystemTest.java (1)

120-222: Great coverage boost on release parsing edge cases.

These tests exercise empty-input handling, alternate release formats, and Constants.UNKNOWN defaults very effectively for the new helper paths.

oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java (1)

587-595: Nice extraction and fallback flow.

Pulling cpuid parsing into a dedicated helper makes this branch much easier to test and maintain.

oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.java (1)

40-60: Great targeted coverage for parseCpuidOutput().

These cases cleanly validate success and null-return paths for the extracted parser logic.

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

69-75: Good coverage expansion for Windows-specific branches.

Enabling CPU utility, suspended procstate, and batched command line in setup is a solid way to exercise previously cold paths in this comparison suite.


382-402: Nice addition: currentProcessUpdateAttributes() validates refreshed process fields.

This test meaningfully strengthens parity checks after updateAttributes() and covers command line/CWD/environment consistency in one place.

@codecov

codecov Bot commented Apr 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 54.54545% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 61.37%. Comparing base (f18b5da) to head (3a50366).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...e/common/platform/linux/LinuxCentralProcessor.java 54.54% 2 Missing and 3 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3211      +/-   ##
==========================================
+ Coverage   61.09%   61.37%   +0.27%     
==========================================
  Files         423      423              
  Lines       20367    20371       +4     
  Branches     3571     3572       +1     
==========================================
+ Hits        12444    12503      +59     
+ Misses       6142     6079      -63     
- Partials     1781     1789       +8     
Flag Coverage Δ
linux 26.09% <54.54%> (+0.06%) ⬆️
macos 29.63% <36.36%> (+0.04%) ⬆️
windows 39.45% <36.36%> (+0.28%) ⬆️

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

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

Caution

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

⚠️ Outside diff range comments (1)
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java (1)

604-617: ⚠️ Potential issue | 🟡 Minor

Validate parsed registers before returning Processor ID.

At Line 616, edx + eax is returned even if one token is missing/malformed, which can return an invalid ID and bypass the fallback path in getProcessorID.

Suggested hardening
 static String parseCpuidOutput(List<String> cpuidLines) {
     for (String checkLine : cpuidLines) {
         if (checkLine.contains("eax=") && checkLine.trim().startsWith("0x00000001")) {
             String eax = "";
             String edx = "";
             for (String register : ParseUtil.whitespaces.split(checkLine)) {
                 if (register.startsWith("eax=")) {
                     eax = ParseUtil.removeMatchingString(register, "eax=0x");
                 } else if (register.startsWith("edx=")) {
                     edx = ParseUtil.removeMatchingString(register, "edx=0x");
                 }
             }
-            return edx + eax;
+            if (eax.matches("(?i)[0-9a-f]{8}") && edx.matches("(?i)[0-9a-f]{8}")) {
+                return edx + eax;
+            }
         }
     }
     return null;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java`
around lines 604 - 617, parseCpuidOutput currently returns edx + eax even when
one or both registers are missing/malformed, which can produce an invalid
processor ID and bypass getProcessorID's fallback; update parseCpuidOutput to
validate the parsed eax and edx before returning (e.g., ensure both are
non-empty and match expected hex digits/length after using
ParseUtil.removeMatchingString), and if validation fails return null (or empty)
so getProcessorID can use its fallback path; reference parseCpuidOutput, eax,
edx, ParseUtil.whitespaces, ParseUtil.removeMatchingString and getProcessorID
when making this change.
♻️ Duplicate comments (1)
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)

546-547: ⚠️ Potential issue | 🟠 Major

Use an absolute delta for loginTime instead of a percentage.

Line 547 compares epoch-millis timestamps with a ratio. That tolerance scales with wall-clock time and can allow very large absolute drift while still passing.

Suggested fix
-                // Login times may differ slightly due to timing
-                assertWithinRatio(f.getLoginTime(), j.getLoginTime(), 0.01, "session[" + key + "].loginTime");
+                // Login times may differ slightly due to timing/source granularity; use absolute millis bound
+                assertThat(Math.abs(f.getLoginTime() - j.getLoginTime()))
+                        .as("session[%s].loginTime", key)
+                        .isLessThanOrEqualTo(5_000L);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java`
around lines 546 - 547, The test in NativeComparisonTest uses
assertWithinRatio(f.getLoginTime(), j.getLoginTime(), 0.01, ...) which is wrong
for epoch-millis; change it to an absolute-delta check comparing
f.getLoginTime() and j.getLoginTime() (e.g., assertWithinDelta or
assertTrue(Math.abs(f.getLoginTime() - j.getLoginTime()) <= MAX_LOGIN_DRIFT))
using a defined MAX_LOGIN_DRIFT in milliseconds (pick a reasonable value like
1000ms) and keep the same message "session[" + key + "].loginTime".
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In
`@oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java`:
- Around line 604-617: parseCpuidOutput currently returns edx + eax even when
one or both registers are missing/malformed, which can produce an invalid
processor ID and bypass getProcessorID's fallback; update parseCpuidOutput to
validate the parsed eax and edx before returning (e.g., ensure both are
non-empty and match expected hex digits/length after using
ParseUtil.removeMatchingString), and if validation fails return null (or empty)
so getProcessorID can use its fallback path; reference parseCpuidOutput, eax,
edx, ParseUtil.whitespaces, ParseUtil.removeMatchingString and getProcessorID
when making this change.

---

Duplicate comments:
In `@oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java`:
- Around line 546-547: The test in NativeComparisonTest uses
assertWithinRatio(f.getLoginTime(), j.getLoginTime(), 0.01, ...) which is wrong
for epoch-millis; change it to an absolute-delta check comparing
f.getLoginTime() and j.getLoginTime() (e.g., assertWithinDelta or
assertTrue(Math.abs(f.getLoginTime() - j.getLoginTime()) <= MAX_LOGIN_DRIFT))
using a defined MAX_LOGIN_DRIFT in milliseconds (pick a reasonable value like
1000ms) and keep the same message "session[" + key + "].loginTime".

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: aaa49816-3806-4023-a9ae-b296b0c66ae8

📥 Commits

Reviewing files that changed from the base of the PR and between a04a7ed and 5991e30.

📒 Files selected for processing (3)
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3174
File: oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java:237-257
Timestamp: 2026-04-19T01:28:47.155Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java`, the WMI comparison tests (e.g., `testProcessor`) intentionally validate only index 0 and a few representative fields per WMI data type (String, uint16, uint32, uint64). Exhaustive row-by-row comparison is deliberately avoided for numerically heavy multi-row tables. The design rationale is: matching row counts + a few selected fields covering each data type is sufficient to verify JNA vs FFM driver parity. Do not suggest looping over all rows for these tests.
📚 Learning: 2026-04-19T01:28:47.155Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3174
File: oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java:237-257
Timestamp: 2026-04-19T01:28:47.155Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java`, the WMI comparison tests (e.g., `testProcessor`) intentionally validate only index 0 and a few representative fields per WMI data type (String, uint16, uint32, uint64). Exhaustive row-by-row comparison is deliberately avoided for numerically heavy multi-row tables. The design rationale is: matching row counts + a few selected fields covering each data type is sufficient to verify JNA vs FFM driver parity. Do not suggest looping over all rows for these tests.

Applied to files:

  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
📚 Learning: 2026-04-18T03:18:06.205Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3170
File: oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java:177-183
Timestamp: 2026-04-18T03:18:06.205Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java`, GPU engine PDH instance counts (from `GpuInformationJNA.queryGpuEngineCounters()` / `GpuInformationFFM.queryGpuEngineCounters()`) are highly volatile — counts can differ dramatically (e.g., 53 vs 40) even between queries taken milliseconds apart. Do not assert instance count equality or exact instance list matching between JNA and FFM results. The only reliable assertion is that both are empty or both are non-empty (`assertThat(ffm.getA().isEmpty()).isEqualTo(jna.getA().isEmpty())`).

Applied to files:

  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
📚 Learning: 2026-04-06T04:45:51.516Z
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:51.516Z
Learning: In the oshi/oshi project, the public API is strictly limited to interfaces and classes in the `oshi`, `oshi.hardware`, and `oshi.software.os` packages. All platform-specific code under subpackages like `oshi.software.os.linux`, `oshi.hardware.platform.linux`, etc., is considered implementation detail — not public API. Do not flag changes to platform-specific classes (e.g., making `LinuxOperatingSystem` abstract, narrowing constructor visibility, adding abstract methods) as public API breaks.

Applied to files:

  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
📚 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
🔇 Additional comments (2)
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)

382-402: Nice coverage addition for updateAttributes() parity checks.

This is a solid, focused test for JNA/FFM refresh behavior, and the added command line/CWD/env assertions are useful regression guards.

oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java (1)

587-595: Good refactor: CPUID parsing extraction keeps fallback behavior intact.

This is a clean extraction that improves testability while preserving the dmidecode → cpuid → encoded fallback order.

- Extract cpuid -1r parsing in LinuxCentralProcessor to a testable
  static parseCpuidOutput() method with unit tests using fixture data
- Enable PROCSTATE_SUSPENDED and COMMANDLINE_BATCH toggles in
  NativeComparisonTest to exercise suspended-state thread logic and
  Win32ProcessCached command line queries
- Add currentProcessUpdateAttributes() test comparing updateAttributes,
  command line, CWD, and environment variables for the current process
- Enhance sessions() test to compare session details (user, device,
  host, login time) field-by-field on Linux
@dbwiddis
dbwiddis force-pushed the improve-oshi-common-coverage branch from 5991e30 to 3a50366 Compare April 29, 2026 00:15

@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-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)

382-398: Add CWD and environment variable parity assertions to currentProcessUpdateAttributes().

The test validates refresh success and basic field parity, but the current assertions don't check the current working directory and environment variables—exactly what this PR targets. Since both getCurrentWorkingDirectory() and getEnvironmentVariables() are exposed in the OSProcess interface and implemented across all platforms (including FFM), adding these assertions strengthens the parity verification:

Suggested patch
     void currentProcessUpdateAttributes() {
         int pid = jnaOs.getProcessId();
         OSProcess jna = jnaOs.getProcess(pid);
         OSProcess ffm = ffmOs.getProcess(pid);
         assertThat(jna).isNotNull();
         assertThat(ffm).isNotNull();
         // Call updateAttributes to refresh and verify it succeeds
         assertThat(jna.updateAttributes()).as("JNA updateAttributes").isTrue();
         assertThat(ffm.updateAttributes()).as("FFM updateAttributes").isTrue();
         // After refresh, basic fields should still match
         assertThat(ffm.getName()).isEqualTo(jna.getName());
         assertThat(ffm.getState()).isEqualTo(jna.getState());
         assertThat(ffm.getProcessID()).isEqualTo(jna.getProcessID());
         // Command line exercises Win32ProcessCached when batch mode is enabled
         assertThat(ffm.getCommandLine()).isEqualTo(jna.getCommandLine());
+        assertThat(ffm.getCurrentWorkingDirectory()).isEqualTo(jna.getCurrentWorkingDirectory());
+        assertThat(ffm.getEnvironmentVariables()).isEqualTo(jna.getEnvironmentVariables());
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java`
around lines 382 - 398, The test currentProcessUpdateAttributes() should also
assert parity of the current working directory and environment variables between
the two OSProcess implementations; after the existing updateAttributes() calls
and other equality assertions, add assertions comparing
ffm.getCurrentWorkingDirectory() to jna.getCurrentWorkingDirectory() and
ffm.getEnvironmentVariables() to jna.getEnvironmentVariables(), taking care to
handle possible nulls/empty maps consistently when comparing these values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java`:
- Around line 382-398: The test currentProcessUpdateAttributes() should also
assert parity of the current working directory and environment variables between
the two OSProcess implementations; after the existing updateAttributes() calls
and other equality assertions, add assertions comparing
ffm.getCurrentWorkingDirectory() to jna.getCurrentWorkingDirectory() and
ffm.getEnvironmentVariables() to jna.getEnvironmentVariables(), taking care to
handle possible nulls/empty maps consistently when comparing these values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 989690d6-361a-4874-82d0-ebf1fcbcf402

📥 Commits

Reviewing files that changed from the base of the PR and between 5991e30 and 3a50366.

📒 Files selected for processing (3)
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-common/src/test/java/oshi/hardware/common/platform/linux/LinuxCentralProcessorTest.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (5)
📚 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-04-19T01:28:47.155Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3174
File: oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java:237-257
Timestamp: 2026-04-19T01:28:47.155Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/WmiComparisonTest.java`, the WMI comparison tests (e.g., `testProcessor`) intentionally validate only index 0 and a few representative fields per WMI data type (String, uint16, uint32, uint64). Exhaustive row-by-row comparison is deliberately avoided for numerically heavy multi-row tables. The design rationale is: matching row counts + a few selected fields covering each data type is sufficient to verify JNA vs FFM driver parity. Do not suggest looping over all rows for these tests.

Applied to files:

  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
📚 Learning: 2026-04-18T03:18:06.205Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3170
File: oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java:177-183
Timestamp: 2026-04-18T03:18:06.205Z
Learning: In `oshi-benchmark/src/test/java/oshi/comparison/PerfmonComparisonTest.java`, GPU engine PDH instance counts (from `GpuInformationJNA.queryGpuEngineCounters()` / `GpuInformationFFM.queryGpuEngineCounters()`) are highly volatile — counts can differ dramatically (e.g., 53 vs 40) even between queries taken milliseconds apart. Do not assert instance count equality or exact instance list matching between JNA and FFM results. The only reliable assertion is that both are empty or both are non-empty (`assertThat(ffm.getA().isEmpty()).isEqualTo(jna.getA().isEmpty())`).

Applied to files:

  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
📚 Learning: 2026-04-06T04:45:51.516Z
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:51.516Z
Learning: In the oshi/oshi project, the public API is strictly limited to interfaces and classes in the `oshi`, `oshi.hardware`, and `oshi.software.os` packages. All platform-specific code under subpackages like `oshi.software.os.linux`, `oshi.hardware.platform.linux`, etc., is considered implementation detail — not public API. Do not flag changes to platform-specific classes (e.g., making `LinuxOperatingSystem` abstract, narrowing constructor visibility, adding abstract methods) as public API breaks.

Applied to files:

  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
🔇 Additional comments (5)
oshi-common/src/main/java/oshi/hardware/common/platform/linux/LinuxCentralProcessor.java (2)

587-595: Nice refactor of cpuid fallback flow.

Good extraction here: the control path is still clear and deterministic, and the fallback order is preserved while making the cpuid parse path unit-testable.


598-622: Helper parsing logic looks robust for malformed cpuid lines.

The method cleanly handles missing leafs/registers and returns null safely, which fits the downstream fallback behavior in getProcessorID(...).

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

44-44: Good explicit OSSession import.

Nice small cleanup to support typed session comparisons in this class.


72-75: Good toggle coverage expansion in setup.

Enabling suspended-state and batch command-line paths here is a practical way to exercise Windows-specific branches in the parity suite.


529-546: Nice improvement to Linux session matching.

Keyed matching plus bounded absolute login-time delta is a stronger and less permissive comparison strategy than ratio-based timestamp checks.

@dbwiddis
dbwiddis merged commit 75fdb0f into oshi:master Apr 29, 2026
16 checks passed
@dbwiddis
dbwiddis deleted the improve-oshi-common-coverage branch April 29, 2026 00:23
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