Repository navigation
Synchronize the BSD ps-family updateAttributes instead of suppressing S3078 - #3586
Conversation
… 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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
📜 Recent review details⏰ Context from checks skipped due to timeout. (11)
🧰 Additional context used📓 Path-based instructions (5)oshi-common/src/main/java/**/*.java📄 CodeRabbit inference engine (AGENTS.md)
Files:
{oshi-common,oshi-core}/src/main/java/**/*.java📄 CodeRabbit inference engine (AGENTS.md)
Files:
**/*.java📄 CodeRabbit inference engine (AGENTS.md)
Files:
**/src/main/java/**/*.java📄 CodeRabbit inference engine (AGENTS.md)
Files:
**/*.{java,xml,properties,md}📄 CodeRabbit inference engine (AGENTS.md)
Files:
🧠 Learnings (4)📚 Learning: 2026-04-12T19:22:09.716ZApplied to files:
📚 Learning: 2026-07-06T19:25:59.225ZApplied to files:
📚 Learning: 2026-07-30T00:35:22.638ZApplied to files:
📚 Learning: 2026-08-03T00:46:14.953ZApplied to files:
🔇 Additional comments (4)
📝 WalkthroughWalkthroughBSD process and thread attribute updates are now synchronized. Public documentation describes refresh usage, bulk monitoring, efficiency, and sampling consistency requirements. ChangesAttribute update synchronization
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
* 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.
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.
Resolves the two Coverity
VOLATILE_ATOMICITYfindings on the BSD monotonic clamps (CID 1677110, CID 1677109) and the matching Sonarjava:S3078reports, 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
psreading), but the fix is cheap enough that suppressing was the worse trade.Why
synchronizedAixHWDiskStore.updateAttributes()already performs the same monotonic read-modify-write undersynchronized, and is the only one of the 44updateAttributes()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 bulkps-list path (10 call sites). It also covers the read-modify-write inOpenBsdOSProcess.updateThreadCount().Cost is irrelevant against the
fork/execofpsthat precedes it, and it makes the whole ~20-field set update atomically, so concurrent refreshes can no longer interleave values from two differentpssamples. Checked for nested locking: the only methods called inside arequeryStartTimeMillis()(a no-op default; DragonFly reads/proc) andupdateThreadCount()(a no-op default; OpenBSD/NetBSD runps). Neither acquires another object's monitor.synchronizedis not part of the method signature, so japicmp stays at0.0.1.The suppression comments were citing a contract that did not exist
Both removed annotations justified themselves with:
It does not. That language lives only on
NetworkIFandHWDiskStore. This PR adds it toOSProcessandOSThread, along with the "re-query the full list" guidance already stated authoritatively inPERFORMANCE.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>/psinfobinary structs via theirPsInfodrivers rather than parsingpsoutput, soBsdOSProcess/BsdOSThreadare 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/PowerSourcelayer 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:S3078may 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
Documentation