Skip to content

Filter WMI handle count query to _Total instance - #3166

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:fix-handle-count-wmi-filter
Apr 17, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:fix-handle-count-wmi-filter

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Apr 17, 2026 •

Copy link
Copy Markdown
Member

The queryHandles() WMI fallback was querying all processes from Win32_PerfRawData_PerfProc_Process without a WHERE clause, returning every process row when only the _Total instance is needed. This adds a WHERE Name="_Total" filter to match the PDH instance filter already defined in HandleCountProperty.

Changes

  • PerfmonConstants: Added WIN32_PERFPROC_PROCESS_WHERE_NAME_TOTAL constant.
  • ProcessInformationJNA.queryHandles(): Use filtered WMI class instead of unfiltered WIN32_PERFPROC_PROCESS.
  • PerfmonDriversTest.testQueryHandles(): Updated WMI test to use the filtered class.

Summary by CodeRabbit

  • Bug Fixes
    • Improved Windows handle-count reporting so the system now returns a single, accurate aggregate total for open handles.
  • Tests
    • Updated Windows performance-counter tests to validate the consolidated handle-count results.

@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: 2ed4156d-2efc-4bd9-977e-46b1e8b01138

📥 Commits

Reviewing files that changed from the base of the PR and between 4175568 and 529f7b3.

📒 Files selected for processing (5)
  • oshi-common/src/main/java/oshi/driver/common/windows/perfmon/PerfmonConstants.java
  • oshi-common/src/main/java/oshi/driver/common/windows/perfmon/ProcessInformation.java
  • oshi-core/src/main/java/oshi/driver/windows/perfmon/ProcessInformationJNA.java
  • oshi-core/src/main/java/oshi/software/os/windows/WindowsFileSystem.java
  • oshi-core/src/test/java/oshi/driver/windows/perfmon/PerfmonDriversTest.java
✅ Files skipped from review due to trivial changes (1)
  • oshi-common/src/main/java/oshi/driver/common/windows/perfmon/PerfmonConstants.java
🚧 Files skipped from review as they are similar to previous changes (2)
  • oshi-core/src/test/java/oshi/driver/windows/perfmon/PerfmonDriversTest.java
  • oshi-core/src/main/java/oshi/driver/windows/perfmon/ProcessInformationJNA.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). (10)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, ubuntu-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Analyze (java)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
🧰 Additional context used
🧠 Learnings (4)
📚 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/software/os/windows/WindowsFileSystem.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/src/main/java/oshi/software/os/windows/WindowsFileSystem.java
📚 Learning: 2026-04-06T04:45:47.644Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3121
File: oshi-core/src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java:53-53
Timestamp: 2026-04-06T04:45:47.644Z
Learning: In the oshi/oshi project, only interfaces and classes in the root packages `oshi`, `oshi.hardware`, and `oshi.software.os` are considered the public API. Code in subpackages that represent specific implementations/platforms (e.g., `oshi.software.os.linux`, `oshi.hardware.platform.linux`, and similar subpackages) is implementation detail. When reviewing, do not treat changes to classes in these platform-specific subpackages as public API breaks (for example: making `LinuxOperatingSystem` abstract, narrowing constructor visibility, or adding/removing abstract methods should not be flagged as breaking public API).

Applied to files:

  • oshi-core/src/main/java/oshi/software/os/windows/WindowsFileSystem.java
📚 Learning: 2026-04-12T19:22:09.716Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3149
File: oshi-common/src/main/java/oshi/hardware/common/platform/mac/MacCentralProcessor.java:159-163
Timestamp: 2026-04-12T19:22:09.716Z
Learning: When reviewing OSHI hardware platform code that uses or implements `CentralProcessor`/`PhysicalProcessor.getEfficiency()`, remember the API’s counterintuitive semantics: a *higher* efficiency-class value indicates *greater performance* (lower efficiency). P-cores/“performance cores” should therefore have higher values (e.g., 1) than E-cores/“efficiency cores” (e.g., 0), as documented in the `CentralProcessor` Javadoc. Do not flag code as incorrect solely because ARM_P_CORES or Intel P-cores are assigned higher efficiency values.

Applied to files:

  • oshi-common/src/main/java/oshi/driver/common/windows/perfmon/ProcessInformation.java
🔇 Additional comments (2)
oshi-common/src/main/java/oshi/driver/common/windows/perfmon/ProcessInformation.java (1)

51-71: LGTM!

The refactor to PdhCounterProperty with a single HANDLECOUNT(TOTAL_INSTANCE, "Handle Count") entry correctly models a single-instance _Total query and matches the PdhCounterProperty contract (getInstance/getCounter). This aligns cleanly with the PR goal of filtering both the PDH and WMI paths to the _Total instance.

oshi-core/src/main/java/oshi/software/os/windows/WindowsFileSystem.java (1)

273-273: LGTM!

Nice simplification — since queryHandles() now returns the _Total aggregate directly, the previous list-sum/null-check logic is no longer needed. getOrDefault(..., 0L) preserves the safe fallback behavior when the query fails or the key is absent.


📝 Walkthrough

Walkthrough

Added a new PERFMON constant to target the "_Total" process instance and refactored handle-count collection to query that aggregate directly (method signature changed to return a single-value map). Tests and callers were updated to use the new constant and the new return shape.

Changes

Cohort / File(s) Summary
Perfmon constants
oshi-common/src/main/java/oshi/driver/common/windows/perfmon/PerfmonConstants.java
Added WIN32_PERFPROC_PROCESS_WHERE_NAME_TOTAL = WIN32_PERFPROC_PROCESS + " WHERE Name=\"_Total\"" to filter WMI queries for the _Total instance.
Handle-count API & query
oshi-core/src/main/java/oshi/driver/windows/perfmon/ProcessInformationJNA.java
Changed queryHandles() signature to return Map<HandleCountProperty, Long> and switched from wildcard instance queries to querying the _Total instance via PerfCounterQuery.queryValues(...). Returns Collections.emptyMap() when perfmon disabled.
HandleCountProperty enum
oshi-common/src/main/java/oshi/driver/common/windows/perfmon/ProcessInformation.java
Reworked HandleCountProperty to implement PdhCounterProperty (store instance + counter), removed separate NAME wildcard entry, added getInstance() and updated constructor to accept instance and counter.
Filesystem caller
oshi-core/src/main/java/oshi/software/os/windows/WindowsFileSystem.java
getOpenFileDescriptors() now reads aggregated handle count directly via queryHandles().getOrDefault(HANDLECOUNT, 0L) instead of summing a list.
Tests
oshi-core/src/test/java/oshi/driver/windows/perfmon/PerfmonDriversTest.java
Updated tests to use PerfCounterQuery.queryValuesFromPDH/FromWMI expecting a map of size HandleCountProperty.values().length and replaced WMI filter constant with _Total variant.

Sequence Diagram(s)

sequenceDiagram
  rect rgba(200,220,255,0.5)
    participant App as Client (WindowsFileSystem)
    participant PI as ProcessInformationJNA
    participant PC as PerfCounterQuery (PDH/WMI)
    participant CONST as PerfmonConstants
  end

  App->>PI: getOpenFileDescriptors()
  PI->>CONST: use WIN32_PERFPROC_PROCESS_WHERE_NAME_TOTAL
  PI->>PC: queryValues(counterDefs, WIN32_PERFPROC_PROCESS_WHERE_NAME_TOTAL)
  PC-->>PI: Map<HandleCountProperty, Long> (aggregate _Total)
  PI-->>App: value for HANDLECOUNT (or 0L)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I hopped through code with a carrot and quill,
Found _Total waiting on perfmon's hill.
No wildcard scramble, no list to comb,
One tidy number brings metrics home.
Hooray for constants — concise and still!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% 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 title clearly and accurately describes the main change: filtering the WMI handle count query to the _Total instance, which is the primary modification across 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.

@codecov

codecov Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.50000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 58.12%. Comparing base (16f6e7f) to head (529f7b3).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
.../driver/windows/perfmon/ProcessInformationJNA.java 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3166      +/-   ##
==========================================
+ Coverage   58.06%   58.12%   +0.06%     
==========================================
  Files         324      324              
  Lines       17382    17376       -6     
  Branches     3068     3066       -2     
==========================================
+ Hits        10092    10100       +8     
+ Misses       5804     5789      -15     
- Partials     1486     1487       +1     
Flag Coverage Δ
linux 26.57% <0.00%> (+0.02%) ⬆️
macos 29.84% <0.00%> (+0.13%) ⬆️
windows 32.10% <87.50%> (+0.06%) ⬆️

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.

Change HandleCountProperty from PdhCounterWildcardProperty to
PdhCounterProperty with a _Total instance. This switches queryHandles()
from PerfCounterWildcardQuery (which enumerates all process instances)
to PerfCounterQuery (which queries _Total directly), with WMI fallback
filtered to WHERE Name="_Total".

Simplify WindowsFileSystem.getOpenFileDescriptors() to read the single
value directly instead of iterating a list.
@dbwiddis
dbwiddis force-pushed the fix-handle-count-wmi-filter branch from 4175568 to 529f7b3 Compare April 17, 2026 08:46
@dbwiddis
dbwiddis merged commit 7228200 into oshi:master Apr 17, 2026
16 of 17 checks passed
@dbwiddis
dbwiddis deleted the fix-handle-count-wmi-filter branch April 17, 2026 08:58
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