Skip to content

Never report a decrease in a BSD process's or thread's CPU time - #3574

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:fix/dfly-usertime-nonmonotonic
Aug 3, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:fix/dfly-usertime-nonmonotonic

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 3, 2026 •

Copy link
Copy Markdown
Member

OperatingSystemTest.testProcessStats has been intermittently failing on the DragonFly BSD 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 looks like.

Root cause

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 -awwxo pid,nlwp,time,ucomm -p <pid> samples 500ms apart on the same JVM:

sample 0 1 2 3 4 5 6 7
TIME 0:07.80 0:09.22 0:09.78 0:08.25 0:08.80 0:08.19 0:08.19 0:08.19
NLWP 30 34 34 34 34 33 33 33

The drops track thread count. Separately, the 33 per-thread -H rows summed to 8.29s against a process row of 8.26s.

The cause is in the kernel — DragonFly's process TIME is a sum over currently live LWPs:

  • sys/kern/kern_kinfo.c fill_kinfo_lwp() does kl_uticks += lwp->lwp_thread->td_uticks (note the +=, likewise sticks/iticks).
  • sys/kern/kern_proc.c sysctl_out_proc(): without KERN_PROC_FLAG_LWP, skip_lwp = 1, so the per-LWP bzero(&ki.kp_lwp, ...) is skipped and every live LWP accumulates into one record.
  • bin/ps/print.c cputime() prints KI_LWP(uticks) + KI_LWP(sticks) + KI_LWP(iticks) from that record.
  • An exited LWP's usage folds into the process-level p_ru, which the TIME column 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%. Its printf is diagnostic only and is suppressed when vm_guest != VM_GUEST_NO. DragonFly has no calcru1() and no such warning; none appeared in the CI console.

The fix

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 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 than ps, 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 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 — testThreads carries a workaround asserting the user + kernel total 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's ps offers neither systime nor cputime, so kernelTime is 0 there and user + kernel is arithmetically identical to userTime alone.

Testing

BsdOSProcessTest and BsdOSThreadTest gain coverage for both column shapes (single TIME, and systime + 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 empirical ps behavior is measured on the DragonFly 6.4 CI runner. I do not have DragonFly hardware beyond that VM.

Summary by CodeRabbit

  • Bug Fixes

    • BSD process and thread CPU-time readings no longer decrease between updates when operating-system reports regress.
    • Improved CPU-time consistency across FreeBSD and DragonFly systems, including thread accounting and kernel/user time measurements.
  • Documentation

    • Added FAQ guidance explaining BSD CPU-time behavior and platform-specific differences.
    • Documented the updated behavior in the changelog.

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.
@coderabbitai

coderabbitai Bot commented Aug 3, 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: 8596bf9c-4faf-4182-aada-bf5f231912f6

📥 Commits

Reviewing files that changed from the base of the PR and between 0483b4d and 9f70340.

📒 Files selected for processing (6)
  • CHANGELOG.md
  • FAQ.md
  • 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/test/java/oshi/software/common/os/unix/bsd/BsdOSProcessTest.java
  • oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSThreadTest.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (9)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{java,xml,properties,md}

📄 CodeRabbit inference engine (AGENTS.md)

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

Files:

  • CHANGELOG.md
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSThread.java
  • FAQ.md
  • oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSThreadTest.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
  • oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSProcessTest.java
CHANGELOG.md

📄 CodeRabbit inference engine (AGENTS.md)

Add a Next Release changelog entry only for user-visible changes; omit pure refactors, deduplication, test-only changes, and CI configuration changes.

Files:

  • CHANGELOG.md
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/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/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/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSThreadTest.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
  • oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSProcessTest.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/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
**/src/test/java/**/*Test.java

📄 CodeRabbit inference engine (AGENTS.md)

Write tests against parsing and transformation methods using fixture data; keep acquisition methods thin. Do not add Mockito, and use JUnit 5 with Hamcrest.

Files:

  • oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSThreadTest.java
  • oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSProcessTest.java
**/*Test.java

📄 CodeRabbit inference engine (AGENTS.md)

Test hardware-dependent behavior using invariants, plausible ranges, correct types, and ordering rather than fixed machine-specific values; treat zero and empty results as valid where applicable.

Files:

  • oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSThreadTest.java
  • oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSProcessTest.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/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/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/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/common/os/unix/bsd/BsdOSThread.java
  • oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSThreadTest.java
  • oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java
  • oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSProcessTest.java
🪛 LanguageTool
FAQ.md

[grammar] ~456-~456: Ensure spelling is correct
Context: ...es the total. Sampling a busy JVM every 500ms on DragonFly 6.4 produced 7.80, 9.22, 9...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)


[grammar] ~462-~462: Ensure spelling is correct
Context: ...e previous values for regressions under 3µs or 1%, and prints `calcru: runtime went...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)

🔇 Additional comments (6)
oshi-common/src/main/java/oshi/software/common/os/unix/bsd/BsdOSProcess.java (1)

204-216: LGTM!

Also applies to: 243-258

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

71-84: LGTM!

oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSProcessTest.java (1)

11-11: LGTM!

Also applies to: 107-156

oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSThreadTest.java (1)

1-74: LGTM!

CHANGELOG.md (1)

10-10: LGTM!

FAQ.md (1)

445-467: LGTM!


📝 Walkthrough

Walkthrough

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

Changes

BSD CPU-time monotonicity

Layer / File(s) Summary
Monotonic process and thread parsing
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
BSD process and thread parsing clamps kernel and user CPU times to previously reported values when parsed readings decrease.
Timing regression coverage and documentation
oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSProcessTest.java, oshi-common/src/test/java/oshi/software/common/os/unix/bsd/BsdOSThreadTest.java, CHANGELOG.md, FAQ.md
Tests cover single-TIME and separate system-time formats. Documentation describes DragonFly and FreeBSD CPU-time behavior.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • oshi/oshi#3562: Related BSD process/thread CPU-time monotonicity and FreeBSD user-time test handling.

Suggested reviewers: krillsson

Poem

A rabbit watched the CPU clock,
No backward hops, no ticking shock.
Kernel and user times stay in line,
Tests guard each reading, time after time.
BSD notes now tell the tale.

🚥 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 the main change: preventing decreases in BSD process and thread CPU time.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 79.89%. Comparing base (0f48066) to head (9f70340).
⚠️ Report is 2 commits behind head on master.

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     
Flag Coverage Δ
freebsd 33.32% <80.00%> (+0.07%) ⬆️
linux 37.44% <80.00%> (+0.22%) ⬆️
macos 38.38% <80.00%> (+0.18%) ⬆️
openbsd 32.49% <100.00%> (+0.11%) ⬆️
solaris 33.99% <80.00%> (+0.23%) ⬆️
windows 45.21% <80.00%> (+0.21%) ⬆️

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 44f804b into oshi:master Aug 3, 2026
16 checks passed
@dbwiddis
dbwiddis deleted the fix/dfly-usertime-nonmonotonic branch August 3, 2026 23:40
dbwiddis added a commit that referenced this pull request Aug 4, 2026
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.
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