Skip to content

Retry the AIX perfstat_process fill when the buffer filled exactly - #3582

Merged
dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:aix-perfstat-truncation
Aug 4, 2026
Merged

dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:aix-perfstat-truncation

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Summary

perfstat_process is a count-then-fill pair, and it returns its array sorted by pid. A buffer sized from the first call therefore loses the highest-pid entries when processes spawn between the two calls — and the newest process in the list is very often the calling JVM itself. Both twins padded the allocation by 10 to absorb that churn, which is a guess rather than a guarantee.

The existing comment already described the failure mode exactly:

"if we allocate exactly count entries and a new process appears, the highest-pid process (often us, the JVM) gets cut off the tail"

How it surfaced

Five NativeComparisonTest cases failed together on the shared cfarm AIX host — currentProcess, currentProcessThreads, currentProcessUpdateAttributes, currentThread, currentThreadUpdateAttributes — all rooted in getProcess(getProcessId()) returning null, which leaves getCurrentProcess() null and NPEs AixOperatingSystem.getCurrentThread.

It reproduced on both attempts within that run and passed on a re-run of the same commit minutes later, which is the signature of a load-dependent race rather than a code regression. On a busy box more than 10 processes appeared between the two perfstat calls.

Change

Treat ret == padded as possible truncation — the buffer filled exactly, so entries beyond it may have been dropped — and re-count and retry, bounded at 3 attempts. After that the result is returned as-is, since a short list still beats none.

Also raises the pad from 10 to 64. That costs a few KB of a confined arena and makes the retry a rare path rather than the common one.

Applied to both backends. This is the same count-then-fetch race class #3569 fixed for the Windows TCP/UDP connection tables, in a different API.

Verification

Full ./mvnw clean spotless:apply sortpom:sort checkstyle:check install forbiddenapis:check javadoc:javadoc green on JDK 26: 1311/119/96 tests, 0 failures.

This is not reproducible off AIX, and is load-dependent even there, so a green cfarm run does not confirm the fix — only that it does not regress. The reasoning rests on the documented perfstat contract and the sorted-by-pid ordering the previous comment already recorded.

Not in this PR

getCurrentProcess() is declared to return "the current process" with no mention of null, but its default implementation delegates to getProcess(int), which is documented to return null. Every non-Linux getCurrentThread() then dereferences it unguarded (AIX, FreeBSD, OpenBSD, NetBSD, DragonFly, macOS). Rather than sprinkle null guards, the contract should be made true — worth its own change, and discussed separately.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed AIX process listings that could omit processes with the highest process IDs when many processes were created simultaneously.
    • Improved reliability of process discovery by allocating additional capacity and retrying when the available process buffer is filled.
    • Process listings now better handle rapid process creation, reducing incomplete results and preserving successfully collected process information when a refresh cannot complete.

perfstat_process is a count-then-fill pair, and it returns its array
sorted by pid, so a buffer sized from the first call loses the
highest-pid entries when processes spawn in between. The entry lost is
most often the calling JVM's own, which is the newest process in the
list. Both twins padded the allocation by 10 to absorb that churn, which
is a guess rather than a guarantee.

Observed on the shared cfarm AIX host: five NativeComparisonTest cases
failed together on both attempts of one run, all of them rooted in
getProcess(getProcessId()) returning null, and the same commit passed on
a re-run minutes later. Under a busy box more than 10 processes appeared
between the two calls.

Treat a return equal to the allocation as possible truncation: re-count
and retry, bounded at 3 attempts, after which the result is returned as
is because a short list still beats none. Also raise the pad from 10 to
64, which costs a few KB of a confined arena and makes the retry a rare
path rather than the common one.

Applied to both backends. This is the count-then-fetch race class that
#3569 fixed for the Windows connection tables, in a different API.

Not reproducible off AIX, and load-dependent even there, so CI passing
does not confirm the fix; it confirms no regression. The reasoning rests
on the perfstat contract and the sorted-by-pid ordering the previous
comment already documented.
@coderabbitai

coderabbitai Bot commented Aug 4, 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: 8bc4d7f0-2aca-4c7e-b88b-3d15e21c0b18

📥 Commits

Reviewing files that changed from the base of the PR and between a24c167 and da556f8.

📒 Files selected for processing (2)
  • oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.java
  • oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.java
  • oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.java
📜 Recent review details
⏰ Context from checks skipped due to timeout. (11)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 21, ubuntu-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)

📝 Walkthrough

Walkthrough

The AIX FFM and JNA process queries now use larger padded buffers and retry up to three times when results fill the buffer. The changelog records the fix for omitted highest-PID processes.

Changes

AIX process enumeration

Layer / File(s) Summary
Padded process enumeration retries
oshi-core-ffm/.../PerfstatProcessFFM.java, oshi-core/.../PerfstatProcessJNA.java, CHANGELOG.md
Both implementations use the larger of 64 entries or 10% padding. Exact buffer fills trigger recounts and retries. Failed recounts preserve the current full result, and failed initial operations return an empty result. The changelog documents the correction.

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

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant queryProcesses
  participant perfstat_process
  Caller->>queryProcesses: request process list
  queryProcesses->>perfstat_process: count and fill padded buffer
  perfstat_process-->>queryProcesses: returned process count
  alt buffer is exactly full and attempts remain
    queryProcesses->>perfstat_process: recount and refill
    perfstat_process-->>queryProcesses: updated process count
  else buffer is not full or retry limit reached
    queryProcesses-->>Caller: populated process array
  end
Loading

Possibly related PRs

Poem

A rabbit counts each process row,
Then leaves extra room to grow.
When the buffer fills tight,
It counts again right,
So the highest PID can show.

🚥 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 describes the main change: retrying AIX perfstat_process fills when the buffer is exactly full.
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.

@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

🤖 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/driver/unix/aix/perfstat/PerfstatProcessFFM.java`:
- Around line 69-73: In PerfstatProcessFFM.java lines 69-73, store the re-count
from perfstat_process in a temporary variable and continue retrying only when it
is positive; otherwise preserve the current full-buffer result and proceed to
map and return it. Apply the same fallback behavior in PerfstatProcessJNA.java
lines 58-62.
🪄 Autofix

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 Plus

Run ID: 26767b51-0b11-4cf4-9e02-417ca5133a5b

📥 Commits

Reviewing files that changed from the base of the PR and between b56a6a9 and 4200116.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.java
  • oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.java
📜 Review details
⏰ Context from checks skipped due to timeout. (10)
  • GitHub Check: Test JDK 25, OpenBSD (+ JNA==FFM)
  • GitHub Check: Test JDK 25, OpenIndiana (+ JNA==FFM)
  • GitHub Check: Test JDK 25, FreeBSD (+ JNA==FFM)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 26, ubuntu-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{java,xml,properties,md}

📄 CodeRabbit inference engine (AGENTS.md)

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

Files:

  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.java
  • oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.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-core/src/main/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

For changes to an oshi-core implementation, apply the equivalent behavior change to its corresponding oshi-core-ffm twin, or explain why the implementations intentionally differ.

Files:

  • oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.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-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.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-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.java
  • oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.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-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.java
  • oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.java
oshi-core-ffm/src/main/java/**/*.java

📄 CodeRabbit inference engine (AGENTS.md)

oshi-core-ffm/src/main/java/**/*.java: For changes to an oshi-core-ffm implementation, apply the equivalent behavior change to its corresponding oshi-core twin, or explain why the implementations intentionally differ.
Do not reference com.sun.jna from FFM implementation sources.

Files:

  • oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.java
🧠 Learnings (4)
📚 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-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.java
  • oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.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-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.java
  • oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.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-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.java
  • oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.java
📚 Learning: 2026-08-02T23:56:23.866Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3565
File: oshi-core-ffm/src/main/java/oshi/ffm/platform/unix/PosixLibcFunctions.java:51-56
Timestamp: 2026-08-02T23:56:23.866Z
Learning: For Java FFM bindings in the oshi-core-ffm module, assume a 64-bit JVM and 64-bit operating system. Do not flag 32-bit native ABI or memory-layout compatibility concerns, consistent with the project's JDK 25 support policy, unless that policy changes.

Applied to files:

  • oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.java
🔇 Additional comments (3)
oshi-core-ffm/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessFFM.java (1)

40-58: LGTM!

oshi-core/src/main/java/oshi/driver/unix/aix/perfstat/PerfstatProcessJNA.java (1)

26-46: LGTM!

CHANGELOG.md (1)

17-17: LGTM!

@codecov

codecov Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 50 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.77%. Comparing base (b56a6a9) to head (da556f8).

Files with missing lines Patch % Lines
...i/driver/unix/aix/perfstat/PerfstatProcessFFM.java 0.00% 27 Missing ⚠️
...i/driver/unix/aix/perfstat/PerfstatProcessJNA.java 0.00% 23 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master    #3582      +/-   ##
============================================
- Coverage     79.99%   79.77%   -0.23%     
- Complexity     3869     4227     +358     
============================================
  Files           709      709              
  Lines         24207    24220      +13     
  Branches       4047     4051       +4     
============================================
- Hits          19364    19321      -43     
- Misses         2690     2748      +58     
+ Partials       2153     2151       -2     
Flag Coverage Δ
freebsd 33.49% <0.00%> (-0.02%) ⬇️
linux 37.65% <0.00%> (+0.02%) ⬆️
macos 38.43% <0.00%> (-0.07%) ⬇️
openbsd 32.66% <0.00%> (-0.02%) ⬇️
solaris 34.17% <0.00%> (-0.01%) ⬇️
windows 45.37% <0.00%> (-0.04%) ⬇️

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.

The truncation retry re-counted the processes to size the next attempt,
and assigned that straight back to the loop variable. A re-count that
returns zero or an error then failed the loop guard, so the method fell
out and returned an empty array -- discarding the full buffer of entries
it had just read successfully.

That is worse than the behavior this PR set out to fix: a list that may be
missing its tail became no list at all, on a path reachable whenever
perfstat transiently fails between two calls.

Hold the re-count in a local and only retry when it is positive.
Otherwise fall through and map the buffer already in hand, which is the
same result the code produced before the retry existed.

Both twins.
The slack absorbs processes spawned between the count and fill calls, so
what it needs to track is the system's spawn rate, not its process count.
Those correlate weakly, and the two cases pull opposite ways.

A small, busy host churns faster than any proportional pad would cover:
at 200 processes a 10% pad is 20 entries, fewer than the fixed 64, and
this is the shape of host that produced the original failure. A large host
makes that same fixed 64 thin — 1.3% headroom at 5000 processes — where a
proportional term is the one that helps.

So take whichever is larger: count/10 or 64. Extracted as paddedSize() in
both twins with the reasoning recorded, since neither half is redundant.

Cost is immaterial either way. perfstat_process_t is 288 bytes, so the
proportional term adds 144 KB at 5000 processes, and the retry loop is
what provides correctness — the pad only decides how often that retry has
to run.
@dbwiddis
dbwiddis merged commit b2cdb43 into oshi:master Aug 4, 2026
16 checks passed
@dbwiddis
dbwiddis deleted the aix-perfstat-truncation branch August 4, 2026 23:58
dbwiddis added a commit that referenced this pull request Aug 5, 2026
CodeQL java/constant-comparison, findings #635 and #636: the
attempt <= MAX_BUFFER_RETRIES term in the for guard is always true. Every
path out of the loop body either breaks or returns except the retry
continue, and that continue requires attempt < MAX_BUFFER_RETRIES, so
after the increment the guard can never fail.

Remove the redundant term rather than the inner check. Doing it the other
way round -- deleting the inner test on the grounds that the guard already
bounds the loop -- would reintroduce the defect fixed in #3582: on the
final attempt the code would continue, the guard would end the loop, and
the empty return would discard a buffer that was read successfully. A
comment at each site records that, since a bounded loop whose guard shows
no bound invites exactly that tidy-up.

Behavior is unchanged: an always-true conjunct is removed, and the loop is
still bounded by the retry check.
dbwiddis added a commit that referenced this pull request Aug 12, 2026
AIX's perfstat_process count-then-fill is a documented, load-dependent
race (#3582) where a bounded retry reduces but cannot fully eliminate a
miss on the current process under heavy process churn on a shared host;
that miss degrades to CurrentProcessStub's zero defaults (#3583) rather
than crashing. OshiMetricsTest's process.thread.count/memory.virtual/
uptime assertions didn't account for that degraded-but-valid case,
unlike NativeComparisonTest which already tolerates the same class of
AIX transient read miss.

Extends the existing BSD zero-tolerance carve-out (structural, not a
race) to also cover AIX for these three assertions.
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