Repository navigation
Add voluntary/involuntary context switch methods to OSProcess - #3232
Conversation
📝 WalkthroughWalkthroughAdds distinct voluntary and involuntary context-switch counters across platforms, implements getrusage bindings (JNA and FFM) to populate per-process counters on Linux/macOS, updates BSD/Solaris parsing to split NVCSW/NIVCSW, adjusts metrics wiring and tests, and records the change in CHANGELOG.md. ChangesContext Switch Split & getrusage Integration
Sequence Diagram(s)sequenceDiagram
participant Process as OSProcess
participant Impl as PlatformImpl
participant Native as JNA/FFM
participant Kernel as Kernel
Process->>Impl: request getVoluntaryContextSwitches()
Impl->>Native: getrusage(RUSAGE_SELF, rusage)
Native->>Kernel: downcall getrusage
Kernel-->>Native: returns rusage (ru_nvcsw / ru_nivcsw)
Native-->>Impl: rusage populated
Impl-->>Process: return voluntary/involuntary (cached or parsed)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 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❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #3232 +/- ##
=========================================
Coverage 63.72% 63.72%
Complexity 73 73
=========================================
Files 421 421
Lines 19439 19518 +79
Branches 3390 3400 +10
=========================================
+ Hits 12387 12438 +51
- Misses 5318 5337 +19
- Partials 1734 1743 +9
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
d647157 to
68da30d
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java (1)
486-493: ⚡ Quick winUse
this.os.getProcessId()for the current-process check, matching the pattern ingetSoftOpenFileLimit()andgetHardOpenFileLimit().
getSoftOpenFileLimit()/getHardOpenFileLimit()at lines 359 and 370 already usegetProcessID() == this.os.getProcessId()for the same purpose. Callingoshi.jna.platform.mac.SystemB.INSTANCE.getpid()here introduces an extra native call and requires a fully-qualified type to disambiguate from the already-importedcom.sun.jna.platform.mac.SystemB.Additionally, add a brief comment noting that
getrusage(RUSAGE_SELF)aggregates across all threads of the calling process, whilepti_csw(which feedscontextSwitches) is the task counter—sovoluntary + involuntaryis not guaranteed to equalgetContextSwitches().♻️ Proposed simplification
- // getrusage provides voluntary/involuntary split for the current process - if (getProcessID() == oshi.jna.platform.mac.SystemB.INSTANCE.getpid()) { - CLibrary.Rusage rusage = new CLibrary.Rusage(); - if (0 == oshi.jna.platform.mac.SystemB.INSTANCE.getrusage(CLibrary.RUSAGE_SELF, rusage)) { - this.voluntaryContextSwitches = rusage.ru_nvcsw.longValue(); - this.involuntaryContextSwitches = rusage.ru_nivcsw.longValue(); - } - } + // getrusage(RUSAGE_SELF) aggregates voluntary/involuntary across all threads of the + // calling process; only available for the current process. Note: this counter is + // distinct from PROC_PIDTASKALLINFO's pti_csw, so the per-type values may not sum to + // getContextSwitches() exactly. + if (getProcessID() == this.os.getProcessId()) { + CLibrary.Rusage rusage = new CLibrary.Rusage(); + if (0 == oshi.jna.platform.mac.SystemB.INSTANCE.getrusage(CLibrary.RUSAGE_SELF, rusage)) { + this.voluntaryContextSwitches = rusage.ru_nvcsw.longValue(); + this.involuntaryContextSwitches = rusage.ru_nivcsw.longValue(); + } + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java` around lines 486 - 493, Replace the current-process check in the MacOSProcessJNA block that calls oshi.jna.platform.mac.SystemB.INSTANCE.getpid() with the existing pattern used in getSoftOpenFileLimit()/getHardOpenFileLimit(): compare getProcessID() == this.os.getProcessId(); remove the fully-qualified SystemB call to avoid the extra native call and disambiguation. Keep the CLibrary.Rusage/rusage and getrusage(RUSAGE_SELF) usage but add a brief comment noting that getrusage(RUSAGE_SELF) aggregates across all threads of the calling process while pti_csw (used for contextSwitches) is a per-task counter, so voluntaryContextSwitches + involuntaryContextSwitches may not equal getContextSwitches().
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java`:
- Around line 447-451: The parsed NVCSW/NIVCSW values are assigned to the wrong
variables, causing voluntary/involuntary context switch counts to be swapped; in
FreeBsdOSProcess (and mirror the change in FreeBsdOSThread) change the
parsing/assignment so PsKeywords.NVCSW is stored as voluntaryContextSwitches and
PsKeywords.NIVCSW as involuntaryContextSwitches, then compute contextSwitches as
their sum and set the instance fields this.voluntaryContextSwitches and
this.involuntaryContextSwitches accordingly (update any local variable names if
necessary to reflect the correct semantics).
---
Nitpick comments:
In `@oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java`:
- Around line 486-493: Replace the current-process check in the MacOSProcessJNA
block that calls oshi.jna.platform.mac.SystemB.INSTANCE.getpid() with the
existing pattern used in getSoftOpenFileLimit()/getHardOpenFileLimit(): compare
getProcessID() == this.os.getProcessId(); remove the fully-qualified SystemB
call to avoid the extra native call and disambiguation. Keep the
CLibrary.Rusage/rusage and getrusage(RUSAGE_SELF) usage but add a brief comment
noting that getrusage(RUSAGE_SELF) aggregates across all threads of the calling
process while pti_csw (used for contextSwitches) is a per-task counter, so
voluntaryContextSwitches + involuntaryContextSwitches may not equal
getContextSwitches().
🪄 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: 213df32c-9f7f-473e-ba26-5ea828231d24
📒 Files selected for processing (10)
CHANGELOG.mdoshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.javaoshi-common/src/main/java/oshi/software/os/OSProcess.javaoshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.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). (2)
- GitHub Check: Analyze (java)
- GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).
Applied to files:
oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.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/software/os/OSProcess.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
🔇 Additional comments (9)
oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java (1)
112-120: LGTM!The split into two
FunctionCounters with distinctprocess.context_switch.typetags (voluntary/involuntary) correctly matches the OpenTelemetry semantic convention forprocess.context_switches.oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.java (1)
401-403: LGTM — Solaris field mapping is correct.
pr_vctxandpr_ictxfrom the Solarisprusage_tcorrespond to voluntary and involuntary context switches respectively, so the assignments and the sum intocontextSwitchesare correct.oshi-common/src/main/java/oshi/software/os/OSProcess.java (1)
434-458: LGTM — clean, backwards-compatible additions.Default 0L matches the existing
getMinorFaults/getMajorFaultspattern, and the Javadoc correctly documents the platform constraints (Linux for any pid, macOS/POSIX limited to the current process viagetrusage(RUSAGE_SELF)). RetaininggetContextSwitches()preserves source/binary compatibility for existing callers.oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java (1)
444-448: LGTM — Linux mapping is correct.
/proc/[pid]/statusexposesvoluntary_ctxt_switchesandnonvoluntary_ctxt_switches(kernel uses "nonvoluntary" but the semantic is involuntary), so the field assignments and the retained sum intocontextSwitchesare right.Note (out of scope but worth tracking for the follow-up referenced in the PR description): per issue
#2904, these/procvalues count only the main thread. If you later addgetrusage(RUSAGE_SELF)on Linux for the current process to aggregate across threads, please update the OSProcess Javadoc — it currently mentions getrusage only for macOS/POSIX, which could mislead Linux callers about the current behavior.oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.java (4)
35-35: Import addition looks correct.
Resourceis now directly used in this class (Resource.Rlimit), so this import is valid.
110-111: Good split of context-switch state.Introducing dedicated fields for voluntary/involuntary context switches is consistent with the new API shape.
392-400: New getters are implemented cleanly.These accessors correctly expose the split counters without altering existing semantics.
467-470: Aggregation logic is consistent.
voluntary + involuntary -> totalkeepsgetContextSwitches()aligned with the new split fields.oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)
394-400: Nice coverage expansion for split context-switch metrics.These assertions are aligned with the new process API and validate parity expectations between JNA and FFM implementations.
aec53b1 to
4601743
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
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/software/os/OSProcess.java (1)
420-458:⚠️ Potential issue | 🟠 Major | ⚡ Quick winKeep the aggregate contract and platform notes consistent with the new split counters.
The interface now introduces per-type context-switch getters, but the default
getContextSwitches()still hardcodes0, so an implementation can expose non-zero split values while the aggregate remains wrong. The new Javadocs also overstate Linux semantics and understate BSD/Solaris support:/proc/[pid]/statusis not an all-threads aggregate on Linux, while other Unix implementations in this PR do return values for non-current processes. That leaves the public API self-contradictory right at the contract layer.🤖 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/main/java/oshi/software/os/OSProcess.java` around lines 420 - 458, The default getContextSwitches() should not hardcode 0 while split counters may be non-zero—change its implementation to return getVoluntaryContextSwitches() + getInvoluntaryContextSwitches(), and update the Javadoc for getContextSwitches(), getVoluntaryContextSwitches(), and getInvoluntaryContextSwitches() to accurately describe platform semantics (e.g., clarify that on Linux values come from /proc/[pid]/status for the process (not per-thread aggregation) and that BSD/Solaris/other POSIX systems may provide per-process values for non-current processes via their rusage or equivalent) so the aggregate contract is consistent with the per-type getters.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@oshi-core/src/main/java/oshi/driver/mac/MacContextSwitchDriver.java`:
- Around line 33-35: getContextSwitches currently returns the actual mutable
long[] stored in the memoized CS_MAP which allows callers to mutate cached
state; change it to fetch the array from CS_MAP (via
CS_MAP.get().getOrDefault(pid, new long[] {0L,0L})) into a local variable and
return a defensive copy (e.g., Arrays.copyOf(..., length)) so callers cannot
modify the cached array; ensure you import java.util.Arrays if necessary and use
the same approach for both cached and default arrays.
In `@oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java`:
- Around line 486-498: The code currently uses taskAllInfo.ptinfo.pti_csw for
this.contextSwitches but sets voluntary/involuntary from getrusage or
MacContextSwitchDriver, causing possible mismatch; after assigning
voluntaryContextSwitches and involuntaryContextSwitches (in both the Rusage
branch and the MacContextSwitchDriver branch), recompute and set
this.contextSwitches = this.voluntaryContextSwitches +
this.involuntaryContextSwitches so all three getters reflect the same snapshot
(refer to variables/methods: contextSwitches, voluntaryContextSwitches,
involuntaryContextSwitches, taskAllInfo.ptinfo.pti_csw, rusage.ru_nvcsw,
rusage.ru_nivcsw, MacContextSwitchDriver.getContextSwitches(getProcessID())).
---
Outside diff comments:
In `@oshi-common/src/main/java/oshi/software/os/OSProcess.java`:
- Around line 420-458: The default getContextSwitches() should not hardcode 0
while split counters may be non-zero—change its implementation to return
getVoluntaryContextSwitches() + getInvoluntaryContextSwitches(), and update the
Javadoc for getContextSwitches(), getVoluntaryContextSwitches(), and
getInvoluntaryContextSwitches() to accurately describe platform semantics (e.g.,
clarify that on Linux values come from /proc/[pid]/status for the process (not
per-thread aggregation) and that BSD/Solaris/other POSIX systems may provide
per-process values for non-current processes via their rusage or equivalent) so
the aggregate contract is consistent with the per-type getters.
🪄 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: 9610b23e-2441-43da-a4bf-a62b7e4115dc
📒 Files selected for processing (11)
CHANGELOG.mdoshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.javaoshi-common/src/main/java/oshi/software/os/OSProcess.javaoshi-core/src/main/java/oshi/driver/mac/MacContextSwitchDriver.javaoshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.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). (2)
- GitHub Check: Analyze (java)
- GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).
Applied to files:
oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.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/software/os/OSProcess.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
🔇 Additional comments (3)
oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java (1)
447-451:NVCSW/NIVCSWstill look swapped here.
NVCSWis the voluntary count andNIVCSWis the involuntary count, but the assignments still invert the two new getters. That leaves FreeBSD reporting the right total with the two component metrics reversed.oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java (1)
33-33: Good metric split with stable naming/tagged dimensions.This update cleanly moves
process.context_switchesto voluntary/involuntary series while keeping the metric name stable and adding explicit type tags.Also applies to: 113-120
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)
394-400: Nice coverage expansion for context-switch parity checks.Adding assertions for total + voluntary + involuntary counters strengthens regression detection for the new process metrics split.
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java (1)
486-498:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRecompute
contextSwitchesfrom the split counters.
getContextSwitches()still comes frompti_csw, while the new getters come fromgetrusage()/MacContextSwitchDriver. If those sources differ, the three getters stop describing the same snapshot andgetContextSwitches()no longer matches the documented combined sum.🐛 Minimal fix
- this.contextSwitches = taskAllInfo.ptinfo.pti_csw; + this.voluntaryContextSwitches = 0L; + this.involuntaryContextSwitches = 0L; // Use native getrusage for current process (fast), memoized ps batch for others if (getProcessID() == oshi.jna.platform.mac.SystemB.INSTANCE.getpid()) { CLibrary.Rusage rusage = new CLibrary.Rusage(); if (0 == oshi.jna.platform.mac.SystemB.INSTANCE.getrusage(CLibrary.RUSAGE_SELF, rusage)) { this.voluntaryContextSwitches = rusage.ru_nvcsw.longValue(); this.involuntaryContextSwitches = rusage.ru_nivcsw.longValue(); } } else { long[] csw = MacContextSwitchDriver.getContextSwitches(getProcessID()); this.voluntaryContextSwitches = csw[0]; this.involuntaryContextSwitches = csw[1]; } + this.contextSwitches = this.voluntaryContextSwitches + this.involuntaryContextSwitches;🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java` around lines 486 - 498, The current code sets contextSwitches from taskAllInfo.ptinfo.pti_csw (pti_csw) but then sets voluntaryContextSwitches and involuntaryContextSwitches from getrusage() or MacContextSwitchDriver.getContextSwitches(), which can diverge; update the logic in the MacOSProcessJNA constructor (or initializer where contextSwitches, voluntaryContextSwitches, involuntaryContextSwitches are assigned) to recompute this.contextSwitches as the sum of voluntaryContextSwitches and involuntaryContextSwitches after those two are obtained (i.e., call CLibrary.Rusage->ru_nvcsw/ru_nivcsw or MacContextSwitchDriver.getContextSwitches(getProcessID()) to set voluntaryContextSwitches and involuntaryContextSwitches, then set contextSwitches = voluntaryContextSwitches + involuntaryContextSwitches) so getContextSwitches() matches the documented combined sum instead of relying on pti_csw.
🧹 Nitpick comments (1)
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)
394-400: ⚡ Quick winAdd the total-vs-split invariant here too.
These assertions only check JNA vs FFM monotonicity, so they won't catch an implementation returning
getContextSwitches()from a different source thanvoluntary + involuntary. A platform-gated equality assertion here would lock in the new contract and catch that regression quickly.🤖 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-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java` around lines 394 - 400, Add a platform-gated invariant asserting that getContextSwitches() equals getVoluntaryContextSwitches() + getInvoluntaryContextSwitches() to ensure the total is computed from the split values; locate the check near the other context-switch assertions in NativeComparisonTest (after the FFM vs JNA monotonicity assertions) and wrap it in the same platform gating used elsewhere in the test so it only runs on platforms where the split totals are expected to match the combined total.
🤖 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/software/os/OSProcess.java`:
- Around line 438-454: Update the Javadoc wording to avoid the absolute claim
about POSIX support: change the phrase "on all POSIX platforms" to "on POSIX
platforms where implemented" (or similar) in the Javadocs for
getVoluntaryContextSwitches() and the following involuntary context switches
method so the interface accurately reflects that getrusage(RUSAGE_SELF) is used
where implemented rather than universally.
In `@oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java`:
- Around line 25-45: Override getContextSwitches() in LinuxOSProcessJNA so that
when the process is the current process (use getProcessID() ==
getOs().getProcessId()) it returns the sum of getVoluntaryContextSwitches() and
getInvoluntaryContextSwitches(); otherwise fall back to
super.getContextSwitches(). Implement the override in the same class alongside
existing getVoluntaryContextSwitches() and getInvoluntaryContextSwitches() to
preserve consistency between the split getters and the total.
---
Duplicate comments:
In `@oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java`:
- Around line 486-498: The current code sets contextSwitches from
taskAllInfo.ptinfo.pti_csw (pti_csw) but then sets voluntaryContextSwitches and
involuntaryContextSwitches from getrusage() or
MacContextSwitchDriver.getContextSwitches(), which can diverge; update the logic
in the MacOSProcessJNA constructor (or initializer where contextSwitches,
voluntaryContextSwitches, involuntaryContextSwitches are assigned) to recompute
this.contextSwitches as the sum of voluntaryContextSwitches and
involuntaryContextSwitches after those two are obtained (i.e., call
CLibrary.Rusage->ru_nvcsw/ru_nivcsw or
MacContextSwitchDriver.getContextSwitches(getProcessID()) to set
voluntaryContextSwitches and involuntaryContextSwitches, then set
contextSwitches = voluntaryContextSwitches + involuntaryContextSwitches) so
getContextSwitches() matches the documented combined sum instead of relying on
pti_csw.
---
Nitpick comments:
In `@oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java`:
- Around line 394-400: Add a platform-gated invariant asserting that
getContextSwitches() equals getVoluntaryContextSwitches() +
getInvoluntaryContextSwitches() to ensure the total is computed from the split
values; locate the check near the other context-switch assertions in
NativeComparisonTest (after the FFM vs JNA monotonicity assertions) and wrap it
in the same platform gating used elsewhere in the test so it only runs on
platforms where the split totals are expected to match the combined total.
🪄 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: a8621684-9780-4548-bc44-304858675c37
📒 Files selected for processing (12)
CHANGELOG.mdoshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.javaoshi-common/src/main/java/oshi/software/os/OSProcess.javaoshi-core/src/main/java/oshi/driver/mac/MacContextSwitchDriver.javaoshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.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). (2)
- GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
- GitHub Check: Codacy Static Code Analysis
🧰 Additional context used
🧠 Learnings (2)
📚 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/software/os/OSProcess.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).
Applied to files:
oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.java
🔇 Additional comments (2)
oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java (1)
447-451: Voluntary/involuntary context-switch values appear swapped (still present).At Line 447 and Line 448,
NVCSWandNIVCSWare parsed into opposite semantic variables, and Lines 449-450 assign those swapped values to the exposed fields.In FreeBSD/OpenBSD ps(1), what do the fields `nvcsw` and `nivcsw` represent (voluntary vs involuntary context switches)?oshi-core/src/main/java/oshi/driver/mac/MacContextSwitchDriver.java (1)
33-35: Return a defensive copy of cached context-switch arrays (still applicable).Line 34 returns the mutable
long[]from the memoized cache directly, so caller mutation can corrupt shared cached values.
4601743 to
d43f3af
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java (1)
24-52: ⚡ Quick winEach getter performs its own
getrusagesyscall.For the current process,
getVoluntaryContextSwitches(),getInvoluntaryContextSwitches(), andgetContextSwitches()each make independentgetrusagecalls (the latter triggering two more via the split getters). A typical caller asking for all three counters incurs four syscalls and fourRusagestruct allocations on every invocation, with no snapshot consistency between them.Consider fetching
Rusageonce perupdateAttributes()(or memoizing it) and exposing both counters from the single snapshot, similar to how the macOS path now stores values in fields.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java` around lines 24 - 52, Current implementation calls LinuxLibc.INSTANCE.getrusage separately in getVoluntaryContextSwitches(), getInvoluntaryContextSwitches(), and indirectly again in getContextSwitches(), causing multiple syscalls and allocations and inconsistent snapshots; change this by taking a single Rusage snapshot once per update cycle (e.g., add fields like cachedRuNvcsw and cachedRuNivcsw populated from a single LinuxLibc.Rusage read inside updateAttributes() or a lazily memoized method) and have getVoluntaryContextSwitches(), getInvoluntaryContextSwitches(), and getContextSwitches() return values from those cached fields (with fallback to the superclass when not the current process).oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java (1)
487-492: 💤 Low valueUse the imported simple name
SystemB.
oshi.jna.platform.mac.SystemBis already imported on line 46; the fully qualified references here add noise without clarification.♻️ Optional cleanup
- oshi.jna.platform.mac.SystemB.Rusage rusage = new oshi.jna.platform.mac.SystemB.Rusage(); - if (0 == oshi.jna.platform.mac.SystemB.INSTANCE.getrusage(oshi.jna.platform.mac.SystemB.RUSAGE_SELF, - rusage)) { + SystemB.Rusage rusage = new SystemB.Rusage(); + if (0 == SystemB.INSTANCE.getrusage(SystemB.RUSAGE_SELF, rusage)) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java` around lines 487 - 492, The code in MacOSProcessJNA uses the fully qualified oshi.jna.platform.mac.SystemB in the Rusage instantiation and getrusage call; replace those with the imported simple name SystemB (e.g., create new SystemB.Rusage() and call SystemB.INSTANCE.getrusage(...)) so the Rusage type and getrusage invocation use the imported SystemB, keeping the assignments to voluntaryContextSwitches, involuntaryContextSwitches and contextSwitches unchanged.
🤖 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/software/os/OSProcess.java`:
- Around line 419-433: The default getContextSwitches() currently returns a
hard-coded 0L which violates the Javadoc contract; change its implementation to
return the sum of getVoluntaryContextSwitches() and
getInvoluntaryContextSwitches() so classes that only override the new split
getters still get a correct total (i.e., implement getContextSwitches() to
return getVoluntaryContextSwitches() + getInvoluntaryContextSwitches()).
In `@oshi-core/src/main/java/oshi/driver/mac/MacContextSwitchDriver.java`:
- Around line 38-53: The current queryContextSwitches method parses nvcsw/nivcsw
from ExecutingCommand.runNative("ps -ax -o pid=,nvcsw=,nivcsw=") but macOS often
returns zeros/empty values, producing misleading [0,0] entries; modify
queryContextSwitches to detect and handle this: when parsing each line from
ExecutingCommand.runNative skip adding entries where both nvcsw and nivcsw are
zero/absent, and after parsing if the resulting map is empty or all values are
zero either return an empty map (or signal unavailability) rather than
populating PID entries with [0,0]; keep changes localized to
queryContextSwitches and preserve use of ParseUtil.parseLongOrDefault for safe
parsing.
In `@oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java`:
- Around line 485-501: When getrusage fails in MacOSProcessJNA (inside the
branch where getProcessID() == this.os.getProcessId()), ensure the split
counters are set so the invariant contextSwitches == voluntaryContextSwitches +
involuntaryContextSwitches holds; specifically, in the failure path that
currently assigns this.contextSwitches = taskAllInfo.ptinfo.pti_csw, also reset
this.voluntaryContextSwitches and this.involuntaryContextSwitches to 0 (or
another documented fallback) so they aren’t left stale, or alternatively compute
contextSwitches from the split counters if you can obtain them — update the
failure branch around getrusage (and references to taskAllInfo.ptinfo.pti_csw
and MacContextSwitchDriver.getContextSwitches) to set both split fields
consistently whenever contextSwitches is assigned.
In `@oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java`:
- Around line 112-129: Change the runtime check from inspecting sampled values
to detecting capability: instead of using "if
(probe.getVoluntaryContextSwitches() > 0 ||
probe.getInvoluntaryContextSwitches() > 0)" decide split-vs-total based on
whether the split getters are implemented (they typically return a sentinel like
-1 when unsupported). Concretely, in ProcessMetrics where processSupplier/probe
is used, register the voluntary and involuntary FunctionCounters whenever the
split getters are implemented (i.e., at least one of
probe.getVoluntaryContextSwitches() or probe.getInvoluntaryContextSwitches() is
>= 0); only fall back to registering the total function counter (using
probe.getContextSwitches()) when both split getters indicate “unsupported”
(e.g., both < 0). Keep existing tags and descriptions and leave
bindTo()/registry registration logic unchanged.
---
Nitpick comments:
In `@oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java`:
- Around line 24-52: Current implementation calls LinuxLibc.INSTANCE.getrusage
separately in getVoluntaryContextSwitches(), getInvoluntaryContextSwitches(),
and indirectly again in getContextSwitches(), causing multiple syscalls and
allocations and inconsistent snapshots; change this by taking a single Rusage
snapshot once per update cycle (e.g., add fields like cachedRuNvcsw and
cachedRuNivcsw populated from a single LinuxLibc.Rusage read inside
updateAttributes() or a lazily memoized method) and have
getVoluntaryContextSwitches(), getInvoluntaryContextSwitches(), and
getContextSwitches() return values from those cached fields (with fallback to
the superclass when not the current process).
In `@oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java`:
- Around line 487-492: The code in MacOSProcessJNA uses the fully qualified
oshi.jna.platform.mac.SystemB in the Rusage instantiation and getrusage call;
replace those with the imported simple name SystemB (e.g., create new
SystemB.Rusage() and call SystemB.INSTANCE.getrusage(...)) so the Rusage type
and getrusage invocation use the imported SystemB, keeping the assignments to
voluntaryContextSwitches, involuntaryContextSwitches and contextSwitches
unchanged.
🪄 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: 998cc3a0-cd4b-46c6-8bd9-2776c041144e
📒 Files selected for processing (15)
CHANGELOG.mdoshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.javaoshi-common/src/main/java/oshi/software/os/OSProcess.javaoshi-core/src/main/java/oshi/driver/mac/MacContextSwitchDriver.javaoshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.javaoshi-core/src/main/java/oshi/jna/platform/mac/SystemB.javaoshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-metrics/README.mdoshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java
✅ Files skipped from review due to trivial changes (1)
- CHANGELOG.md
📜 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). (9)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
- GitHub Check: Test JDK 21, macos-latest
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: JMH Benchmarks, windows-latest
- GitHub Check: Analyze (java)
- GitHub Check: JMH Benchmarks, ubuntu-latest
- GitHub Check: JMH Benchmarks, macos-latest
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).
Applied to files:
oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.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/software/os/OSProcess.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
🔇 Additional comments (4)
oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java (1)
447-451: Voluntary/involuntary mapping is now correct.The previous swap concern is resolved:
NVCSWis correctly mapped tovoluntaryContextSwitchesandNIVCSWtoinvoluntaryContextSwitches, matching FreeBSDps(1)semantics.oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.java (1)
465-469: Voluntary/involuntary mapping looks correct.
NVCSW→voluntaryContextSwitchesandNIVCSW→involuntaryContextSwitchesmatches OpenBSDps(1)semantics, andcontextSwitchesis consistently the sum.oshi-core/src/main/java/oshi/driver/mac/MacContextSwitchDriver.java (1)
33-36: Defensive copy added — looks good.The previous concern about returning the cached mutable array is addressed via
Arrays.copyOf.oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)
394-400: ⚡ Quick winAssertion premise depends on FFM and JNA using equivalent sources.
The "FFM ≥ JNA" assumption holds only if both implementations sample the same underlying counter. Since the JNA path on Linux now switches to
getrusagefor the current process viaLinuxOSProcessJNA, confirm that the FFM implementation reads the equivalent counter — otherwise these assertions can fail spuriously when one side uses/proc/[pid]/statusand the other usesgetrusage.
d43f3af to
9694389
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java (2)
19-19: 💤 Low valueStale class Javadoc — also document
getrusage.
LinuxOSProcessJNA's class doc was updated in this PR to mention bothgetrlimitandgetrusage, but this class still says onlygetrlimit.📝 Proposed doc tweak
/** - * FFM-based Linux OS process. Implements {`@code` getrlimit} via FFM. + * FFM-based Linux OS process. Implements {`@code` getrlimit} and {`@code` getrusage} via FFM. */🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java` at line 19, Update the stale class Javadoc on LinuxOSProcessFFM to match LinuxOSProcessJNA by documenting that this FFM-based class implements both getrlimit and getrusage via FFM; specifically mention the getrusage method alongside getrlimit in the top-of-class comment for LinuxOSProcessFFM so the documentation accurately reflects implemented functionality.
58-86: 💤 Low valueSame dual-getrusage pattern as the JNA class — consider populating once per refresh.
Each split getter allocates an
Arena, callsgetrusage(RUSAGE_SELF), and reads one field. The defaultgetContextSwitches()triggers two such syscalls, and the two values are not from the same snapshot. A singleupdateAttributes()override that callsgetrusageonce and writes both fields would be more efficient and atomic, mirroring the macOS FFM approach in this PR. (Same suggestion applies toLinuxOSProcessJNA; happy to consolidate in one place if you prefer.)Additionally, lines 64 and 79 use the fully-qualified
java.lang.foreign.ValueLayout.JAVA_LONG. Other FFM classes (e.g.MacOSProcessFFM) useimport static java.lang.foreign.ValueLayout.JAVA_LONG;— adopting the same here would be a small readability win.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java` around lines 58 - 86, The two getters getVoluntaryContextSwitches and getInvoluntaryContextSwitches each call getrusage separately causing two syscalls and non-atomic snapshots; refactor LinuxOSProcessFFM to override updateAttributes() to allocate one Arena, call LinuxLibcFunctions.getrusage(RUSAGE_SELF) once, read both JAVA_LONG fields at LinuxLibcFunctions.RUSAGE_NVCSW_OFFSET and RUSAGE_NIVCSW_OFFSET and store them for the existing getters to return; also replace fully-qualified java.lang.foreign.ValueLayout.JAVA_LONG references with a static import (import static java.lang.foreign.ValueLayout.JAVA_LONG;) to match other FFM classes and improve readability.oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java (1)
24-44: 💤 Low valueTwo getrusage syscalls per
getContextSwitches()and per-call non-atomicity.Each split getter allocates a fresh
Rusageand invokesgetrusage(RUSAGE_SELF). The defaultgetContextSwitches()inOSProcesssums them, so a total query results in two syscalls rather than one, and the voluntary/involuntary values come from different snapshots (sovoluntary + involuntary != getContextSwitches()strictly speaking, even under steady state).Consider populating both fields once via a single
getrusagecall in anupdateAttributes()override (mirroring theMacOSProcessFFMpattern in this PR) so the parent's/proc/statusvalues are simply overwritten withgetrusagedata for the current process.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java` around lines 24 - 44, Replace the dual per-getter getrusage calls with a single snapshot in updateAttributes: in LinuxOSProcessJNA.override updateAttributes(...) call LinuxLibc.INSTANCE.getrusage(LinuxLibc.RUSAGE_SELF, rusage) once when getProcessID() == getOs().getProcessId(), read rusage.ru_nvcsw and ru_nivcsw and populate the process' stored context-switch values (use the existing setters or the internal fields that back getVoluntaryContextSwitches/getInvoluntaryContextSwitches) so getVoluntaryContextSwitches() and getInvoluntaryContextSwitches() simply return those stored values and avoid extra syscalls and non-atomic mismatched snapshots.
🤖 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/software/os/OSProcess.java`:
- Around line 436-463: The getters getVoluntaryContextSwitches() and
getInvoluntaryContextSwitches() currently return 0 as the “unsupported” value
which conflicts with a real 0 result; add an explicit capability method (e.g.,
supportsContextSwitchSplit() defaulting to false) to indicate whether the split
is available, and update the javadoc of getVoluntaryContextSwitches() and
getInvoluntaryContextSwitches() to state they return the switch counts only when
supportsContextSwitchSplit() is true (otherwise callers must treat the values as
undefined); reference the new supportsContextSwitchSplit() method alongside
getVoluntaryContextSwitches() and getInvoluntaryContextSwitches() so callers can
unambiguously detect support.
In `@oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java`:
- Around line 33-34: The Javadoc currently asserts that process.context_switches
will be by type (voluntary, involuntary) but bindTo() can register a fallback
series "process.context_switch.type=total" or omit the meter; update the Javadoc
for process.context_switches to mention that implementations may emit either
per-type series (voluntary/involuntary) or a total/no-data fallback labeled
"process.context_switch.type=total" (or omit the metric) so callers know
bindTo() can produce a total aggregate instead of distinct types.
---
Nitpick comments:
In `@oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java`:
- Line 19: Update the stale class Javadoc on LinuxOSProcessFFM to match
LinuxOSProcessJNA by documenting that this FFM-based class implements both
getrlimit and getrusage via FFM; specifically mention the getrusage method
alongside getrlimit in the top-of-class comment for LinuxOSProcessFFM so the
documentation accurately reflects implemented functionality.
- Around line 58-86: The two getters getVoluntaryContextSwitches and
getInvoluntaryContextSwitches each call getrusage separately causing two
syscalls and non-atomic snapshots; refactor LinuxOSProcessFFM to override
updateAttributes() to allocate one Arena, call
LinuxLibcFunctions.getrusage(RUSAGE_SELF) once, read both JAVA_LONG fields at
LinuxLibcFunctions.RUSAGE_NVCSW_OFFSET and RUSAGE_NIVCSW_OFFSET and store them
for the existing getters to return; also replace fully-qualified
java.lang.foreign.ValueLayout.JAVA_LONG references with a static import (import
static java.lang.foreign.ValueLayout.JAVA_LONG;) to match other FFM classes and
improve readability.
In `@oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java`:
- Around line 24-44: Replace the dual per-getter getrusage calls with a single
snapshot in updateAttributes: in LinuxOSProcessJNA.override
updateAttributes(...) call LinuxLibc.INSTANCE.getrusage(LinuxLibc.RUSAGE_SELF,
rusage) once when getProcessID() == getOs().getProcessId(), read rusage.ru_nvcsw
and ru_nivcsw and populate the process' stored context-switch values (use the
existing setters or the internal fields that back
getVoluntaryContextSwitches/getInvoluntaryContextSwitches) so
getVoluntaryContextSwitches() and getInvoluntaryContextSwitches() simply return
those stored values and avoid extra syscalls and non-atomic mismatched
snapshots.
🪄 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: 464e95ee-d573-4132-9bb3-5f88c48b0c51
📒 Files selected for processing (18)
CHANGELOG.mdoshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.javaoshi-common/src/main/java/oshi/software/os/OSProcess.javaoshi-core-ffm/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.javaoshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.javaoshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.javaoshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.javaoshi-core/src/main/java/oshi/jna/platform/mac/SystemB.javaoshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-metrics/README.mdoshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java
✅ Files skipped from review due to trivial changes (1)
- CHANGELOG.md
📜 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). (6)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: JMH Benchmarks, macos-latest
- GitHub Check: JMH Benchmarks, windows-latest
- GitHub Check: Analyze (java)
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (2)
📚 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/software/os/OSProcess.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).
Applied to files:
oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java
🔇 Additional comments (10)
oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java (1)
113-132: This still fixes meter shape from a single startup sample.A split-capable JVM can legitimately be
0/0/0whenbindTo()runs, so the registry ends up with noprocess.context_switchesseries even though the platform supports them. This still needs an explicit capability signal rather than value-based probing.oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java (1)
104-105: LGTM!Field declarations, getters, and parsing of
voluntary_ctxt_switches/nonvoluntary_ctxt_switchesfrom/proc/<pid>/statusare correctly mapped to the new split counters. Relying on the interface's defaultgetContextSwitches()(sum of the two) keeps the contract intact for non-current processes.Also applies to: 279-286, 438-441
oshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.java (1)
100-115: LGTM!Layout math checks out for macOS LP64: 2×
struct timeval(16 B padded each) + 14 longs × 8 B = 144 B;ru_nvcswat 128 (32 + 12×8) andru_nivcswat 136 (32 + 13×8). The downcall handle and wrapper follow the established style for this file.oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java (1)
566-580: LGTM — clean integration withupdateAttributes.Single
getrusage(RUSAGE_SELF)per refresh keeps voluntary/involuntary atomically consistent and overwritescontextSwitcheswith the sum sogetContextSwitches()matches the split for the current process. The innertry/catch (Throwable)correctly contains the failure so the outer block does not flip state toINVALID. Non-current processes fall through topti_cswonly, matching the documented macOS contract (split unavailable for other processes).oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.java (1)
109-110: LGTM!NVCSW →
voluntaryContextSwitchesand NIVCSW →involuntaryContextSwitchesmapping matches OpenBSDps(1)semantics, and the new getters cleanly replace the prior aggregate.Also applies to: 387-394, 459-462
oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java (1)
96-97: LGTM — prior swap fix verified.
PsKeywords.NVCSW→voluntaryContextSwitchesandPsKeywords.NIVCSW→involuntaryContextSwitchesis now correct and consistent with the OpenBSD implementation in this PR.Also applies to: 371-378, 441-444
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)
394-400: LGTM!The
ffm >= jnaassertions are sound: counters fromgetrusageare monotonic non-decreasing, FFM is invoked second, and platforms where the split is unavailable (Windows/AIX) trivially satisfy0 >= 0.oshi-core-ffm/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.java (3)
133-140: Rusage layout constants are well-defined.These constants are clear and consistent for the LP64 Linux
struct rusagemapping used by the FFM path.
229-229: Nativegetrusagehandle binding looks correct.The method-handle declaration and downcall descriptor align with the libc signature and match the existing binding pattern in this class.
Also applies to: 258-259
572-582: Publicgetrusagewrapper is clean and consistent.The wrapper keeps invocation semantics uniform with other libc calls and provides a clear contract for callers.
| /** | ||
| * The number of voluntary context switches the process has made. A voluntary context switch occurs when a process | ||
| * gives up the CPU before its time slice expires (e.g., waiting for I/O). | ||
| * <p> | ||
| * For the current process, {@code getrusage(RUSAGE_SELF)} is used on supported POSIX platforms, which aggregates | ||
| * across all threads. For other processes, platform-specific sources are used ({@code /proc/[pid]/status} on Linux, | ||
| * {@code ps} on FreeBSD/OpenBSD, {@code /proc/[pid]/usage} on Solaris). On macOS, the split is only available for | ||
| * the current process; for other processes this returns 0. | ||
| * | ||
| * @return voluntary context switches if available, 0 otherwise. | ||
| */ | ||
| default long getVoluntaryContextSwitches() { | ||
| return 0L; | ||
| } | ||
|
|
||
| /** | ||
| * The number of involuntary context switches the process has made. An involuntary context switch occurs when the | ||
| * scheduler preempts the process (e.g., time slice expired). | ||
| * <p> | ||
| * For the current process, {@code getrusage(RUSAGE_SELF)} is used on supported POSIX platforms, which aggregates | ||
| * across all threads. For other processes, platform-specific sources are used ({@code /proc/[pid]/status} on Linux, | ||
| * {@code ps} on FreeBSD/OpenBSD, {@code /proc/[pid]/usage} on Solaris). On macOS, the split is only available for | ||
| * the current process; for other processes this returns 0. | ||
| * | ||
| * @return involuntary context switches if available, 0 otherwise. | ||
| */ | ||
| default long getInvoluntaryContextSwitches() { | ||
| return 0L; |
There was a problem hiding this comment.
0 is ambiguous as the “unsupported” value for the new split getters.
A supported process can also legitimately report 0 voluntary/involuntary switches, so callers cannot distinguish “split unavailable” from “no switches yet.” That ambiguity is already forcing value-based heuristics in ProcessMetrics. Please use a distinct sentinel or expose an explicit capability method instead.
🤖 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/main/java/oshi/software/os/OSProcess.java` around lines 436 -
463, The getters getVoluntaryContextSwitches() and
getInvoluntaryContextSwitches() currently return 0 as the “unsupported” value
which conflicts with a real 0 result; add an explicit capability method (e.g.,
supportsContextSwitchSplit() defaulting to false) to indicate whether the split
is available, and update the javadoc of getVoluntaryContextSwitches() and
getInvoluntaryContextSwitches() to state they return the switch counts only when
supportsContextSwitchSplit() is true (otherwise callers must treat the values as
undefined); reference the new supportsContextSwitchSplit() method alongside
getVoluntaryContextSwitches() and getInvoluntaryContextSwitches() so callers can
unambiguously detect support.
9694389 to
e4ade3f
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java (1)
20-54:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winSame critical field-initializer-order bug as
LinuxOSProcessFFM.The
private long cachedVoluntaryContextSwitches = -1;/cachedInvoluntaryContextSwitches = -1;initializers run after the super constructor returns and overwrite the values thatsuper(...)populated via the virtually-dispatchedupdateAttributes()override. After construction the caches are-1, so the JNAgetrusagefix is silently bypassed andgetVoluntaryContextSwitches()/getInvoluntaryContextSwitches()return the misleading/proc/<pid>/statusvalues issue#2904was meant to fix. Apply the same fix proposed forLinuxOSProcessFFM(replace the-1sentinel with aboolean rusagePopulatedflag, and add a correspondinggetContextSwitches()override that returnscachedVoluntary + cachedInvoluntarywhen populated to keep the prior consistency fix intact).🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java` around lines 20 - 54, The cached field initializers currently overwrite values set during the super(...) construction via the virtual updateAttributes() call; replace the long sentinels with a boolean flag (e.g., rusagePopulated) initialized false, set rusagePopulated = true inside LinuxOSProcessJNA.updateAttributes() when LinuxLibc.INSTANCE.getrusage(...) succeeds and the cachedVoluntaryContextSwitches/cachedInvoluntaryContextSwitches are assigned, and update the getters getVoluntaryContextSwitches()/getInvoluntaryContextSwitches() to return the cached values only when rusagePopulated is true (otherwise delegate to super); also add an override of getContextSwitches() that returns cachedVoluntaryContextSwitches + cachedInvoluntaryContextSwitches when rusagePopulated is true to preserve the prior consistency fix.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java`:
- Around line 27-67: The field initializers setting
cachedVoluntaryContextSwitches and cachedInvoluntaryContextSwitches to -1
overwrite values written during the superclass constructor's call to
updateAttributes(); change the sentinel approach to a boolean flag instead: add
a private boolean rusagePopulated (no explicit initializer), set rusagePopulated
= true inside LinuxOSProcessFFM.updateAttributes() only when
LinuxLibcFunctions.getrusage succeeds, and modify
getVoluntaryContextSwitches()/getInvoluntaryContextSwitches() to return the
cached longs only when rusagePopulated is true (otherwise delegate to super);
apply the same change to the analogous fields and methods in LinuxOSProcessJNA.
In `@oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java`:
- Around line 565-580: In MacOSProcessFFM inside the getrusage block that
updates contextSwitches, ensure the JNA failure-path semantics are mirrored: if
getrusage returns non-zero or an exception is thrown, explicitly set
voluntaryContextSwitches = 0L and involuntaryContextSwitches = 0L so that
contextSwitches == voluntary + involuntary still holds, and add a debug log in
the catch (Throwable t) similar to LinuxOSProcessFFM (include the exception) to
make FFM failures diagnosable; update the code around the MemorySegment/arena
allocation and the MacSystemFunctions.getrusage call to perform this reset and
logging when failure occurs.
---
Duplicate comments:
In `@oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java`:
- Around line 20-54: The cached field initializers currently overwrite values
set during the super(...) construction via the virtual updateAttributes() call;
replace the long sentinels with a boolean flag (e.g., rusagePopulated)
initialized false, set rusagePopulated = true inside
LinuxOSProcessJNA.updateAttributes() when LinuxLibc.INSTANCE.getrusage(...)
succeeds and the cachedVoluntaryContextSwitches/cachedInvoluntaryContextSwitches
are assigned, and update the getters
getVoluntaryContextSwitches()/getInvoluntaryContextSwitches() to return the
cached values only when rusagePopulated is true (otherwise delegate to super);
also add an override of getContextSwitches() that returns
cachedVoluntaryContextSwitches + cachedInvoluntaryContextSwitches when
rusagePopulated is true to preserve the prior consistency fix.
🪄 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: 56b6a6bf-f563-4d85-a3db-7e472ed9257b
📒 Files selected for processing (18)
CHANGELOG.mdoshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.javaoshi-common/src/main/java/oshi/software/os/OSProcess.javaoshi-core-ffm/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.javaoshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.javaoshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.javaoshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.javaoshi-core/src/main/java/oshi/jna/platform/mac/SystemB.javaoshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-metrics/README.mdoshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java
🚧 Files skipped from review as they are similar to previous changes (1)
- oshi-metrics/README.md
📜 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). (9)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: JMH Benchmarks, ubuntu-latest
- GitHub Check: Test JDK 21, macos-latest
- GitHub Check: JMH Benchmarks, windows-latest
- GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: JMH Benchmarks, macos-latest
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (2)
📚 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/software/os/OSProcess.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).
Applied to files:
oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java
🔇 Additional comments (7)
oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java (1)
112-132: Same issue remains: meter shape still depends on the first sampled values.A split-capable process can still report
0/0whenbindTo()runs, so this branch may permanently registerprocess.context_switch.type=total— or nothing — even though split meters are supported.oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.java (1)
90-91: LGTM!The Solaris implementation correctly maps
pr_vctx→ voluntary andpr_ictx→ involuntary context switches, and the new getters cleanly expose them. The defaultgetContextSwitches()from the OSProcess interface will return their sum.Also applies to: 251-258, 395-396
oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java (1)
484-501: LGTM!The two prior review comments (deriving total from split, and resetting split on
getrusagefailure) are properly addressed. The invariants now hold consistently for the current-process path, and the non-current-process path leaves the split at the default 0, matching the documented macOS contract.oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java (1)
104-105: LGTM!The mapping
voluntary_ctxt_switches → voluntaryContextSwitchesandnonvoluntary_ctxt_switches → involuntaryContextSwitchesis correct, and these now correctly populate the per-type counters from/proc/<pid>/status. The known limitation around per-thread aggregation (issue#2904) is addressed in the subclass overrides viagetrusage(RUSAGE_SELF)for the current process.Also applies to: 279-286, 438-441
oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.java (1)
109-110: LGTM!
PsKeywords.NVCSW→voluntaryContextSwitchesandPsKeywords.NIVCSW→involuntaryContextSwitchesmatches OpenBSDps(1)semantics, mirroring the FreeBSD fix from a prior review. The new getters and field declarations are correct.Also applies to: 387-394, 459-462
oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java (1)
96-97: LGTM!The previously-flagged voluntary/involuntary swap is now correctly oriented:
NVCSW → voluntaryContextSwitches,NIVCSW → involuntaryContextSwitches, matching FreeBSDps(1)semantics. The new fields and getters look good.Also applies to: 371-378, 441-444
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java (1)
394-399: Nice coverage extension for the new split context-switch API.These assertions are a good fit for the PR goal and validate JNA/FFM parity on total + voluntary + involuntary process context switches in one place.
e4ade3f to
9f746d9
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
oshi-common/src/main/java/oshi/software/os/OSProcess.java (1)
436-463:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftUse an explicit split-support signal instead of overloading
0.
0is a valid context-switch count, so these defaults make “unsupported” indistinguishable from “supported but idle.” That already leaks downstream intoProcessMetrics.bindTo(), where the registry shape depends on the first sampled values and a split-capable process can register noprocess.context_switchesseries at all if it happens to be at 0/0 during startup. Please expose support explicitly (for example, a capability method) or reserve a distinct sentinel for unsupported platforms.🤖 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/main/java/oshi/software/os/OSProcess.java` around lines 436 - 463, The defaults for getVoluntaryContextSwitches() and getInvoluntaryContextSwitches() use 0 which conflates “unsupported” with a real zero count; add an explicit capability signal (for example a new default boolean method supportsContextSwitchCounts() or supportsContextSwitchSplit()) and have implementations override it on platforms that can provide the split, or alternatively use a distinct sentinel value (e.g., -1) for “unsupported”; update ProcessMetrics.bindTo() to check that capability (or sentinel) before registering any process.context_switches series so registry shape no longer depends on first-sampled numeric values.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java`:
- Around line 36-53: The rusagePopulated flag is only set to true on success,
leaving stale cachedVoluntaryContextSwitches/cachedInvoluntaryContextSwitches if
getrusage fails; modify updateAttributes() so that before invoking
LinuxLibcFunctions.getrusage(...) you clear/reset rusagePopulated (set to false)
so the cache is considered invalid until a successful native refresh, and only
set rusagePopulated = true inside the successful branch where getrusage returns
0; locate updateAttributes(), the try block that allocates rusage via
LinuxLibcFunctions and adjust the flag handling accordingly.
In `@oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java`:
- Around line 29-39: updateAttributes currently leaves rusagePopulated true if a
prior getrusage succeeded but a subsequent refresh fails, causing stale
cachedVoluntaryContextSwitches/cachedInvoluntaryContextSwitches to be returned;
in updateAttributes (method updateAttributes) reset rusagePopulated to false
before attempting LinuxLibc.INSTANCE.getrusage (or explicitly set
rusagePopulated = false in the failure branch) and only set it true when
getrusage returns 0 and you update
cachedVoluntaryContextSwitches/cachedInvoluntaryContextSwitches, ensuring stale
split counters are not used after a failed refresh.
---
Duplicate comments:
In `@oshi-common/src/main/java/oshi/software/os/OSProcess.java`:
- Around line 436-463: The defaults for getVoluntaryContextSwitches() and
getInvoluntaryContextSwitches() use 0 which conflates “unsupported” with a real
zero count; add an explicit capability signal (for example a new default boolean
method supportsContextSwitchCounts() or supportsContextSwitchSplit()) and have
implementations override it on platforms that can provide the split, or
alternatively use a distinct sentinel value (e.g., -1) for “unsupported”; update
ProcessMetrics.bindTo() to check that capability (or sentinel) before
registering any process.context_switches series so registry shape no longer
depends on first-sampled numeric values.
🪄 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: c7883eba-0d18-461f-b9c3-fe4d44a5af7e
📒 Files selected for processing (18)
CHANGELOG.mdoshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.javaoshi-common/src/main/java/oshi/software/os/OSProcess.javaoshi-core-ffm/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.javaoshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.javaoshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.javaoshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.javaoshi-core/src/main/java/oshi/jna/platform/mac/SystemB.javaoshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-metrics/README.mdoshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java
🚧 Files skipped from review as they are similar to previous changes (1)
- oshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.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). (9)
- GitHub Check: Codacy Static Code Analysis
- GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
- GitHub Check: Test JDK 21, macos-latest
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: JMH Benchmarks, ubuntu-latest
- GitHub Check: JMH Benchmarks, windows-latest
- GitHub Check: Analyze (java)
- GitHub Check: JMH Benchmarks, macos-latest
🧰 Additional context used
🧠 Learnings (2)
📚 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/software/common/os/linux/LinuxOSProcess.javaoshi-common/src/main/java/oshi/software/os/OSProcess.java
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).
Applied to files:
oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
🔇 Additional comments (2)
oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.java (2)
109-110: Split context-switch fields/getters look correctly wired.This cleanly exposes per-type counters and keeps OpenBSD aligned with the new
OSProcesssplit-counter design.Also applies to: 387-394
459-462:NVCSW/NIVCSWmapping is correct.The parsed values are assigned to the matching voluntary/involuntary fields without accidental inversion.
9f746d9 to
5f025ee
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java (1)
115-133:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftDon't make meter registration depend on the first sampled value.
Line 119 still uses
total > 0as the proxy for split support. A split-capable process can legitimately report0voluntary and0involuntary switches whenbindTo()runs, and this branch then registers noprocess.context_switchesmeters for the lifetime of the registry. SinceOSProcesscurrently uses0for both “unsupported” and “zero so far,” this needs an explicit capability/sentinel instead of a value-based probe.🤖 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-metrics/src/main/java/oshi/metrics/ProcessMetrics.java` around lines 115 - 133, The current registration logic uses runtime values (vol, invol, total) to detect split support and skips registering meters when values are zero; replace this value-based check with an explicit capability/sentinel on OSProcess (e.g., a new isContextSwitchSplitSupported() or a dedicated sentinel return like -1) and use that to decide which meters to register: if the OSProcess capability indicates split support, always register the two FunctionCounter builders that call getVoluntaryContextSwitches() and getInvoluntaryContextSwitches(), otherwise register the single FunctionCounter that calls getContextSwitches(); ensure you add or use a clear OSProcess symbol (e.g., isContextSwitchSplitSupported or documented sentinel semantics for getVoluntaryContextSwitches/getInvoluntaryContextSwitches) rather than relying on total > 0 so meters are not omitted when the counters are legitimately zero.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java`:
- Around line 439-444: In FreeBsdOSProcess swap the mistaken assignments so
minorFaults is set from PsKeywords.MINFLT and majorFaults from
PsKeywords.MAJFLT; locate the lines assigning this.minorFaults and
this.majorFaults in the FreeBsdOSProcess class and replace the current
ParseUtil.parseLongOrDefault(...) calls so minorFaults uses PsKeywords.MINFLT
and majorFaults uses PsKeywords.MAJFLT (leave the context-switch assignments
untouched).
---
Duplicate comments:
In `@oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java`:
- Around line 115-133: The current registration logic uses runtime values (vol,
invol, total) to detect split support and skips registering meters when values
are zero; replace this value-based check with an explicit capability/sentinel on
OSProcess (e.g., a new isContextSwitchSplitSupported() or a dedicated sentinel
return like -1) and use that to decide which meters to register: if the
OSProcess capability indicates split support, always register the two
FunctionCounter builders that call getVoluntaryContextSwitches() and
getInvoluntaryContextSwitches(), otherwise register the single FunctionCounter
that calls getContextSwitches(); ensure you add or use a clear OSProcess symbol
(e.g., isContextSwitchSplitSupported or documented sentinel semantics for
getVoluntaryContextSwitches/getInvoluntaryContextSwitches) rather than relying
on total > 0 so meters are not omitted when the counters are legitimately zero.
🪄 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: f14265dd-b2eb-4f2a-a51e-4f95549d26f6
📒 Files selected for processing (18)
CHANGELOG.mdoshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.javaoshi-common/src/main/java/oshi/software/os/OSProcess.javaoshi-core-ffm/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.javaoshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.javaoshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.javaoshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.javaoshi-core/src/main/java/oshi/jna/platform/mac/SystemB.javaoshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-metrics/README.mdoshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java
✅ Files skipped from review due to trivial changes (1)
- CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (1)
- oshi-common/src/main/java/oshi/software/os/OSProcess.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, macos-latest
- GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: Test JDK 11, macos-latest
- GitHub Check: JMH Benchmarks, ubuntu-latest
- GitHub Check: JMH Benchmarks, macos-latest
- GitHub Check: JMH Benchmarks, windows-latest
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
- GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).
Applied to files:
oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.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/software/common/os/linux/LinuxOSProcess.java
Resolves #2904 Adds getVoluntaryContextSwitches() and getInvoluntaryContextSwitches() to OSProcess interface with defaults returning 0. For the current process, getrusage(RUSAGE_SELF) is preferred on all POSIX platforms as it aggregates across all threads (addressing the core issue that /proc/[pid]/status only shows the main thread). Platform support: - Linux: getrusage for current process (JNA), /proc/[pid]/status fallback - macOS: getrusage for current process, memoized ps batch for others - FreeBSD: ps output (nvcsw/nivcsw) for any process - OpenBSD: ps output for any process - Solaris: /proc/[pid]/usage (pr_vctx/pr_ictx) for any process Also adds: - POSIX getrusage() and Rusage struct to CLibrary - MacContextSwitchDriver with memoized batch ps query - oshi-metrics: emits voluntary/involuntary per OTel spec - JNA vs FFM comparison test assertions
5f025ee to
2dd71f4
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (1)
oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java (1)
119-133:⚠️ Potential issue | 🟠 Major | ⚡ Quick winMetric registration is still startup-sample dependent.
Line 119-133 gates registration on
total > 0, so a split-capable process with an initial0/0/0sample registers noprocess.context_switchesmeter at all, and that shape won’t recover later. This makes emitted series depend on startup timing rather than capability.Suggested direction
- if (vol + invol == total && total > 0) { + if (vol + invol == total) { FunctionCounter.builder(CONTEXT_SWITCHES, processSupplier, s -> s.get().getVoluntaryContextSwitches()) ... - } else if (total > 0) { + } else { FunctionCounter.builder(CONTEXT_SWITCHES, processSupplier, s -> s.get().getContextSwitches()) ... }If all-zero unsupported platforms are a concern, consider exposing an explicit capability/sentinel in
OSProcessand branching on that instead of first-sample values.🤖 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-metrics/src/main/java/oshi/metrics/ProcessMetrics.java` around lines 119 - 133, The current registration logic in ProcessMetrics that checks "if (vol + invol == total && total > 0) { ... } else if (total > 0) { ... }" makes metric presence depend on the first sample; instead register the CONTEXT_SWITCHES meter(s) unconditionally (using processSupplier and registry) and decide which variants to emit based on a real capability flag on the OSProcess (e.g., add an explicit method like OSProcess.hasContextSwitchSupport() or getContextSwitchCapability()) so the code in ProcessMetrics always registers meters (FunctionCounter.builder with CONTEXT_SWITCHES, processSupplier, and registry) but uses the capability/sentinel to choose between emitting separate voluntary/involuntary counters vs a total counter or tagging as unsupported. Ensure you reference CONTEXT_SWITCHES, processSupplier, registry, and the new OSProcess capability method in the change.
🤖 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.
Duplicate comments:
In `@oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java`:
- Around line 119-133: The current registration logic in ProcessMetrics that
checks "if (vol + invol == total && total > 0) { ... } else if (total > 0) { ...
}" makes metric presence depend on the first sample; instead register the
CONTEXT_SWITCHES meter(s) unconditionally (using processSupplier and registry)
and decide which variants to emit based on a real capability flag on the
OSProcess (e.g., add an explicit method like OSProcess.hasContextSwitchSupport()
or getContextSwitchCapability()) so the code in ProcessMetrics always registers
meters (FunctionCounter.builder with CONTEXT_SWITCHES, processSupplier, and
registry) but uses the capability/sentinel to choose between emitting separate
voluntary/involuntary counters vs a total counter or tagging as unsupported.
Ensure you reference CONTEXT_SWITCHES, processSupplier, registry, and the new
OSProcess capability method in the change.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 02581e50-0ac8-43db-9d79-09347abaec10
📒 Files selected for processing (18)
CHANGELOG.mdoshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.javaoshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.javaoshi-common/src/main/java/oshi/software/os/OSProcess.javaoshi-core-ffm/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.javaoshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.javaoshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.javaoshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.javaoshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.javaoshi-core/src/main/java/oshi/jna/platform/mac/SystemB.javaoshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.javaoshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.javaoshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.javaoshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.javaoshi-metrics/README.mdoshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java
✅ Files skipped from review due to trivial changes (3)
- oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
- oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java
- CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (13)
- oshi-metrics/README.md
- oshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.java
- oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
- oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
- oshi-common/src/main/java/oshi/software/os/OSProcess.java
- oshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.java
- oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
- oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.java
- oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.java
- oshi-core-ffm/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.java
- oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
- oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java
- oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.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 11, windows-latest
- GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
- GitHub Check: Test JDK 21, macos-latest
- GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
- GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
- GitHub Check: JMH Benchmarks, windows-latest
- GitHub Check: JMH Benchmarks, macos-latest
- GitHub Check: JMH Benchmarks, ubuntu-latest
- GitHub Check: Analyze (java)
🔇 Additional comments (1)
oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java (1)
566-585: Looks good: failure-path semantics are now consistent and safe.Line 566-585 correctly keeps
contextSwitchesfallback behavior while resetting split counters on failedgetrusage, which avoids stale split values.
Summary
Resolves #2904
Adds
getVoluntaryContextSwitches()andgetInvoluntaryContextSwitches()to theOSProcessinterface. The defaultgetContextSwitches()now returns their sum.Design
getrusage(RUSAGE_SELF)on all POSIX platforms (aggregates across all threads — the core fix for Context switches on Linux may be misleading #2904)/proc,ps, etc.)getContextSwitches(): returnsgetVoluntaryContextSwitches() + getInvoluntaryContextSwitches()— no need to override on platforms with the splitPlatform support
Metrics
ProcessMetricsemits:voluntary+involuntarywhenvol + invol == total(POSIX current process)totalonly when split is unavailable (Windows)Changes
OSProcess.java: Added split methods with defaults;getContextSwitches()returns their sumLinuxOSProcess.java: Stores split values from /procLinuxOSProcessJNA.java: Overrides split with getrusage for current processLinuxOSProcessFFM.java: Same via FFMLinuxLibcFunctions.java: Added getrusage downcall + RUSAGE constantsMacOSProcessJNA.java: getrusage for current process, pti_csw for othersMacOSProcessFFM.java: Same via FFMMacSystemFunctions.java: Added getrusage downcall + RUSAGE constantsLinuxLibc.java/SystemB.java: Platform-specific Rusage structsCLibrary.java: RUSAGE_SELF constantFreeBsdOSProcess.java/OpenBsdOSProcess.java/SolarisOSProcess.java: Expose split valuesProcessMetrics.java: Emits split or total based on availabilityNativeComparisonTest.java: JNA vs FFM assertionsCHANGELOG.md: EntrySummary by CodeRabbit
New Features
Documentation
Tests
Changelog