Repository navigation
Add PerfCounterQueryFFM for multi-counter PDH queries with WMI fallback - #3167
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
✅ Files skipped from review due to trivial changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📜 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)
🧰 Additional context used🧠 Learnings (3)📓 Common learnings📚 Learning: 2026-03-29T20:03:00.830ZApplied to files:
📚 Learning: 2026-04-03T02:07:47.621ZApplied to files:
🔇 Additional comments (2)
📝 WalkthroughWalkthroughAdds a PDH-first, WMI-fallback perf counter query layer (PerfCounterQueryFFM), refactors PerfDataUtilFFM to perform batched multi-counter PDH queries, adds ProcessInformationFFM to fetch the Changes
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
✨ Simplify 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. Comment |
There was a problem hiding this comment.
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 | 🟡 MinorAll-or-nothing failure semantics may discard partial results.
If
addEnglishCounterorreadCounterValuethrows for any single counter in the enum, the entireEnumMapis discarded and an empty map is returned, triggering a full WMI fallback inPerfCounterQueryFFM.queryValuesand permanently disabling PDH for thisperfObjectviaFAILED_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
PerfCounterQuerybehavior, so it's likely intentional, but worth confirming given thatFAILED_QUERY_CACHEis 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: SinglePdhCollectQueryDatacall — fine for raw counters only.A single
PdhCollectQueryDatais sufficient for raw/instantaneous counters (likeHandle 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_CACHEis 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 thatperfObjectthrough WMI, which is significantly more expensive. This matches the JNAPerfCounterQuerybehavior, 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
📒 Files selected for processing (4)
oshi-core-java25/src/main/java/oshi/driver/windows/perfmon/ProcessInformationFFM.javaoshi-core-java25/src/main/java/oshi/software/os/windows/WindowsFileSystemFFM.javaoshi-core-java25/src/main/java/oshi/util/platform/windows/PerfCounterQueryFFM.javaoshi-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.javaoshi-core-java25/src/main/java/oshi/driver/windows/perfmon/ProcessInformationFFM.javaoshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.javaoshi-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.javaoshi-core-java25/src/main/java/oshi/driver/windows/perfmon/ProcessInformationFFM.javaoshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.javaoshi-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 fromPerfCounterQueryFFM.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 currentHandleCountPropertyuse case, but worth remembering when adding multi-instance enums in the future.
Codecov Report❌ Patch coverage is 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🧹 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 inPerfDataUtilFFM.queryCountersand matches the PR's stated intent. The!counterMap.isEmpty()guard beforeupdateQuery()avoids a pointless PDH collect when nothing was added.Optional nit: the read loop could iterate
counterMap.entrySet()to avoid the extracounterMap.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.
counterPathduplicates the\object(instance)\counterformatting that already lives inPerfDataUtil.createCounter(non-FFM) /PerfCounter.getCounterPath(). SincePdhCounterPropertyis shared with the JNA path, exposing a small static helper there (or reusingPerfCounter#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
📒 Files selected for processing (3)
CHANGELOG.mdoshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.javaoshi-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.javaoshi-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
queryis handled properly: the handle is only extracted afterPdhOpenQuerysucceeds, and thefinallycloses it on any internal throw; ifPdhOpenQueryitself fails,checkSuccessthrows before the innertry, so there is no handle to leak. Per-countertry/catcharoundaddEnglishCounterandreadCounterValueensures one bad counter won't abort the batch, consistent with the non-FFM path inPerfCounterQuery. Early return on emptycounterHandlesavoids a wastedPdhCollectQueryDatacall.Nit: the outer
catch (Throwable t)returnsnew EnumMap<>(propertyEnum)rather than the (necessarily empty at that point)valueMap. It's equivalent, but reusingvalueMapwould drop one allocation and be clearer that no partial results are ever surfaced from this path.Per-counter
throws Throwablepropagation here is consistent with the documented FFM wrapper convention (compiler artifact ofMethodHandle.invokeExact), so no exception-masking concern around thefinally. Based on learnings from PdhUtilFFM.java:87-89 (PR#3014).
02bfe69 to
908cb69
Compare
There was a problem hiding this comment.
🧹 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)aroundaddEnglishCounter/readCounterValuecorrectly isolates a single bad counter from aborting the whole batch. The early-return whencounterHandles.isEmpty()still falls through the innerfinally, soPdhCloseQueryruns on every path afterPdhOpenQuerysucceeds. CatchingThrowablehere is the expected pattern for FFM native wrappers.One minor contract note worth surfacing in the Javadoc: the returned
EnumMapmay contain a strict subset of the enum constants when some counters fail to add or read, so callers must tolerate missing keys (PerfCounterQueryFFMalready does via its WMI fallback). The current Javadoc only mentions the all-or-nothing empty-map case.Based on learnings from PR 3014:
throws Throwableon PDH/FFM wrapper methods is a compiler artifact ofMethodHandle.invokeExactand the outercatch (Throwable t)+finallyblock 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:counterPathdoes not escape parentheses in instance names.If
instanceever contains(or), the produced PDH path (\Object(inst)\Counter) will be malformed andPdhAddEnglishCounterwill fail (handled gracefully by the caller, but silently skipped). This mirrors the existing JNA-side helper, so likely fine for the current set ofPdhCounterPropertyconsumers (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
📒 Files selected for processing (3)
CHANGELOG.mdoshi-core-java25/src/main/java/oshi/util/platform/windows/PerfDataUtilFFM.javaoshi-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_OFFSETextraction.Hoisting the nested
groupElementbyte-offset lookup into astatic finalavoids recomputing it on everyreadCounterValuecall.
117-127: Helpers are clean and correctly scoped.
addEnglishCounterreturns the dereferenced counter handle andreadCounterValueuses the precomputedVALUE_OFFSETagainst a freshPDH_FMT_COUNTERVALUE_LAYOUTallocation in the confined arena. Both propagateThrowableup to the per-counter handlers inqueryCounters, 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.
908cb69 to
fc2e1e5
Compare
Adds FFM-based infrastructure for querying PDH performance counters, paralleling the JNA
PerfCounterQuery.Changes
PerfDataUtilFFMqueryCounters(Class<T>, String)method that opens a single PDH query, adds all counters fromPdhCounterPropertyenum constants, collects once, and returns anEnumMap<T, Long>queryCounter()method (now dead code)VALUE_OFFSETconstant and shared helpers (counterPath,addEnglishCounter,readCounterValue)PerfCounterQueryFFM(new)queryValues— PDH first with failure caching, WMI fallbackqueryValuesFromPDH— delegates toPerfDataUtilFFM.queryCountersqueryValuesFromWMI— usesWmiQueryHandlerFFMwithIWbemClassObjectFFM.getLongto read enum property valuesProcessInformationFFM(new)ProcessInformationJNA, routes handle count query throughPerfCounterQueryFFMWindowsFileSystemFFMProcessInformationFFM.queryHandles()instead of directPerfDataUtilFFM.queryCounter(), exercising the full PDH/WMI fallback pathSummary by CodeRabbit
New Features
Refactor
Bug Fixes
Chores