Repository navigation
Never report a decrease in a BSD process's or thread's CPU time - #3574
Conversation
OperatingSystemTest.testProcessStats intermittently failed on the DragonFly CI VM with "User time should be nondecreasing after update" (observed 7890 -> 7590, 16560 -> 16090, 10540 -> 10340). The drops are multiples of 10ms rather than 1000ms, so this is not the coarse one-second ps resolution it first looked like. A temporary debug harness on the DragonFly runner showed the regression is present in raw ps output with OSHI out of the picture. Eight `ps -o nlwp,time` samples 500ms apart on the same JVM returned 7.80, 9.22, 9.78, 8.25, 8.80, 8.19, 8.19, 8.19 seconds while NLWP moved 30, 34, 34, 34, 34, 33, 33, 33, and the 33 per-thread rows summed to 8.29s against a process row of 8.26s. The cause is in the kernel. Without KERN_PROC_FLAG_LWP, sysctl_out_proc() accumulates every live LWP into one record -- fill_kinfo_lwp() does `kl_uticks += lwp->lwp_thread->td_uticks` and the per-LWP bzero is skipped -- and ps prints uticks+sticks+iticks from it. An exited LWP's usage folds into the process-level p_ru, which the TIME column never reads, so a thread's CPU time leaves the total when that thread exits. Rather than relax the assertion, enforce monotonicity where the ps row is parsed. Adds BsdOSProcess.monotonic(previous, parsed) and applies it in both shared BSD ps-row parsers: BsdOSProcess.updateAttributes(psMap) and BsdOSThread.updateAttributes(threadMap). The fields start at 0 and every other caller of those methods is a constructor, so the clamp only ever binds on a genuine re-read of the same process or thread. This mirrors what FreeBSD's kernel already does for its own consumers: calcru1() enforces monotonicity on the user/system buckets it derives from a statistical tick ratio, restores prior values for regressions under 3us or 1%, and warns `calcru: runtime went backwards` on larger ones. DragonFly has no calcru1() and no such warning (none appeared in the CI console), so the guard belongs in userland. It also matches the existing precedent in AixHWDiskStore.updateAttributes, which already declines to decrease a previously-reported counter -- though that one clamps values derived from perfstat rather than ps, so the two do not share code. Applied to the whole BSD family rather than DragonFly alone: the FreeBSD path derives user time by subtracting two independently-sampled ps columns, which is susceptible to the same effect. The thread path is included because it has the same shape and has already been seen to dip -- OperatingSystemTest.testThreads carries a workaround asserting the user+kernel total for exactly that reason. That workaround is left in place: it also covers macOS, where no BSD clamp runs. Adds BsdOSProcessTest and BsdOSThreadTest coverage for both the single-TIME-column and the systime-plus-TIME shapes, and documents the behavior in FAQ.md.
|
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 (6)
📜 Recent review details⏰ Context from checks skipped due to timeout. (9)
🧰 Additional context used📓 Path-based instructions (8)**/*.{java,xml,properties,md}📄 CodeRabbit inference engine (AGENTS.md)
Files:
CHANGELOG.md📄 CodeRabbit inference engine (AGENTS.md)
Files:
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:
**/src/test/java/**/*Test.java📄 CodeRabbit inference engine (AGENTS.md)
Files:
**/*Test.java📄 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:
🪛 LanguageToolFAQ.md[grammar] ~456-~456: Ensure spelling is correct (QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1) [grammar] ~462-~462: Ensure spelling is correct (QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1) 🔇 Additional comments (6)
📝 WalkthroughWalkthroughBSD process and thread CPU-time updates now prevent kernel and user times from decreasing between readings. Tests cover BSD timing formats and regressions. The changelog and FAQ document DragonFly and FreeBSD accounting behavior. ChangesBSD CPU-time monotonicity
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Suggested reviewers: 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 #3574 +/- ##
============================================
- Coverage 79.90% 79.89% -0.02%
- Complexity 76 198 +122
============================================
Files 709 709
Lines 24198 24213 +15
Branches 4047 4049 +2
============================================
+ Hits 19336 19345 +9
- Misses 2689 2707 +18
+ Partials 2173 2161 -12
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:
|
The monotonic() clamps added in #3574 are read-modify-writes on volatile long fields, which Sonar flags as S3078. The read-modify-write is one of ~20 unsynchronized volatile writes in updateAttributes(); OSProcess documents that concurrent callers must synchronize externally, and both racing writers only ever raise the value, so a lost clamp still yields a real ps reading. Suppress on the two methods rather than convert the shared protected fields to AtomicLong. Also restore ascending PR-number order in the 7.4.4 changelog, where the #3574 squash-merge landed the entry above #3569 and #3573.
OperatingSystemTest.testProcessStatshas been intermittently failing on the DragonFly BSD CI VM withUser time should be nondecreasing after update(observed 7890 → 7590, 16560 → 16090, 10540 → 10340).The drops are multiples of 10ms rather than 1000ms, so this is not the coarse one-second
psresolution it first looks like.Root cause
A temporary debug harness on the DragonFly runner showed the regression is present in raw
psoutput with OSHI out of the picture. Eightps -awwxo pid,nlwp,time,ucomm -p <pid>samples 500ms apart on the same JVM:TIMENLWPThe drops track thread count. Separately, the 33 per-thread
-Hrows summed to 8.29s against a process row of 8.26s.The cause is in the kernel — DragonFly's process
TIMEis a sum over currently live LWPs:sys/kern/kern_kinfo.cfill_kinfo_lwp()doeskl_uticks += lwp->lwp_thread->td_uticks(note the+=, likewise sticks/iticks).sys/kern/kern_proc.csysctl_out_proc(): withoutKERN_PROC_FLAG_LWP,skip_lwp = 1, so the per-LWPbzero(&ki.kp_lwp, ...)is skipped and every live LWP accumulates into one record.bin/ps/print.ccputime()printsKI_LWP(uticks) + KI_LWP(sticks) + KI_LWP(iticks)from that record.p_ru, which theTIMEcolumn never reads.So when a thread exits, the CPU time it had accumulated leaves the process total.
This is not FreeBSD's
calcru: runtime went backwards. That is a different mechanism, easy to conflate:calcru1()divides a high-resolution runtime by a statistical user/system tick ratio, and it does clamp — flooring the buckets when time advanced and restoring prior values for regressions under 3µs or 1%. Itsprintfis diagnostic only and is suppressed whenvm_guest != VM_GUEST_NO. DragonFly has nocalcru1()and no such warning; none appeared in the CI console.The fix
Rather than relax the assertion, enforce monotonicity where the
psrow is parsed. AddsBsdOSProcess.monotonic(previous, parsed)and applies it in both shared BSDps-row parsers —BsdOSProcess.updateAttributes(psMap)andBsdOSThread.updateAttributes(threadMap).The time fields start at 0 and every other caller of those two methods is a constructor, so the clamp only ever binds on a genuine re-read of the same process or thread.
This mirrors what FreeBSD's kernel already does for its own consumers, and matches the existing precedent in
AixHWDiskStore.updateAttributes, which already declines to decrease a previously-reported counter — though that one clamps values derived from perfstat rather thanps, so the two deliberately do not share code.Applied to the whole BSD family rather than DragonFly alone: the FreeBSD path derives user time by subtracting two independently-sampled
pscolumns, which is susceptible to the same effect. The thread path is included because it has the same shape and has already been seen to dip —testThreadscarries a workaround asserting theuser + kerneltotal for exactly that reason. That workaround is left in place, since it also covers macOS where no BSD clamp runs.Note that a
testThreads-style "assert the total instead" fix could not work for the process case: DragonFly'spsoffers neithersystimenorcputime, sokernelTimeis 0 there anduser + kernelis arithmetically identical touserTimealone.Testing
BsdOSProcessTestandBsdOSThreadTestgain coverage for both column shapes (singleTIME, andsystime+TIME), asserting a regressing row holds at the previous value while a genuine increase passes through.Full gate green locally on macOS/JDK25. All six Unix CI jobs pass on this commit on my fork — DragonFly BSD, FreeBSD, OpenBSD, NetBSD (JNA and no-JNA), and OpenIndiana.
The kernel-source reasoning is read from DragonFly
master; the empiricalpsbehavior is measured on the DragonFly 6.4 CI runner. I do not have DragonFly hardware beyond that VM.Summary by CodeRabbit
Bug Fixes
Documentation