Skip to content

Add voluntary/involuntary context switch methods to OSProcess - #3232

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:feature/context-switches-split
May 6, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:feature/context-switches-split

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 6, 2026 •

Copy link
Copy Markdown
Member

Summary

Resolves #2904

Adds getVoluntaryContextSwitches() and getInvoluntaryContextSwitches() to the OSProcess interface. The default getContextSwitches() now returns their sum.

Design

  • Current process: getrusage(RUSAGE_SELF) on all POSIX platforms (aggregates across all threads — the core fix for Context switches on Linux may be misleading #2904)
  • Other processes: platform-specific fallback (/proc, ps, etc.)
  • Default getContextSwitches(): returns getVoluntaryContextSwitches() + getInvoluntaryContextSwitches() — no need to override on platforms with the split

Platform support

Platform Split available Scope Source
Linux (JNA + FFM) ✅ Any process (current via getrusage, others via /proc) getrusage / /proc/[pid]/status
macOS (JNA + FFM) ✅ Current process only getrusage(RUSAGE_SELF)
FreeBSD ✅ Any process ps nvcsw/nivcsw
OpenBSD ✅ Any process ps nvcsw/nivcsw
Solaris ✅ Any process /proc/[pid]/usage pr_vctx/pr_ictx
Windows ❌ Total only (from perfmon) Overrides getContextSwitches()
AIX ❌ Returns 0 Default

Metrics

ProcessMetrics emits:

  • voluntary + involuntary when vol + invol == total (POSIX current process)
  • total only when split is unavailable (Windows)
  • Nothing when all are 0 (AIX)

Changes

  • OSProcess.java: Added split methods with defaults; getContextSwitches() returns their sum
  • LinuxOSProcess.java: Stores split values from /proc
  • LinuxOSProcessJNA.java: Overrides split with getrusage for current process
  • LinuxOSProcessFFM.java: Same via FFM
  • LinuxLibcFunctions.java: Added getrusage downcall + RUSAGE constants
  • MacOSProcessJNA.java: getrusage for current process, pti_csw for others
  • MacOSProcessFFM.java: Same via FFM
  • MacSystemFunctions.java: Added getrusage downcall + RUSAGE constants
  • LinuxLibc.java / SystemB.java: Platform-specific Rusage structs
  • CLibrary.java: RUSAGE_SELF constant
  • FreeBsdOSProcess.java / OpenBsdOSProcess.java / SolarisOSProcess.java: Expose split values
  • ProcessMetrics.java: Emits split or total based on availability
  • NativeComparisonTest.java: JNA vs FFM assertions
  • CHANGELOG.md: Entry

Summary by CodeRabbit

  • New Features

    • Process metrics now report separate voluntary and involuntary context-switch counts on POSIX hosts, with total fallback when per-type counts aren’t available.
  • Documentation

    • Metrics docs updated to describe per-type context-switch metrics, getrusage usage for POSIX, platform differences, and fallback behavior.
  • Tests

    • Tests/benchmarks extended to validate parity of the new per-type context-switch metrics across implementations.
  • Changelog

    • Added release note entry describing per-type context-switch reporting.

@coderabbitai

coderabbitai Bot commented May 6, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds 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.

Changes

Context Switch Split & getrusage Integration

Layer / File(s) Summary
API Design
oshi-common/src/main/java/oshi/software/os/OSProcess.java
Adds getVoluntaryContextSwitches() and getInvoluntaryContextSwitches() defaults and changes getContextSwitches() to return their sum.
Linux / proc parsing
oshi-common/src/main/java/oshi/software/common/os/linux/LinuxOSProcess.java
Replaces single contextSwitches field with voluntaryContextSwitches and involuntaryContextSwitches; parses voluntary_ctxt_switches and nonvoluntary_ctxt_switches.
BSD / Solaris parsing
oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java, .../openbsd/OpenBsdOSProcess.java, .../solaris/SolarisOSProcess.java
Replace aggregated counter with separate voluntary/involuntary fields; map NVCSW/NIVCSW or usage.pr_vctx/pr_ictx into new fields and add getters.
macOS JNA types & calls
oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java, oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
Adds Rusage structure and getrusage signature; Mac process class reads getrusage(RUSAGE_SELF) for the host process and stores voluntary/involuntary counts with fallback to pti_csw.
Linux JNA types & calls
oshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.java, oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
Adds Rusage Structure and getrusage signature; Linux JNA process implementation calls getrusage for host PID and caches ru_nvcsw/ru_nivcsw.
FFM native bindings
oshi-core-ffm/src/main/java/oshi/ffm/linux/LinuxLibcFunctions.java, oshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.java
Adds rusage size/offset constants, RUSAGE_SELF, downcall MethodHandle for getrusage, and public getrusage(int, MemorySegment) wrappers.
FFM process implementations
oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java, .../mac/MacOSProcessFFM.java
Call getrusage(RUSAGE_SELF) for host PID, cache NVCSW/NIVCSW, add getters returning cached values or delegating to superclass; set combined contextSwitches from sum when applicable.
CLibrary constant
oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
Adds RUSAGE_SELF constant (0).
Metrics wiring & docs
oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java, oshi-metrics/README.md
Emit two process.context_switches FunctionCounters tagged by `process.context_switch.type=voluntary
Tests / Changelog
oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.java, CHANGELOG.md
Adds assertions in benchmark test comparing JNA vs FFM for total, voluntary, and involuntary context-switches; updates CHANGELOG entry under 7.1.0.

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)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • oshi/oshi#3150: Related — overlaps with NativeComparisonTest additions and JNA vs FFM comparison scaffolding.
  • oshi/oshi#3211: Related — also modifies NativeComparisonTest and cross-checks JNA/FFM process attributes.
  • oshi/oshi#3104: Related — touches macOS native bindings and FFM/JNA macOS process code.

Poem

🐰
I hopped through structs and native calls,
Counting switches down kernel halls.
Voluntary and involuntary—two in view,
Tests compare JNA and FFM too.
A crunchy carrot for changes new 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.74% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding voluntary and involuntary context switch methods to OSProcess interface.
Linked Issues check ✅ Passed The PR fully addresses issue #2904 by implementing getVoluntaryContextSwitches() and getInvoluntaryContextSwitches() on OSProcess, using getrusage for current process aggregation on POSIX platforms.
Out of Scope Changes check ✅ Passed All changes are within scope: OSProcess interface methods, platform-specific process implementations, JNA/FFM bindings for getrusage, ProcessMetrics updates, test additions, and CHANGELOG entry—all directly supporting the split context-switch objective.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@codecov

codecov Bot commented May 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 63.95349% with 31 lines in your changes missing coverage. Please review.
✅ Project coverage is 63.72%. Comparing base (195502c) to head (2dd71f4).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...java/oshi/software/os/linux/LinuxOSProcessFFM.java 63.15% 4 Missing and 3 partials ⚠️
...ain/java/oshi/software/os/mac/MacOSProcessFFM.java 53.33% 6 Missing and 1 partial ⚠️
...ics/src/main/java/oshi/metrics/ProcessMetrics.java 66.66% 4 Missing and 2 partials ⚠️
...java/oshi/software/os/linux/LinuxOSProcessJNA.java 66.66% 2 Missing and 3 partials ⚠️
...ain/java/oshi/software/os/mac/MacOSProcessJNA.java 69.23% 3 Missing and 1 partial ⚠️
.../oshi/software/common/os/linux/LinuxOSProcess.java 50.00% 2 Missing ⚠️
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     
Flag Coverage Δ
linux 30.00% <44.18%> (+0.05%) ⬆️
macos 33.09% <36.04%> (+<0.01%) ⬆️
windows 40.53% <6.97%> (-0.17%) ⬇️

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

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@dbwiddis
dbwiddis force-pushed the feature/context-switches-split branch 2 times, most recently from d647157 to 68da30d Compare May 6, 2026 18:26

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java (1)

486-493: ⚡ Quick win

Use this.os.getProcessId() for the current-process check, matching the pattern in getSoftOpenFileLimit() and getHardOpenFileLimit().

getSoftOpenFileLimit() / getHardOpenFileLimit() at lines 359 and 370 already use getProcessID() == this.os.getProcessId() for the same purpose. Calling oshi.jna.platform.mac.SystemB.INSTANCE.getpid() here introduces an extra native call and requires a fully-qualified type to disambiguate from the already-imported com.sun.jna.platform.mac.SystemB.

Additionally, add a brief comment noting that getrusage(RUSAGE_SELF) aggregates across all threads of the calling process, while pti_csw (which feeds contextSwitches) is the task counter—so voluntary + involuntary is not guaranteed to equal getContextSwitches().

♻️ 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

📥 Commits

Reviewing files that changed from the base of the PR and between ea0b525 and 68da30d.

📒 Files selected for processing (10)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.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/src/main/java/oshi/jna/platform/unix/CLibrary.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.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-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.java
  • oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java
  • oshi-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.java
  • oshi-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 distinct process.context_switch.type tags (voluntary/involuntary) correctly matches the OpenTelemetry semantic convention for process.context_switches.

oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.java (1)

401-403: LGTM — Solaris field mapping is correct.

pr_vctx and pr_ictx from the Solaris prusage_t correspond to voluntary and involuntary context switches respectively, so the assignments and the sum into contextSwitches are 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/getMajorFaults pattern, and the Javadoc correctly documents the platform constraints (Linux for any pid, macOS/POSIX limited to the current process via getrusage(RUSAGE_SELF)). Retaining getContextSwitches() 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]/status exposes voluntary_ctxt_switches and nonvoluntary_ctxt_switches (kernel uses "nonvoluntary" but the semantic is involuntary), so the field assignments and the retained sum into contextSwitches are right.

Note (out of scope but worth tracking for the follow-up referenced in the PR description): per issue #2904, these /proc values count only the main thread. If you later add getrusage(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.

Resource is 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 -> total keeps getContextSwitches() 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.

@dbwiddis
dbwiddis force-pushed the feature/context-switches-split branch 2 times, most recently from aec53b1 to 4601743 Compare May 6, 2026 18:49

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 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 win

Keep 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 hardcodes 0, 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]/status is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 68da30d and aec53b1.

📒 Files selected for processing (11)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.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/src/main/java/oshi/driver/mac/MacContextSwitchDriver.java
  • oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.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-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.java
  • oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.java
  • oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.java
  • oshi-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.java
  • oshi-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/NIVCSW still look swapped here.

NVCSW is the voluntary count and NIVCSW is 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_switches to 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java (1)

486-498: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Recompute contextSwitches from the split counters.

getContextSwitches() still comes from pti_csw, while the new getters come from getrusage() / MacContextSwitchDriver. If those sources differ, the three getters stop describing the same snapshot and getContextSwitches() 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 win

Add 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 than voluntary + 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

📥 Commits

Reviewing files that changed from the base of the PR and between aec53b1 and 4601743.

📒 Files selected for processing (12)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.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/src/main/java/oshi/driver/mac/MacContextSwitchDriver.java
  • oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.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-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.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.java
  • oshi-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, NVCSW and NIVCSW are 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.

@dbwiddis
dbwiddis force-pushed the feature/context-switches-split branch from 4601743 to d43f3af Compare May 6, 2026 19:32

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (2)
oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java (1)

24-52: ⚡ Quick win

Each getter performs its own getrusage syscall.

For the current process, getVoluntaryContextSwitches(), getInvoluntaryContextSwitches(), and getContextSwitches() each make independent getrusage calls (the latter triggering two more via the split getters). A typical caller asking for all three counters incurs four syscalls and four Rusage struct allocations on every invocation, with no snapshot consistency between them.

Consider fetching Rusage once per updateAttributes() (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 value

Use the imported simple name SystemB.

oshi.jna.platform.mac.SystemB is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4601743 and d43f3af.

📒 Files selected for processing (15)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.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/src/main/java/oshi/driver/mac/MacContextSwitchDriver.java
  • oshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.java
  • oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
  • oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.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-metrics/README.md
  • oshi-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.java
  • oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java
  • oshi-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.java
  • oshi-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: NVCSW is correctly mapped to voluntaryContextSwitches and NIVCSW to involuntaryContextSwitches, matching FreeBSD ps(1) semantics.

oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.java (1)

465-469: Voluntary/involuntary mapping looks correct.

NVCSW → voluntaryContextSwitches and NIVCSW → involuntaryContextSwitches matches OpenBSD ps(1) semantics, and contextSwitches is 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 win

Assertion 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 getrusage for the current process via LinuxOSProcessJNA, confirm that the FFM implementation reads the equivalent counter — otherwise these assertions can fail spuriously when one side uses /proc/[pid]/status and the other uses getrusage.

@dbwiddis
dbwiddis force-pushed the feature/context-switches-split branch from d43f3af to 9694389 Compare May 6, 2026 20:57

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java (2)

19-19: 💤 Low value

Stale class Javadoc — also document getrusage.

LinuxOSProcessJNA's class doc was updated in this PR to mention both getrlimit and getrusage, but this class still says only getrlimit.

📝 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 value

Same dual-getrusage pattern as the JNA class — consider populating once per refresh.

Each split getter allocates an Arena, calls getrusage(RUSAGE_SELF), and reads one field. The default getContextSwitches() triggers two such syscalls, and the two values are not from the same snapshot. A single updateAttributes() override that calls getrusage once and writes both fields would be more efficient and atomic, mirroring the macOS FFM approach in this PR. (Same suggestion applies to LinuxOSProcessJNA; 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) use import 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 value

Two getrusage syscalls per getContextSwitches() and per-call non-atomicity.

Each split getter allocates a fresh Rusage and invokes getrusage(RUSAGE_SELF). The default getContextSwitches() in OSProcess sums them, so a total query results in two syscalls rather than one, and the voluntary/involuntary values come from different snapshots (so voluntary + involuntary != getContextSwitches() strictly speaking, even under steady state).

Consider populating both fields once via a single getrusage call in an updateAttributes() override (mirroring the MacOSProcessFFM pattern in this PR) so the parent's /proc/status values are simply overwritten with getrusage data 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

📥 Commits

Reviewing files that changed from the base of the PR and between d43f3af and 9694389.

📒 Files selected for processing (18)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.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/linux/LinuxLibcFunctions.java
  • oshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.java
  • oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
  • oshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.java
  • oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
  • oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.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-metrics/README.md
  • oshi-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.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-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/0 when bindTo() runs, so the registry ends up with no process.context_switches series 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_switches from /proc/<pid>/status are correctly mapped to the new split counters. Relying on the interface's default getContextSwitches() (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_nvcsw at 128 (32 + 12×8) and ru_nivcsw at 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 with updateAttributes.

Single getrusage(RUSAGE_SELF) per refresh keeps voluntary/involuntary atomically consistent and overwrites contextSwitches with the sum so getContextSwitches() matches the split for the current process. The inner try/catch (Throwable) correctly contains the failure so the outer block does not flip state to INVALID. Non-current processes fall through to pti_csw only, 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 → voluntaryContextSwitches and NIVCSW → involuntaryContextSwitches mapping matches OpenBSD ps(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 → voluntaryContextSwitches and PsKeywords.NIVCSW → involuntaryContextSwitches is 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 >= jna assertions are sound: counters from getrusage are monotonic non-decreasing, FFM is invoked second, and platforms where the split is unavailable (Windows/AIX) trivially satisfy 0 >= 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 rusage mapping used by the FFM path.


229-229: Native getrusage handle 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: Public getrusage wrapper is clean and consistent.

The wrapper keeps invocation semantics uniform with other libc calls and provides a clear contract for callers.

Comment on lines +436 to 463
/**
* 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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

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.

@dbwiddis
dbwiddis force-pushed the feature/context-switches-split branch from 9694389 to e4ade3f Compare May 6, 2026 21:29

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java (1)

20-54: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Same 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 that super(...) populated via the virtually-dispatched updateAttributes() override. After construction the caches are -1, so the JNA getrusage fix is silently bypassed and getVoluntaryContextSwitches()/getInvoluntaryContextSwitches() return the misleading /proc/<pid>/status values issue #2904 was meant to fix. Apply the same fix proposed for LinuxOSProcessFFM (replace the -1 sentinel with a boolean rusagePopulated flag, and add a corresponding getContextSwitches() override that returns cachedVoluntary + cachedInvoluntary when 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9694389 and e4ade3f.

📒 Files selected for processing (18)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.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/linux/LinuxLibcFunctions.java
  • oshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.java
  • oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
  • oshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.java
  • oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
  • oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.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-metrics/README.md
  • oshi-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.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
  • oshi-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/0 when bindTo() runs, so this branch may permanently register process.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 and pr_ictx → involuntary context switches, and the new getters cleanly expose them. The default getContextSwitches() 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 getrusage failure) 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 → voluntaryContextSwitches and nonvoluntary_ctxt_switches → involuntaryContextSwitches is 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 via getrusage(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 → voluntaryContextSwitches and PsKeywords.NIVCSW → involuntaryContextSwitches matches OpenBSD ps(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 FreeBSD ps(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.

@dbwiddis
dbwiddis force-pushed the feature/context-switches-split branch from e4ade3f to 9f746d9 Compare May 6, 2026 21:46

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
oshi-common/src/main/java/oshi/software/os/OSProcess.java (1)

436-463: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Use an explicit split-support signal instead of overloading 0.

0 is a valid context-switch count, so these defaults make “unsupported” indistinguishable from “supported but idle.” That already leaks downstream into ProcessMetrics.bindTo(), where the registry shape depends on the first sampled values and a split-capable process can register no process.context_switches series 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

📥 Commits

Reviewing files that changed from the base of the PR and between e4ade3f and 9f746d9.

📒 Files selected for processing (18)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.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/linux/LinuxLibcFunctions.java
  • oshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.java
  • oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
  • oshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.java
  • oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
  • oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.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-metrics/README.md
  • oshi-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.java
  • oshi-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.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java
  • oshi-core/src/main/java/oshi/software/os/unix/solaris/SolarisOSProcess.java
  • oshi-core/src/main/java/oshi/software/os/unix/openbsd/OpenBsdOSProcess.java
  • oshi-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 OSProcess split-counter design.

Also applies to: 387-394


459-462: NVCSW/NIVCSW mapping is correct.

The parsed values are assigned to the matching voluntary/involuntary fields without accidental inversion.

@dbwiddis
dbwiddis force-pushed the feature/context-switches-split branch from 9f746d9 to 5f025ee Compare May 6, 2026 21:57

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java (1)

115-133: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Don't make meter registration depend on the first sampled value.

Line 119 still uses total > 0 as the proxy for split support. A split-capable process can legitimately report 0 voluntary and 0 involuntary switches when bindTo() runs, and this branch then registers no process.context_switches meters for the lifetime of the registry. Since OSProcess currently uses 0 for 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9f746d9 and 5f025ee.

📒 Files selected for processing (18)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.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/linux/LinuxLibcFunctions.java
  • oshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.java
  • oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
  • oshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.java
  • oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
  • oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.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-metrics/README.md
  • oshi-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.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.java
  • oshi-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
@dbwiddis
dbwiddis force-pushed the feature/context-switches-split branch from 5f025ee to 2dd71f4 Compare May 6, 2026 22:21

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
oshi-metrics/src/main/java/oshi/metrics/ProcessMetrics.java (1)

119-133: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Metric registration is still startup-sample dependent.

Line 119-133 gates registration on total > 0, so a split-capable process with an initial 0/0/0 sample registers no process.context_switches meter 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 OSProcess and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5f025ee and 2dd71f4.

📒 Files selected for processing (18)
  • CHANGELOG.md
  • oshi-benchmark/src/test/java/oshi/comparison/NativeComparisonTest.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/linux/LinuxLibcFunctions.java
  • oshi-core-ffm/src/main/java/oshi/ffm/mac/MacSystemFunctions.java
  • oshi-core-ffm/src/main/java/oshi/software/os/linux/LinuxOSProcessFFM.java
  • oshi-core-ffm/src/main/java/oshi/software/os/mac/MacOSProcessFFM.java
  • oshi-core/src/main/java/oshi/jna/platform/linux/LinuxLibc.java
  • oshi-core/src/main/java/oshi/jna/platform/mac/SystemB.java
  • oshi-core/src/main/java/oshi/jna/platform/unix/CLibrary.java
  • oshi-core/src/main/java/oshi/software/os/linux/LinuxOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/mac/MacOSProcessJNA.java
  • oshi-core/src/main/java/oshi/software/os/unix/freebsd/FreeBsdOSProcess.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-metrics/README.md
  • oshi-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 contextSwitches fallback behavior while resetting split counters on failed getrusage, which avoids stale split values.

@dbwiddis
dbwiddis merged commit 27517c1 into oshi:master May 6, 2026
18 of 19 checks passed
dbwiddis added a commit that referenced this pull request May 9, 2026
- Add native-free Linux SystemInfoProvider and Apple Silicon fix to 7.2.0
- Fix issue links to point to implementing PRs (#3230, #3232, #3227)
- Add macOS disk type (#3231) and OSFileStore fast path (#3195)
- Mention native-free Linux option in README Usage section
@dbwiddis
dbwiddis deleted the feature/context-switches-split branch May 18, 2026 23:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Context switches on Linux may be misleading

1 participant