Skip to content

Synchronize the BSD ps-family updateAttributes instead of suppressing S3078 - #3586

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:sync-bsd-ps-update-attributes
Aug 5, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:sync-bsd-ps-update-attributes

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

Resolves the two Coverity VOLATILE_ATOMICITY findings on the BSD monotonic clamps (CID 1677110, CID 1677109) and the matching Sonar java:S3078 reports, by taking a lock rather than suppressing.

Why not dismiss

The race is real and defeats the clamp it sits on. Two refreshes can both read the same previous value; if the lower one lands last, the reported CPU time decreases — exactly what monotonic() was added to prevent in #3574. Before that fix these were plain volatile writes, which are atomic; the clamp introduced the read-modify-write.

Impact is small (a lost clamp still leaves a genuine ps reading), but the fix is cheap enough that suppressing was the worse trade.

Why synchronized

AixHWDiskStore.updateAttributes() already performs the same monotonic read-modify-write under synchronized, and is the only one of the 44 updateAttributes() implementations Coverity does not flag. This follows a pattern already in the tree.

The lock goes on the protected updateAttributes(Map) overload rather than the public no-arg method, because that overload is the sole writer of these fields and is reached from two directions — the public refresh, and each platform's constructor on the bulk ps-list path (10 call sites). It also covers the read-modify-write in OpenBsdOSProcess.updateThreadCount().

Cost is irrelevant against the fork/exec of ps that precedes it, and it makes the whole ~20-field set update atomically, so concurrent refreshes can no longer interleave values from two different ps samples. Checked for nested locking: the only methods called inside are queryStartTimeMillis() (a no-op default; DragonFly reads /proc) and updateThreadCount() (a no-op default; OpenBSD/NetBSD run ps). Neither acquires another object's monitor.

synchronized is not part of the method signature, so japicmp stays at 0.0.1.

The suppression comments were citing a contract that did not exist

Both removed annotations justified themselves with:

OSProcess documents that concurrent updateAttributes() callers must synchronize externally

It does not. That language lives only on NetworkIF and HWDiskStore. This PR adds it to OSProcess and OSThread, along with the "re-query the full list" guidance already stated authoritatively in PERFORMANCE.md.

That contract is worth keeping even with the lock, because it addresses a different problem: a reader calling two getters across an intervening update still sees two samples. That is true on every platform, lock or not.

Scope

Deliberately limited to the BSD ps-family. AIX and Solaris read /proc/<pid>/psinfo binary structs via their PsInfo drivers rather than parsing ps output, so BsdOSProcess/BsdOSThread are the entire family — and the entire set of Coverity findings.

This is the first slice of a consistency arc across all 44 implementations, which diverge on four axes (synchronization 1-in-44, the documented contract on 2 of 6 interfaces, polling guidance on 1.5 of 6, and two independent spellings of "monotonic"). The remaining process/thread implementations and the OSFileStore/HWDiskStore/NetworkIF/PowerSource layer are queued for the next minor version, deliberately kept out of a release branch.

Verification

Full gate green from a clean root build: spotless, sortpom, checkstyle (0 violations), install, forbiddenapis, javadoc. Tests 1311 / 119 / 96 / 30, 0 failed.

Behavior is unchanged on every platform — this only constrains interleaving.

Note

Coverity understands lock-guarded read-modify-writes, so both CIDs should clear. Sonar java:S3078 may be more syntactic; if it re-fires under the lock, the suppression can go back — but with a justification that is actually true this time.

Summary by CodeRabbit

  • Bug Fixes

    • Improved consistency when refreshing BSD process and thread information, helping prevent mixed or out-of-sync attribute values during concurrent updates.
  • Documentation

    • Added guidance on refreshing process and thread data, including recommendations for monitoring multiple items efficiently and safely.

… S3078

The monotonic() clamps added for the BSD CPU-time fix read and write a
volatile long, which Coverity flagged as VOLATILE_ATOMICITY (CID 1677110,
CID 1677109). The race is real and defeats the clamp: two refreshes can
both read the same previous value, and if the lower one lands last the
reported time decreases, which is exactly what monotonic() exists to
prevent.

Take the lock instead. AixHWDiskStore.updateAttributes() already does the
same monotonic read-modify-write under synchronized and is the only one of
the 44 updateAttributes() implementations that Coverity does not flag, so
this follows a pattern already in the tree rather than introducing one.

The lock goes on the protected updateAttributes(Map) overload rather than
the public no-arg method because that overload is the sole writer of these
fields and is reached from two directions: the public refresh, and each
platform's constructor on the bulk ps-list path. It also covers the
read-modify-write in OpenBsdOSProcess.updateThreadCount(). Cost is
irrelevant against the fork/exec of ps that precedes it, and it makes the
whole ~20-field set update atomically, so concurrent refreshes can no
longer interleave values from two different ps samples.

Both @SuppressWarnings("java:S3078") annotations are removed. Their
justification cited a contract that did not exist: the comments claimed
OSProcess documents that concurrent updateAttributes() callers must
synchronize externally, but that language lives only on NetworkIF and
HWDiskStore. Add it to OSProcess and OSThread, along with the
"re-query the full list" guidance from PERFORMANCE.md, so the four
interfaces carrying updateAttributes() in the process/thread layer state
the same contract. That contract is about readers seeing two samples
across separate getter calls, which the lock does not address and which
applies on every platform.

Scoped to the BSD ps-family; AIX and Solaris read /proc psinfo structs
rather than parsing ps output. Remaining implementations to follow.
@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a5464782-b474-4d17-9258-fef44322b3f8

📥 Commits

Reviewing files that changed from the base of the PR and between cd7034c and bfc44e3.

📒 Files selected for processing (4)
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/main/java/oshi/software/os/OSProcess.java
  • oshi-common/src/main/java/oshi/software/os/OSThread.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (11)
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
📓 Path-based instructions (5)
oshi-common/src/main/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

oshi-common/src/main/java/**/*.java: Keep oshi-common pure Java: do not reference JNA, FFM (java.lang.foreign), or System.load/loadLibrary; place parsing, conversion, validation, caching, and shared implementation logic here when it is not native-API-specific.
Before adding a general parsing helper, check oshi.util.ParseUtil; use its existing parsing methods or add shared primitives there rather than duplicating parsers in platform drivers.
Read runtime configuration from oshi-common/src/main/resources/oshi.properties through GlobalConfig or Java system properties; do not introduce a separate configuration mechanism.

Files:

  • oshi-common/src/main/java/oshi/software/os/OSThread.java
  • oshi-common/src/main/java/oshi/software/os/OSProcess.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
{oshi-common,oshi-core}/src/main/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

Use Java 8 language and API compatibility: do not use var, records, switch expressions, text blocks, List.of, Stream.toList(), or other post-Java-8 features.

Files:

  • oshi-common/src/main/java/oshi/software/os/OSThread.java
  • oshi-common/src/main/java/oshi/software/os/OSProcess.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

**/*.java: Do not use banned numeric parsing APIs such as Integer.parseInt, Long.parseLong, Double.parseDouble, or Integer.decode; use the corresponding tolerant ParseUtil methods.
Do not import org.slf4j.event.**; use oshi.util.LogLevel instead.

Files:

  • oshi-common/src/main/java/oshi/software/os/OSThread.java
  • oshi-common/src/main/java/oshi/software/os/OSProcess.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
**/src/main/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

**/src/main/java/**/*.java: Keep external imports synchronized with config/import-control.xml, the module's module-info.java, and, when necessary, its Maven configuration.
Provide Javadoc for every public and protected type and method; use imported simple class names rather than fully qualified names in code and Javadoc links.
Use the repository's concurrency annotation (@ThreadSafe, @Immutable, @NotThreadSafe, or @GuardedBy) on new classes, matching the modeled class where appropriate.
Memoize constant or expensive, slowly changing system values with oshi.util.Memoizer.memoize, generally using a Supplier<T> and defaultExpiration() when refresh is required.
Do not duplicate non-native logic between platform implementations; hoist parsing, conversion, filtering, caching, validation, and sentinel handling into oshi-common where possible.

Files:

  • oshi-common/src/main/java/oshi/software/os/OSThread.java
  • oshi-common/src/main/java/oshi/software/os/OSProcess.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
**/*.{java,xml,properties,md}

📄 CodeRabbit inference engine (AGENTS.md)

Do not commit generated output, target/, or IDE files.

Files:

  • oshi-common/src/main/java/oshi/software/os/OSThread.java
  • oshi-common/src/main/java/oshi/software/os/OSProcess.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
🧠 Learnings (4)
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/software/os/OSThread.java
  • oshi-common/src/main/java/oshi/software/os/OSProcess.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
📚 Learning: 2026-07-06T19:25:59.225Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3432
File: oshi-common/src/main/java/oshi/util/ExceptionUtil.java:26-56
Timestamp: 2026-07-06T19:25:59.225Z
Learning: In this repo’s SLF4J 1.x-compatible logging code, do not flag cases where a logger call uses SLF4J 1.6+ implicit-cause handling—e.g., `log.error("...{}", value, t)` (or similar with a single `{}` placeholder) where `t` is passed as the final/trailing argument. SLF4J will attach `t` as the log event’s cause with the full stack trace; this is equivalent to SLF4J 2.x’s fluent `atLevel(...).setCause(t).log(...)` and is intentionally used to preserve SLF4J 1.x runtime compatibility.

Applied to files:

  • oshi-common/src/main/java/oshi/software/os/OSThread.java
  • oshi-common/src/main/java/oshi/software/os/OSProcess.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
📚 Learning: 2026-07-30T00:35:22.638Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3547
File: oshi-common/src/main/java/oshi/hardware/common/platform/unix/BsdFirmware.java:82-82
Timestamp: 2026-07-30T00:35:22.638Z
Learning: In OSHI, treat changes as “API-breaking” only when they affect classes (or relevant API surface) annotated with `PublicAPI`. Public classes/members that are not annotated with `PublicAPI` should be reviewed as internal implementation details, even if they are public (e.g., classes like `oshi.hardware.common.platform.unix.BsdFirmware`). Also, respect intentional visibility decisions used for tests—e.g., methods like `BsdFirmware.parseDmesg(List<String>)` may be intentionally package-private to support tests within the same package; avoid widening visibility or altering signatures unless the related `PublicAPI` contract requires it.

Applied to files:

  • oshi-common/src/main/java/oshi/software/os/OSThread.java
  • oshi-common/src/main/java/oshi/software/os/OSProcess.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
📚 Learning: 2026-08-03T00:46:14.953Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3566
File: oshi-common/src/main/java/oshi/software/common/os/unix/openbsd/OpenBsdNetworkParams.java:18-22
Timestamp: 2026-08-03T00:46:14.953Z
Learning: In the OSHI Java codebase, do not require duplicate Javadoc on public methods annotated with Override when the inherited Javadoc from the parent declaration adequately documents the method. The general public-member Javadoc requirement should not flag these overrides solely because they lack redundant documentation.

Applied to files:

  • oshi-common/src/main/java/oshi/software/os/OSThread.java
  • oshi-common/src/main/java/oshi/software/os/OSProcess.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
🔇 Additional comments (4)
oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java (1)

173-183: LGTM!

oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java (1)

56-65: LGTM!

oshi-common/src/main/java/oshi/software/os/OSProcess.java (1)

35-44: LGTM!

oshi-common/src/main/java/oshi/software/os/OSThread.java (1)

17-26: LGTM!


📝 Walkthrough

Walkthrough

BSD process and thread attribute updates are now synchronized. Public documentation describes refresh usage, bulk monitoring, efficiency, and sampling consistency requirements.

Changes

Attribute update synchronization

Layer / File(s) Summary
Synchronized BSD updates
oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java, oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
updateAttributes() is synchronized for BSD processes and threads. Field refreshes and monotonic CPU-time updates execute under the instance lock.
Refresh usage documentation
oshi-common/src/main/java/oshi/software/os/OSProcess.java, oshi-common/src/main/java/oshi/software/os/OSThread.java
Javadoc describes individual and bulk refresh usage, refresh cost, thread safety, and external synchronization for consistent multi-getter samples.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • oshi/oshi#3288: Directly concerns OSProcess and OSThread.updateAttributes() behavior.
  • oshi/oshi#3489: Also modifies BsdOSProcess attribute-update concurrency.
  • oshi/oshi#3574: Introduced related BSD CPU-time handling.

Poem

I’m a rabbit guarding each sample with care,
Process and thread updates now lock in the air.
CPU times move forward, refreshes align,
Clear docs explain when samples combine.
Hop, hop—consistent values shine!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes synchronizing BSD ps-family updateAttributes methods and removing the S3078 suppression.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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.

@codecov

codecov Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.84%. Comparing base (cd7034c) to head (bfc44e3).

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3586      +/-   ##
============================================
- Coverage     79.88%   79.84%   -0.05%     
- Complexity     3866     4226     +360     
============================================
  Files           710      710              
  Lines         24242    24242              
  Branches       4052     4052              
============================================
- Hits          19366    19356      -10     
- Misses         2718     2725       +7     
- Partials       2158     2161       +3     
Flag Coverage Δ
freebsd 33.49% <ø> (-0.01%) ⬇️
linux 37.61% <ø> (+0.01%) ⬆️
macos 38.42% <ø> (-0.05%) ⬇️
openbsd 32.67% <ø> (+<0.01%) ⬆️
solaris 34.16% <ø> (+<0.01%) ⬆️
windows 45.37% <ø> (-0.03%) ⬇️

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

☔ View full report in Codecov by Harness.
📢 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 merged commit a16e1ab into oshi:master Aug 5, 2026
16 checks passed
@dbwiddis
dbwiddis deleted the sync-bsd-ps-update-attributes branch August 5, 2026 23:42
dbwiddis added a commit that referenced this pull request Aug 18, 2026
* Clamp file store space against locals rather than the fields being written

setSpace assigned each volatile and then read it back to bound the next one, so
the method that exists to guarantee an ordering was itself a read-modify-write.
Two concurrent refreshes could interleave and leave a triple violating it:

    A: total = 100
    A: free  = min(50, 100) = 50
    B: total = 10
    A: usable = min(30, this.freeSpace = 50) = 30
       -> total=10, free=50, usable=30, and free > total

Compute the three into locals and assign once. The clamps then bound values from
a single reading, whatever else is writing concurrently.

* Synchronize the disk and file store refresh paths

Continues the updateAttributes() consistency arc from #3586, which established
the pattern on the BSD process and thread implementations: the lock goes on the
method that writes the fields, and no suppression is kept alongside it. Coverity
and Sonar are both clean on that shape now, so it is the standard rather than a
proposal.

The file store side needed only one file. #3651 made AbstractOSFileStore the
sole writer of the mutable fields -- no platform class assigns them -- so
locking its three update entry points covers all ten implementations at once.
setSpace stays private and is only reached from them, hence unlocked.

HWDiskStore has no such choke point: eight of its platform classes write the
counters directly, so each updateAttributes() takes the lock itself. That
matches AixHWDiskStore, which has been the only synchronized one since #3586 and
whose monotonic clamps are read-modify-writes that the lock now protects
everywhere rather than in one place.

Verified no implementation acquires a second lock inside the method, and that
every caller is a freshly constructed store inside a getDisks() factory holding
nothing, so there is no ordering hazard.

OSFileStore was one of two interfaces carrying no thread-safety contract; it now
states the externally-synchronize guidance the other four have, the space
ordering it guarantees, and the prefer-the-full-list advice. PowerSource, the
other, comes with the network chunk.
dbwiddis added a commit that referenced this pull request Aug 18, 2026
Final chunk of the updateAttributes() consistency arc begun in #3586, after
#3653 and #3654. Every refreshable type is now covered.

This is the phase the arc flagged as highest risk, for two reasons that both
turned out to be answered by locking the writer rather than the public method.

Where a class writes its fields in an overload -- AIX process, and Windows
process and thread -- the lock goes there, matching what #3586 did for the BSD
pair. That is not a stylistic choice: every one of those overloads is called
from a subclass constructor doing bulk population, so locking only the public
no-arg would leave the list-building path unguarded while appearing to cover it.

It also keeps the expensive work outside the lock. The Windows twins do all
their registry, performance counter and WTS querying in the public method before
delegating, so no WMI or COM call happens under the monitor -- verified, not
assumed. The BSD pair likewise spawns ps outside it.

Where a class writes inline instead, with no separate writer to target --
Solaris process and thread, Linux process and thread, AIX thread, and both macOS
process backends -- the no-arg takes the lock and its queries come with it.
macOS interleaves proc_pidinfo, proc_pidpath and getpwuid with the assignments,
so there is nothing to separate; this matches the six NetworkIF platforms in
#3654.

WindowsOSThreadJNA and WindowsOSThreadFFM need nothing: they write no fields and
delegate to the base overload now locked.

Verified no locked body acquires a second lock, so there is no ordering hazard.

Not included: hoisting BsdOSProcess.monotonic to share with AixHWDiskStore's
inline clamps, the arc's last open item. Both are now lock-protected, so it is
purely a duplication question, and it needs a home neutral to both hierarchies.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant