Repository navigation
Consolidate remaining FFM catch arms onto ExceptionUtil / ForeignFunctions helpers - #3355
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (7)
🚧 Files skipped from review as they are similar to previous changes (6)
📜 Recent 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). (15)
🧰 Additional context used🧠 Learnings (3)📓 Common learnings📚 Learning: 2026-04-03T18:44:48.200ZApplied to files:
📚 Learning: 2026-03-29T20:01:06.452ZApplied to files:
🔇 Additional comments (3)
📝 WalkthroughWalkthroughThis PR extends ChangesStructured exception logging with configurable levels
File system test coverage for platform-specific behavior
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #3355 +/- ##
============================================
+ Coverage 74.96% 75.02% +0.06%
Complexity 76 76
============================================
Files 602 602
Lines 25832 25832
Branches 3984 3983 -1
============================================
+ Hits 19364 19381 +17
+ Misses 4217 4199 -18
- Partials 2251 2252 +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
🧹 Nitpick comments (2)
pom.xml (1)
827-827: ⚡ Quick winDocument the rationale for excluding all FFM code from coverage.
The blanket
**/ffm/**exclusion lacks an explanatory comment (unlike other exclusion categories at lines 832–836, 840, 857, etc.) and makes many existing specific FFM exclusions redundant (e.g.,**/LinuxGpuStatsFFM*at line 846,**/WindowsGraphicsCardFFM*at line 862).If FFM code is excluded because it requires Java 25+ and is difficult to exercise in CI (similar to the rationale for JNA), consider adding a comment to document this. If the exclusion is meant to be temporary or only applies to certain FFM modules, prefer keeping the specific exclusions rather than a catch-all pattern.
📝 Suggested comment addition
<exclude>**/demo/**</exclude> + <!-- FFM (Foreign Function & Memory) integration layer: requires Java 25+ and native access setup --> <exclude>**/ffm/**</exclude> <exclude>**/jna/**</exclude>🤖 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 `@pom.xml` at line 827, Add a short explanatory comment above the blanket coverage exclusion "**/ffm/**" in the pom.xml indicating why all FFM code is excluded (e.g., requires Java 25+, difficult to exercise in CI, or temporary exclusion), and clarify scope (global vs specific modules) and intended duration; if the exclusion is meant to apply only to certain FFM classes instead of all FFM code, remove the catch‑all and retain the existing specific exclusions such as "**/LinuxGpuStatsFFM*" and "**/WindowsGraphicsCardFFM*" to avoid overbroad coverage gaps.oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java (1)
307-385: 🏗️ Heavy liftThese tests don't verify the new level-aware behavior.
This block only checks the return defaults and “does not throw” paths. If
ExceptionUtilignored the suppliedleveland always logged atDEBUG, or stopped attaching the thrown cause, every added test here would still pass. Please capture one emitted event or mock the logger/builder for at least one overload so the new contract is actually pinned down.🤖 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-common/src/test/java/oshi/util/ExceptionUtilTest.java` around lines 307 - 385, Add a test that actually verifies the level-aware logging behavior by capturing/emulating the logger and asserting the emitted event contains the configured Level and the thrown cause: instrument the existing tests (e.g., testGetOrDefaultWithTraceLevel or testRunOrLogWithTraceLevel) to replace LOG with a mock or a test appender (or Mockito spy) and assert that ExceptionUtil.getOrDefault (or ExceptionUtil.runOrLog) logs at Level.TRACE and includes the RuntimeException as the logged throwable; update only one overload test to perform this capture so the contract is pinned down.
🤖 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/util/ExceptionUtil.java`:
- Around line 154-160: The log calls in ExceptionUtil (e.g., getOrDefault and
the other overloaded methods in this class) incorrectly pass the Throwable twice
by calling log(msg, t) after setCause(t), so the `{}` placeholder is not
populated; change each occurrence to pass the exception message (t.getMessage())
as the parameter to log (or call log(msg) if no `{}` is present) and keep
setCause(t) so the stacktrace is attached only once—update every instance around
the methods named getOrDefault and the other exception-handling overloads to
remove the throwable from the varargs and use t.getMessage() for `{}`
substitution.
---
Nitpick comments:
In `@oshi-common/src/test/java/oshi/util/ExceptionUtilTest.java`:
- Around line 307-385: Add a test that actually verifies the level-aware logging
behavior by capturing/emulating the logger and asserting the emitted event
contains the configured Level and the thrown cause: instrument the existing
tests (e.g., testGetOrDefaultWithTraceLevel or testRunOrLogWithTraceLevel) to
replace LOG with a mock or a test appender (or Mockito spy) and assert that
ExceptionUtil.getOrDefault (or ExceptionUtil.runOrLog) logs at Level.TRACE and
includes the RuntimeException as the logged throwable; update only one overload
test to perform this capture so the contract is pinned down.
In `@pom.xml`:
- Line 827: Add a short explanatory comment above the blanket coverage exclusion
"**/ffm/**" in the pom.xml indicating why all FFM code is excluded (e.g.,
requires Java 25+, difficult to exercise in CI, or temporary exclusion), and
clarify scope (global vs specific modules) and intended duration; if the
exclusion is meant to apply only to certain FFM classes instead of all FFM code,
remove the catch‑all and retain the existing specific exclusions such as
"**/LinuxGpuStatsFFM*" and "**/WindowsGraphicsCardFFM*" to avoid overbroad
coverage gaps.
🪄 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
Run ID: 0b2ea1d7-7d16-4020-a5cf-8f3bb6b2c47e
📒 Files selected for processing (7)
oshi-common/src/main/java/oshi/util/ExceptionUtil.javaoshi-common/src/test/java/oshi/util/ExceptionUtilTest.javaoshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.javaoshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.javapom.xml
📜 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). (17)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
- GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
- GitHub Check: Test JDK 21, macos-latest
- GitHub Check: Test JDK 21, windows-latest
- GitHub Check: Test JDK 26, ubuntu-latest
- GitHub Check: Test JDK 26, windows-latest
- GitHub Check: Test JDK 26, macos-latest
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: JMH Benchmarks, windows-latest
- GitHub Check: JMH Benchmarks, ubuntu-latest
- GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
- GitHub Check: JMH Benchmarks, macos-latest
- GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
- GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (7)
📓 Common learnings
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.
📚 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:
pom.xmloshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
📚 Learning: 2026-04-03T02:07:49.467Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:49.467Z
Learning: In `oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java` (and similar FFM/API implementations in OSHI), the `updateAttributes()` method intentionally uses `catch (Throwable e) { return false; }` without logging. This is by design: `updateAttributes()` is a public API method whose contract is to return `false` on failure; callers consume the boolean and would never see log output, so adding a log statement is not desired.
Applied to files:
oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.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-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java
📚 Learning: 2026-04-17T23:43:35.860Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3168
File: oshi-core-java25/src/main/java/oshi/ffm/windows/PdhFFM.java:0-0
Timestamp: 2026-04-17T23:43:35.860Z
Learning: In `oshi-core-java25/src/main/java/oshi/ffm/windows/PdhFFM.java`, the `PDH_RAW_COUNTER_LAYOUT` Java FFM struct layout must place `FirstValue` at byte offset 16 (not 12). The native MSVC compiler inserts 4 bytes of implicit alignment padding before the `LONGLONG FirstValue` field (after CStatus=4 bytes + FILETIME TimeStamp=8 bytes = 12 bytes), because LONGLONG requires 8-byte alignment. The total struct size is 40 bytes (with trailing padding). Do not use JAVA_LONG_UNALIGNED without explicit padding here, as that incorrectly places FirstValue at offset 12 and causes reads of garbage counter values.
Applied to files:
oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.javaoshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.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/util/ExceptionUtil.java
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.
Applied to files:
oshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java
🔇 Additional comments (10)
oshi-core-ffm/src/main/java/oshi/driver/mac/IOReportClientFFM.java (2)
7-8: LGTM!Also applies to: 18-20, 40-40
115-130: LGTM!oshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java (2)
11-12: LGTM!
106-136: LGTM!oshi-core-ffm/src/main/java/oshi/software/os/mac/MacInternetProtocolStatsFFM.java (4)
11-12: LGTM!Also applies to: 57-57, 68-70, 84-84
152-176: LGTM!
181-198: LGTM!
202-262: LGTM!oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java (2)
13-14: LGTM!
473-605: LGTM!
…tions helpers Continuation of the centralisation work from #3352. Six more `try { ... } catch (Throwable) { return default; }` sites now route their swallow-and-return through the existing `ExceptionUtil` / `ForeignFunctions` helpers so the catch-and-default behaviour lives in one tested place per pattern: * `IOReportClientFFM.sampleGpuTicks`, `MacInternetProtocolStatsFFM.queryFdList`, and `MacInternetProtocolStatsFFM.queryIPConnection` move to `ExceptionUtil.getOrDefault` (no Arena owned at the catch site). * `HkeyUserDataFFM.lookupAccountBySid`, `MacInternetProtocolStatsFFM.getConnections`, and `MacOSProcessFFM.updateAttributes` move to `ForeignFunctions.callInArenaOrDefault` / `callInArenaBooleanOrDefault` — these are catches paired with `try (Arena = Arena.ofConfined())` that the heuristic missed in #3352. `updateAttributes` hoists its `this.state = INVALID` side-effect outside the helper so the catch arm itself stays pure. `ExceptionUtil` grows `Level`-taking overloads in parity with `ForeignFunctions.callInArenaOrDefault`'s signature. Existing `(supplier, default, log, msg)` methods become one-line delegates passing `Level.DEBUG`, preserving behaviour for the 20+ existing callers. New call sites log at `TRACE`: SLF4J's level guard collapses to a single JIT-inlined `isTraceEnabled()` check when TRACE is not configured, so the success-path cost is effectively zero, while turning TRACE on for the offending class surfaces the swallowed throwable when debugging. The fluent log call passes `t.getMessage()` as the substitution argument (matching `ForeignFunctions`'s pattern), so `{}` placeholders in caller messages render as the throwable's message string rather than its full `toString()`. No public API removal, no signature changes — JAPICMP stays quiet. `IOReportClientFFM.sampleGpuUtilization` (L167) and `samplePowerWatts` (L221) were considered but left as-is: their outer `finally { cfRelease(sample); }` cleanup with mid-body sample ownership transfer doesn't fit the helper's try/catch/default shape without a structural refactor that costs more clarity than it recovers. Folds in two unrelated fixes that surfaced from CI on the prior push: * `FileSystemTest` now skips the "total space should not change after update" assertion on FreeBSD in addition to Solaris — ZFS pools report a dynamically computed total that can fluctuate by a few MB between back-to-back queries due to pool/dataset metadata refresh. Uses an `EnumSet` named `FLUCTUATING_TOTAL_SPACE` so future platforms with the same behaviour can be added without growing the conditional. DragonFly's HAMMER2 doesn't share this property, so it's left out. A planned `**/ffm/**` jacoco exclusion (mirroring the existing `**/jna/**`) was prepared and then dropped from this PR — it accidentally drops 25 real driver classes in `oshi.ffm.driver.*` (AIX perfstat, Solaris PsInfo + kstat, Windows InstalledApps) from coverage. The underlying structure needs cleanup first: those drivers belong in `oshi.driver.*` alongside the Mac/Linux/Windows FFM drivers, and the Windows FFM mapping files (`*FFM.java`) should follow the same `*Functions.java` convention used elsewhere. Handle in a follow-up PR.
9118bc3 to
a94832d
Compare
Summary
Follow-up to #3352 that finishes the FFM catch-arm consolidation. Six remaining
try { ... } catch (Throwable) { return default; }sites now route through the existingExceptionUtil/ForeignFunctionshelpers so the swallow-and-default behaviour lives in one tested place per pattern.IOReportClientFFM.sampleGpuTicks,MacInternetProtocolStatsFFM.queryFdList,MacInternetProtocolStatsFFM.queryIPConnection→ExceptionUtil.getOrDefault.trykeywords instead of the outertry (Arena)):HkeyUserDataFFM.lookupAccountBySid,MacInternetProtocolStatsFFM.getConnections,MacOSProcessFFM.updateAttributes→ForeignFunctions.callInArenaOrDefault/callInArenaBooleanOrDefault.updateAttributeshoists itsthis.state = INVALIDside-effect outside the helper so the catch arm itself stays pure.ExceptionUtilgrowsLevel-taking overloads in parity withForeignFunctions.callInArenaOrDefault's signature. Existing(supplier, default, log, msg)methods become one-line delegates that passLevel.DEBUG, preserving behaviour for the 20+ existing callers. New call sites log atTRACE: SLF4J's level guard resolves to a single JIT-inlinedisTraceEnabled()check when TRACE isn't configured, so the success-path cost is effectively zero; enabling TRACE on the offending class surfaces the swallowed throwable when debugging. No public API removal, no signature changes — JAPICMP stays quiet (andExceptionUtilis not annotated@PublicApieither way).Per-file:
oshi-common/.../ExceptionUtil.javaLevel-taking overloads; 9 existing methods become delegatesoshi-common/.../ExceptionUtilTest.javaoshi-core-ffm/.../IOReportClientFFM.javasampleGpuTicks→getOrDefaultoshi-core-ffm/.../HkeyUserDataFFM.javalookupAccountBySid→callInArenaOrDefaultoshi-core-ffm/.../MacInternetProtocolStatsFFM.javaoshi-core-ffm/.../MacOSProcessFFM.javaupdateAttributes→callInArenaBooleanOrDefault;state = INVALIDhoisted outside helperSites intentionally left alone:
IOReportClientFFM.sampleGpuUtilization(L167) andsamplePowerWatts(L221). Their outerfinally { cfRelease(sample); }cleanup with mid-body sample ownership transfer doesn't fit the helper's try/catch/default shape without a structural refactor that costs more clarity than it recovers.Coverage parity (
pom.xml)JaCoCo's
<excludes>adds**/ffm/**alongside the existing**/jna/**. Both namespaces are mostly FFM/JNA mapping declarations and helper utilities whose coverage tells us little. The implementation classes (*FFMand*JNAinhardware.platform.*andsoftware.os.*) stay in scope.Test plan
./mvnw -pl oshi-common,oshi-core-ffm -am spotless:apply checkstyle:check install javadoc:javadoc -DskipTests— all gates pass locally./mvnw -pl oshi-common,oshi-core-ffm -am test— full suite green on macOS arm64; 10 new ExceptionUtil tests addedSummary by CodeRabbit
New Features
Tests