Skip to content

Add PerfCounterQueryFFM for multi-counter PDH queries with WMI fallback - #3167

Merged
dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:migrate-perfcounter-query
Apr 17, 2026
Merged

dbwiddis merged 3 commits into
oshi:masterfrom
dbwiddis:migrate-perfcounter-query

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Apr 17, 2026 •

Copy link
Copy Markdown
Member

Adds FFM-based infrastructure for querying PDH performance counters, paralleling the JNA PerfCounterQuery.

Changes

PerfDataUtilFFM

  • Add queryCounters(Class<T>, String) method that opens a single PDH query, adds all counters from PdhCounterProperty enum constants, collects once, and returns an EnumMap<T, Long>
  • Remove single-counter queryCounter() method (now dead code)
  • Extract VALUE_OFFSET constant and shared helpers (counterPath, addEnglishCounter, readCounterValue)

PerfCounterQueryFFM (new)

  • queryValues — PDH first with failure caching, WMI fallback
  • queryValuesFromPDH — delegates to PerfDataUtilFFM.queryCounters
  • queryValuesFromWMI — uses WmiQueryHandlerFFM with IWbemClassObjectFFM.getLong to read enum property values

ProcessInformationFFM (new)

  • FFM equivalent of ProcessInformationJNA, routes handle count query through PerfCounterQueryFFM

WindowsFileSystemFFM

  • Updated to use ProcessInformationFFM.queryHandles() instead of direct PerfDataUtilFFM.queryCounter(), exercising the full PDH/WMI fallback path

Summary by CodeRabbit

  • New Features

    • Added multi-counter Windows performance querying with automatic WMI fallback and an aggregated handle-count metric for total processes.
  • Refactor

    • Per-counter failures are isolated and logged so partial results are returned instead of aborting entire queries.
  • Bug Fixes

    • File-descriptor handling now defaults to 0 when handle metrics are unavailable, avoiding erroneous negative values.
  • Chores

    • Updated changelog for the release.

Add queryCounters method to PerfDataUtilFFM that opens one PDH query,
adds all counters from PdhCounterProperty enum constants, collects
once, and returns an EnumMap.

Add PerfCounterQueryFFM paralleling PerfCounterQuery with PDH-first
and WMI-fallback pattern using failure caching.
Add ProcessInformationFFM driver class paralleling ProcessInformationJNA.
Update WindowsFileSystemFFM to use ProcessInformationFFM.queryHandles()
instead of direct PerfDataUtilFFM.queryCounter() call, exercising the
full PDH-first/WMI-fallback path for testing.
@coderabbitai

coderabbitai Bot commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: dfae1168-170c-47a8-b90c-409b02b0dab0

📥 Commits

Reviewing files that changed from the base of the PR and between 908cb69 and fc2e1e5.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
  • oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterQuery.java
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterQuery.java
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).

Applied to files:

  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
🔇 Additional comments (2)
oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java (2)

44-45: LGTM on the helper extraction and lifecycle.

VALUE_OFFSET factoring, the counterPath/addEnglishCounter/readCounterValue helpers, and the try-with-arena + inner try/finally around PdhCloseQuery are clean. The early-return on empty counterHandles avoids an unnecessary PdhCollectQueryData, and per-counter try/catch blocks give the documented per-counter resilience without aborting the whole query.

Based on learnings from PR #3014 (PdhUtilFFM.java:87-89): the throws Throwable on addEnglishCounter / readCounterValue is the expected compiler artifact of MethodHandle.invokeExact, and the outer catch (Throwable t) correctly covers the inner finally that calls PdhCloseQuery, so there's no exception-masking concern.

Also applies to: 108-128


53-93: The partial-map concern is not supported by the codebase.

The existing consumer of queryCounters result—WindowsFileSystem.getOpenFileDescriptors()—safely handles missing keys using .getOrDefault(HandleCountProperty.HANDLECOUNT, 0L). The javadoc contract ("may contain a subset of constants if individual counters fail") is clearly documented and correctly honored. No NPE risk exists, and no changes are required.


📝 Walkthrough

Walkthrough

Adds a PDH-first, WMI-fallback perf counter query layer (PerfCounterQueryFFM), refactors PerfDataUtilFFM to perform batched multi-counter PDH queries, adds ProcessInformationFFM to fetch the _Total handle count, and updates WindowsFileSystemFFM to use the new handle-query path.

Changes

Cohort / File(s) Summary
Perf Counter Query Infrastructure
oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfCounterQueryFFM.java, oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
Added PerfCounterQueryFFM with PDH-first + PDH-failure cache and WMI fallback; refactored PerfDataUtilFFM to queryCounters(...) that batches multiple PDH counters and returns an EnumMap of results, with per-counter error handling.
Process Information Utility
oshi-core-java25/src/main/java/oshi/driver/windows/perfmon/ProcessInformationFFM.java
New @ThreadSafe final class exposing queryHandles() that calls PerfCounterQueryFFM.queryValues(...) for PROCESS and the _Total selector, returning a Map<HandleCountProperty,Long>.
FileSystem Integration
oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.java
getOpenFileDescriptors() now uses ProcessInformationFFM.queryHandles().getOrDefault(HandleCountProperty.HANDLECOUNT, 0L) instead of the previous single-counter PDH helper, defaulting to 0L when absent.
Changelog
CHANGELOG.md
Added entry documenting the multi-counter PDH queries with WMI fallback and related FFM changes.

Sequence Diagram

sequenceDiagram
    participant Client as WindowsFileSystemFFM
    participant PCQ as PerfCounterQueryFFM
    participant PDU as PerfDataUtilFFM
    participant WMI as WmiQueryHandlerFFM

    Client->>PCQ: queryValues(HandleCountProperty, "PROCESS", "WIN32_PERFPROC_PROCESS_WHERE_NAME_TOTAL")
    alt perfObject not cached as PDH-failed
        PCQ->>PDU: queryValuesFromPDH(HandleCountProperty, "PROCESS")
        PDU-->>PCQ: Map<HandleCountProperty,Long> (may be empty)
        alt PDH returned non-empty
            PCQ-->>Client: Map from PDH
        else PDH empty
            PCQ->>PCQ: cache perfObject as PDH-failed
            PCQ->>WMI: queryWMI("WIN32_PERFPROC_PROCESS_WHERE_NAME_TOTAL")
            WMI-->>PCQ: IWbemClassObject rows
            PCQ-->>Client: Map from WMI (first row merged)
        end
    else perfObject cached as PDH-failed
        PCQ->>WMI: queryWMI("WIN32_PERFPROC_PROCESS_WHERE_NAME_TOTAL")
        WMI-->>PCQ: IWbemClassObject rows
        PCQ-->>Client: Map from WMI (first row merged)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I hopped through counters, PDH first on the trail,

When PDH trips, WMI ships the needed detail.
Enums gathered, totals snug in a map,
Handles counted tidy—no more mishap.
Hop, nibble, code: a rabbit's small clap!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately and concisely describes the main change: adding PerfCounterQueryFFM, a new FFM-based utility for multi-counter PDH queries with WMI fallback. This is the primary objective of the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
✨ Simplify code
  • Create PR with simplified code

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 and usage tips.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java (1)

51-90: ⚠️ Potential issue | 🟡 Minor

All-or-nothing failure semantics may discard partial results.

If addEnglishCounter or readCounterValue throws for any single counter in the enum, the entire EnumMap is discarded and an empty map is returned, triggering a full WMI fallback in PerfCounterQueryFFM.queryValues and permanently disabling PDH for this perfObject via FAILED_QUERY_CACHE. For enums with several counters where only one is problematic (e.g., localization/path resolution issue on one counter), this means losing all PDH data forever for the object.

This mirrors the JNA PerfCounterQuery behavior, so it's likely intentional, but worth confirming given that FAILED_QUERY_CACHE is never cleared.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java`
around lines 51 - 90, The current queryCounters method discards all results if a
single counter fails, causing permanent PDH disable via FAILED_QUERY_CACHE;
change the logic to handle failures per-counter instead: when calling
addEnglishCounter and readCounterValue inside queryCounters, wrap each call in
its own try/catch so a failing counter is skipped (log debug) but other counters
are still collected and placed into valueMap; after collecting, return the
partial valueMap if non-empty and only treat the overall query as failed (and
allow the caller to record FAILED_QUERY_CACHE) when no counters succeeded.
Reference queryCounters, addEnglishCounter, readCounterValue, and
FAILED_QUERY_CACHE to locate and update the code paths.
🧹 Nitpick comments (2)
oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java (1)

71-77: Single PdhCollectQueryData call — fine for raw counters only.

A single PdhCollectQueryData is sufficient for raw/instantaneous counters (like Handle Count), but rate-type counters (e.g., % Processor Time, per-second rates) require two samples separated by a time interval to produce non-zero values. Future callers passing rate-counter enums will silently receive 0 without an obvious indication. Consider documenting this limitation in the Javadoc, or mention in commit history that this utility is intended for raw counters only.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java`
around lines 71 - 77, PerfDataUtilFFM calls PdhCollectQueryData only once before
reading counters, which yields valid data for raw/instantaneous counters but
returns zeros for rate-type counters; update the Javadoc for class
PerfDataUtilFFM (or the relevant public factory/method) to document that this
utility is intended for raw counters only and that rate/per-second counters
require two samples separated by an interval (or alternatively implement a
second PdhCollectQueryData sample and delay between samples before calling
readCounterValue); reference the PdhCollectQueryData invocation,
readCounterValue, and checkSuccess so reviewers can locate where to document or
add the extra sample.
oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfCounterQueryFFM.java (1)

48-59: Permanent PDH disablement on transient failure.

FAILED_QUERY_CACHE is never cleared for the process lifetime, so a single transient PDH failure (e.g., service not yet available during startup) permanently routes all subsequent queries for that perfObject through WMI, which is significantly more expensive. This matches the JNA PerfCounterQuery behavior, so it's presumably intentional, but flagging in case a retry policy (e.g., time-based expiration) was under consideration.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfCounterQueryFFM.java`
around lines 48 - 59, The current logic in queryValues permanently adds
perfObject to FAILED_QUERY_CACHE on any PDH failure, causing all future calls to
queryValues to skip PDH; change this to use a retry/expiration policy instead:
replace the boolean set-in-cache behavior of FAILED_QUERY_CACHE with a
time-based entry (or store timestamps) and update queryValues to re-attempt
queryValuesFromPDH when the cached failure has expired; adjust the code paths
around FAILED_QUERY_CACHE, queryValuesFromPDH, and queryValuesFromWMI to consult
the timestamped cache and refresh or remove entries after a configurable timeout
so transient PDH failures don’t permanently disable PDH queries.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In
`@oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java`:
- Around line 51-90: The current queryCounters method discards all results if a
single counter fails, causing permanent PDH disable via FAILED_QUERY_CACHE;
change the logic to handle failures per-counter instead: when calling
addEnglishCounter and readCounterValue inside queryCounters, wrap each call in
its own try/catch so a failing counter is skipped (log debug) but other counters
are still collected and placed into valueMap; after collecting, return the
partial valueMap if non-empty and only treat the overall query as failed (and
allow the caller to record FAILED_QUERY_CACHE) when no counters succeeded.
Reference queryCounters, addEnglishCounter, readCounterValue, and
FAILED_QUERY_CACHE to locate and update the code paths.

---

Nitpick comments:
In
`@oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfCounterQueryFFM.java`:
- Around line 48-59: The current logic in queryValues permanently adds
perfObject to FAILED_QUERY_CACHE on any PDH failure, causing all future calls to
queryValues to skip PDH; change this to use a retry/expiration policy instead:
replace the boolean set-in-cache behavior of FAILED_QUERY_CACHE with a
time-based entry (or store timestamps) and update queryValues to re-attempt
queryValuesFromPDH when the cached failure has expired; adjust the code paths
around FAILED_QUERY_CACHE, queryValuesFromPDH, and queryValuesFromWMI to consult
the timestamped cache and refresh or remove entries after a configurable timeout
so transient PDH failures don’t permanently disable PDH queries.

In
`@oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java`:
- Around line 71-77: PerfDataUtilFFM calls PdhCollectQueryData only once before
reading counters, which yields valid data for raw/instantaneous counters but
returns zeros for rate-type counters; update the Javadoc for class
PerfDataUtilFFM (or the relevant public factory/method) to document that this
utility is intended for raw counters only and that rate/per-second counters
require two samples separated by an interval (or alternatively implement a
second PdhCollectQueryData sample and delay between samples before calling
readCounterValue); reference the PdhCollectQueryData invocation,
readCounterValue, and checkSuccess so reviewers can locate where to document or
add the extra sample.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f8282e65-28eb-41c4-b769-0f32d621b523

📥 Commits

Reviewing files that changed from the base of the PR and between 7228200 and e8175aa.

📒 Files selected for processing (4)
  • oshi-core-java25/src/main/java/oshi/driver/windows/perfmon/ProcessInformationFFM.java
  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfCounterQueryFFM.java
  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/driver/windows/perfmon/ProcessInformationFFM.java
  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfCounterQueryFFM.java
📚 Learning: 2026-04-10T22:44:36.786Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3136
File: oshi-core-java25/src/main/java/oshi/software/os/linux/LinuxOperatingSystemFFM.java:46-53
Timestamp: 2026-04-10T22:44:36.786Z
Learning: In OSHI's `AuxvFFM.queryAuxv()` (oshi-core-java25/src/main/java/oshi/driver/linux/proc/AuxvFFM.java), the do-while loop is safe even when `/proc/self/auxv` cannot be read: `FileUtil.readAllBytesAsBuffer` returns an empty ByteBuffer on failure, and `FileUtil.readLongFromBuffer`/`readIntFromBuffer` return 0L when reading past the buffer limit. This 0L equals AT_NULL, causing the loop to exit immediately with an empty map, which triggers the `getconf`/hardcoded-default fallback in callers like `LinuxOperatingSystemFFM`. Do not flag this do-while loop or the static initializer that calls `AuxvFFM.queryAuxv()` as unsafe.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.java
📚 Learning: 2026-04-08T00:58:10.736Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3125
File: oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java:131-133
Timestamp: 2026-04-08T00:58:10.736Z
Learning: In `oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceJNA.java` and `oshi-core-java25/src/main/java/oshi/hardware/platform/windows/WindowsPowerSourceFFM.java`, the `getPowerSources()` method intentionally returns a singleton list wrapping a single `getPowerSource("System Battery")` call, and the enumeration loop short-circuits after the first eligible battery pack. This matches the longstanding JNA behavior and is not a bug. A broader refactor to support zero-or-more batteries across both implementations is planned for a later date. Do not flag this as an issue.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.java
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).

Applied to files:

  • oshi-core-java25/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.java
  • oshi-core-java25/src/main/java/oshi/driver/windows/perfmon/ProcessInformationFFM.java
  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfCounterQueryFFM.java
🔇 Additional comments (2)
oshi-core-java25/src/main/java/oshi/driver/windows/perfmon/ProcessInformationFFM.java (1)

20-33: LGTM!

Clean, minimal FFM wrapper that mirrors ProcessInformation (JNA). Thread-safety is inherited from PerfCounterQueryFFM.

oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfCounterQueryFFM.java (1)

88-104: LGTM on WMI fallback shape.

Using rows.getFirst() to return a single-row result is appropriate for _Total-style selectors. For callers passing WHERE clauses that legitimately return multiple instance rows, only the first would be retained — not a concern for the current HandleCountProperty use case, but worth remembering when adding multi-instance enums in the future.

@codecov

codecov Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 57.14286% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.13%. Comparing base (7228200) to head (fc2e1e5).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...shi/util/platform/windows/PerfCounterQueryFFM.java 25.00% 13 Missing and 2 partials ⚠️
...va/oshi/util/platform/windows/PerfDataUtilFFM.java 74.28% 7 Missing and 2 partials ⚠️
...a/oshi/util/platform/windows/PerfCounterQuery.java 50.00% 1 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3167      +/-   ##
==========================================
+ Coverage   57.97%   58.13%   +0.16%     
==========================================
  Files         324      326       +2     
  Lines       17376    17417      +41     
  Branches     3066     3072       +6     
==========================================
+ Hits        10074    10126      +52     
+ Misses       5825     5804      -21     
- Partials     1477     1487      +10     
Flag Coverage Δ
linux 26.56% <0.00%> (+0.16%) ⬆️
macos 29.76% <0.00%> (-0.01%) ⬇️
windows 32.12% <57.14%> (+0.07%) ⬆️

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

☔ View full report in Codecov by Sentry.
📢 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.

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

🧹 Nitpick comments (2)
oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterQuery.java (1)

94-109: Per-counter resilience change looks good.

Skipping counters that fail to register (instead of aborting the entire PDH query and tripping FAILED_QUERY_CACHE) correctly mirrors the behavior in PerfDataUtilFFM.queryCounters and matches the PR's stated intent. The !counterMap.isEmpty() guard before updateQuery() avoids a pointless PDH collect when nothing was added.

Optional nit: the read loop could iterate counterMap.entrySet() to avoid the extra counterMap.get(prop) lookups — trivial, take it or leave it.

♻️ Optional diff
-            if (!counterMap.isEmpty() && 0 < pdhQueryHandler.updateQuery()) {
-                for (T prop : counterMap.keySet()) {
-                    valueMap.put(prop, pdhQueryHandler.queryCounter(counterMap.get(prop)));
-                }
-            }
+            if (!counterMap.isEmpty() && 0 < pdhQueryHandler.updateQuery()) {
+                for (Map.Entry<T, PerfCounter> entry : counterMap.entrySet()) {
+                    valueMap.put(entry.getKey(), pdhQueryHandler.queryCounter(entry.getValue()));
+                }
+            }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterQuery.java`
around lines 94 - 109, The read loop in PerfCounterQuery currently iterates over
counterMap.keySet() and calls counterMap.get(prop) for each prop; change it to
iterate over counterMap.entrySet() so you can call
pdhQueryHandler.queryCounter(entry.getValue()) and put the result into valueMap
using entry.getKey(), eliminating the extra map lookup and improving efficiency.
oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java (1)

107-115: Consider delegating to the existing counter-path builder.

counterPath duplicates the \object(instance)\counter formatting that already lives in PerfDataUtil.createCounter (non-FFM) / PerfCounter.getCounterPath(). Since PdhCounterProperty is shared with the JNA path, exposing a small static helper there (or reusing PerfCounter#getCounterPath) would keep path construction in one place and avoid drift if escaping rules ever change (e.g., instance names containing parentheses or backslashes). Non-blocking.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java`
around lines 107 - 115, The counterPath method duplicates counter path
formatting; refactor to reuse the canonical builder: call
PerfCounter.getCounterPath(object, instance, counter) if accessible, or add a
small static helper (e.g., PdhCounterProperty.buildCounterPath(String, String,
String)) and delegate to it from PerfDataUtilFFM.counterPath to centralize
escaping/formatting logic and avoid duplicate implementations; update
imports/usages accordingly so only the single helper constructs paths.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In
`@oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java`:
- Around line 107-115: The counterPath method duplicates counter path
formatting; refactor to reuse the canonical builder: call
PerfCounter.getCounterPath(object, instance, counter) if accessible, or add a
small static helper (e.g., PdhCounterProperty.buildCounterPath(String, String,
String)) and delegate to it from PerfDataUtilFFM.counterPath to centralize
escaping/formatting logic and avoid duplicate implementations; update
imports/usages accordingly so only the single helper constructs paths.

In `@oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterQuery.java`:
- Around line 94-109: The read loop in PerfCounterQuery currently iterates over
counterMap.keySet() and calls counterMap.get(prop) for each prop; change it to
iterate over counterMap.entrySet() so you can call
pdhQueryHandler.queryCounter(entry.getValue()) and put the result into valueMap
using entry.getKey(), eliminating the extra map lookup and improving efficiency.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a75b9437-3cb9-4251-9c6b-937cab0381b1

📥 Commits

Reviewing files that changed from the base of the PR and between e8175aa and 02bfe69.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
  • oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterQuery.java
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.

Applied to files:

  • oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterQuery.java
  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).

Applied to files:

  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
🔇 Additional comments (1)
oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java (1)

60-105: Multi-counter query refactor looks correct.

Lifetime of query is handled properly: the handle is only extracted after PdhOpenQuery succeeds, and the finally closes it on any internal throw; if PdhOpenQuery itself fails, checkSuccess throws before the inner try, so there is no handle to leak. Per-counter try/catch around addEnglishCounter and readCounterValue ensures one bad counter won't abort the batch, consistent with the non-FFM path in PerfCounterQuery. Early return on empty counterHandles avoids a wasted PdhCollectQueryData call.

Nit: the outer catch (Throwable t) returns new EnumMap<>(propertyEnum) rather than the (necessarily empty at that point) valueMap. It's equivalent, but reusing valueMap would drop one allocation and be clearer that no partial results are ever surfaced from this path.

Per-counter throws Throwable propagation here is consistent with the documented FFM wrapper convention (compiler artifact of MethodHandle.invokeExact), so no exception-masking concern around the finally. Based on learnings from PdhUtilFFM.java:87-89 (PR #3014).

@dbwiddis
dbwiddis force-pushed the migrate-perfcounter-query branch from 02bfe69 to 908cb69 Compare April 17, 2026 18:26

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

🧹 Nitpick comments (2)
oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java (2)

55-105: Resilient multi-counter PDH query looks correct.

The add → collect → read flow is right, and per-counter try/catch(Throwable) around addEnglishCounter / readCounterValue correctly isolates a single bad counter from aborting the whole batch. The early-return when counterHandles.isEmpty() still falls through the inner finally, so PdhCloseQuery runs on every path after PdhOpenQuery succeeds. Catching Throwable here is the expected pattern for FFM native wrappers.

One minor contract note worth surfacing in the Javadoc: the returned EnumMap may contain a strict subset of the enum constants when some counters fail to add or read, so callers must tolerate missing keys (PerfCounterQueryFFM already does via its WMI fallback). The current Javadoc only mentions the all-or-nothing empty-map case.

Based on learnings from PR 3014: throws Throwable on PDH/FFM wrapper methods is a compiler artifact of MethodHandle.invokeExact and the outer catch (Throwable t) + finally block is the idiomatic safety net in this codebase.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java`
around lines 55 - 105, The method queryCounters currently returns an empty
EnumMap only when no counters were added, but its Javadoc claims an
all-or-nothing empty result; update the Javadoc for queryCounters to state that
the returned EnumMap may contain a strict subset of the enum constants when
individual counters fail to add or read (due to addEnglishCounter or
readCounterValue throwing), and callers must tolerate missing keys; also mention
that PdhOpenQuery/PdhCloseQuery are still guaranteed to pair because of the
inner finally and the outer catch(Throwable) pattern used for FFM PDH wrappers.

107-115: counterPath does not escape parentheses in instance names.

If instance ever contains ( or ), the produced PDH path (\Object(inst)\Counter) will be malformed and PdhAddEnglishCounter will fail (handled gracefully by the caller, but silently skipped). This mirrors the existing JNA-side helper, so likely fine for the current set of PdhCounterProperty consumers (Process, etc. don't produce paren-bearing instances), but worth keeping in mind if/when this utility is used for counters with arbitrary instance names (e.g., process names can legitimately contain parens). No action required now.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java`
around lines 107 - 115, The counterPath method constructs PDH paths but doesn't
escape parentheses in the instance name, which can produce malformed paths for
instance values containing '(' or ')'; update the counterPath(String object,
String instance, String counter) implementation to sanitize the instance by
replacing '(' with "\\(" and ')' with "\\)" (handling null instance as before)
before appending, so the produced path "\\Object(inst)\\Counter" becomes valid
for instances containing parentheses and remains compatible with
PdhAddEnglishCounter and existing PdhCounterProperty use.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In
`@oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java`:
- Around line 55-105: The method queryCounters currently returns an empty
EnumMap only when no counters were added, but its Javadoc claims an
all-or-nothing empty result; update the Javadoc for queryCounters to state that
the returned EnumMap may contain a strict subset of the enum constants when
individual counters fail to add or read (due to addEnglishCounter or
readCounterValue throwing), and callers must tolerate missing keys; also mention
that PdhOpenQuery/PdhCloseQuery are still guaranteed to pair because of the
inner finally and the outer catch(Throwable) pattern used for FFM PDH wrappers.
- Around line 107-115: The counterPath method constructs PDH paths but doesn't
escape parentheses in the instance name, which can produce malformed paths for
instance values containing '(' or ')'; update the counterPath(String object,
String instance, String counter) implementation to sanitize the instance by
replacing '(' with "\\(" and ')' with "\\)" (handling null instance as before)
before appending, so the produced path "\\Object(inst)\\Counter" becomes valid
for instances containing parentheses and remains compatible with
PdhAddEnglishCounter and existing PdhCounterProperty use.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 783ff07a-67d9-4ec0-9c19-034662101a97

📥 Commits

Reviewing files that changed from the base of the PR and between 02bfe69 and 908cb69.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
  • oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterQuery.java
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-core/src/main/java/oshi/util/platform/windows/PerfCounterQuery.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.
📚 Learning: 2026-03-29T20:03:00.830Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3014
File: oshi-core-java25/src/main/java/oshi/util/platform/windows/PdhUtilFFM.java:87-89
Timestamp: 2026-03-29T20:03:00.830Z
Learning: In the OSHI FFM codebase (oshi-core-java25), all PDH/Kernel32/COM wrapper methods in classes like PdhFFM, Kernel32FFM, etc. declare `throws Throwable` solely as a compiler artifact of `MethodHandle.invokeExact`. They are native calls and do not throw Java checked exceptions in practice. The enclosing `getOpenFileDescriptors()` method in PdhUtilFFM already has an outer `catch (Throwable t)` that covers the entire method body including any `finally` blocks, so no exception-masking concern exists for cleanup calls like `PdhCloseQuery` in `finally`.

Applied to files:

  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
📚 Learning: 2026-04-03T02:07:47.621Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3110
File: oshi-core-java25/src/main/java/oshi/hardware/platform/mac/MacHWDiskStoreFFM.java:119-121
Timestamp: 2026-04-03T02:07:47.621Z
Learning: In OSHI’s Java FFM/API implementation classes (e.g., *FFM.java) that implement/override `updateAttributes()`, preserve the intentional failure-handling pattern: catch `Throwable` and return `false` without logging. `updateAttributes()` is a public API whose contract is to signal failure via the boolean return value, and callers rely on that return value (so emitting logs from this path is not desired and should not be introduced during review unless the method contract changes).

Applied to files:

  • oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java
🔇 Additional comments (2)
oshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.java (2)

44-45: LGTM — VALUE_OFFSET extraction.

Hoisting the nested groupElement byte-offset lookup into a static final avoids recomputing it on every readCounterValue call.


117-127: Helpers are clean and correctly scoped.

addEnglishCounter returns the dereferenced counter handle and readCounterValue uses the precomputed VALUE_OFFSET against a fresh PDH_FMT_COUNTERVALUE_LAYOUT allocation in the confined arena. Both propagate Throwable up to the per-counter handlers in queryCounters, which is the correct split of responsibilities.

Skip failing counters instead of aborting the entire query in both
JNA PerfCounterQuery.queryValuesFromPDH and FFM PerfDataUtilFFM.
queryCounters. A single bad counter no longer causes an empty result
that permanently disables PDH via FAILED_QUERY_CACHE.

Document that PerfDataUtilFFM uses a single PdhCollectQueryData call
for raw counters; OSHI computes rates in Java rather than using PDH
formatted rate counters.
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