Skip to content

Issue #85: Free the native memory of WMI queries without waiting for the garbage collector - #86

Merged
NassimBtk merged 3 commits into
mainfrom
feature/issue-85-jna-native-memory
Nov 19, 2026
Merged

NassimBtk merged 3 commits into
mainfrom
feature/issue-85-jna-native-memory

Conversation

@NassimBtk

@NassimBtk NassimBtk commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #85

What changes

  • WmiCimTypeHandler.getPropertyValueFromWbemObject calls IWbemClassObject::Get (vtable 4) with three native buffers: the VARIANT, the CIM type and the property name. All three are freed by try-with-resources, after VariantClear. plFlavor is passed as NULL.
  • convertScalar converts the scalar values straight from the buffer: VT_EMPTY, VT_NULL, VT_BSTR, VT_BOOL, VT_UI1, VT_I2, VT_I4, VT_R4, VT_R8. It returns exactly what convert() returned through the JNA structure, including the same exceptions. Arrays, embedded objects and any other type return NOT_SCALAR, so they still go through the JNA VARIANT, built on the same buffer.
  • processWqlResult calls IEnumWbemClassObject::Next (vtable 4) with two native buffers that are reused for every record and freed on return.
  • Converters now take a VARIANT instead of a VARIANT.ByReference.

Results

Native blocks left to the garbage collector, for SELECT Name, ProcessId, ThreadCount, HandleCount, CreationDate FROM Win32_Process (534 rows): 151,372 before, 9 after. The 9 remaining blocks are allocated once per query (the WQL string, GetNames).

MetricsHub agent, side by side for 60 minutes. Both agents used the same configuration (3 WMI resources, 1-minute collect). The only difference was the WMI extension, built with wmi-java 1.0.07 or with this branch.

After 60 min 1.0.07 This branch
Process private memory 2,709 MB 488 MB
Heap committed / used 2,280 / 1,710 MB 180 / 73 MB
CPU time over the 60 min 434 s 42 s
GC time over the 60 min 12.2 s 0.1 s
G1 concurrent cycles over the 60 min about 22 none (about 3, all during startup)
JNA native blocks waiting for the GC (Memory$MemoryDisposer, live histogram) 2,330,586 1,949

Non-regression

Unit tests:

  • testConvertScalarReturnsWhatConvertReturns runs 22 VARIANT values (every handled VT, plus VT_I1, VT_UI2 and VT_I8, which must fall back) against 19 CIM types, including an array type and an unknown type. convertScalar must return the same value and class as the old path, or the same exception, or NOT_SCALAR.
  • testQueryLeavesNoNativeMemoryToTheGarbageCollector measures one query with no garbage collection running during it. It fails on 1.0.07 every time, with the default heap and with -Xmn8m.
  • testUnknownEmbeddedObjectPropertyIsNull: an unknown sub-property of an embedded object still gives null, and does not fail the query.

Each new test was run with its own fix reverted, and failed.

Differential test on real Windows hosts:

  • Corpus: 234 WQL queries, made of every WMI query in community-connectors (112) and enterprise-connectors (80), plus 42 generic queries (CIM types, arrays, references, __PATH, ASSOCIATORS OF, embedded objects). The $1 queries are resolved like the connector does, for example the WinStorageSpaces MSFT_StorageReliabilityCounter ones.
  • How it runs: each query runs with 1.0.07, then this branch, then 1.0.07 again, in the same JVM with two class loaders that share JNA. EXACT means every row is identical, values and Java types included. Columns that differ between the two 1.0.07 runs count as volatile (VOLATILE_OK): their values are not compared, only their types and the row count.
  • Hosts: 12 machines. The local Windows 11 workstation ran elevated. The 11 remote servers were reached through DCOM; morgan is an IBM Director host and dev-hv-01 is Hyper-V.
  • Result: no regression.
    • Identical results: 1,521 (1,124 EXACT, 397 VOLATILE_OK), over 90,590 rows, 14,252 array cells and 758 embedded-object cells.
    • Same error with both versions: 1,206. Most are a namespace or class that does not exist on that host.
    • Coverage: 190 of the 234 queries are identical on at least one host, across 15 of the 17 connectors (Director61NT, Director52NT and Director5NT on morgan). The other 44 need hardware we do not have: HP Insight root\hpq, Fujitsu root\svs and ServeRAID.
  • RPC errors: remote DCOM sessions break with 0x800706BF under load and stay broken for both versions. That gave 1,363 RPC results in the first pass. Two retry rounds in fresh JVMs, and then the $1 WinStorageSpaces queries run alone, brought this down to 89 untested results. All 89 are on 3 hosts that stopped resolving in DNS during the retries, and 73 of them are identical on other hosts.
  • The one non-identical result: 1.0.07 failed with RPC and this branch returned 1 row, on a host that could not be re-tested.

MetricsHub CLI (-t win --wmi, automatic detection, 2 collects, 1.0.07 → this branch → 1.0.07):

  • Local host: identical line by line once numbers are masked, in two campaigns, with no error.
  • Remote hosts (4 campaigns, 3 to 11 hosts each): the output varies between the two 1.0.07 runs themselves, because detection times out or fails with RPC. Pooled over all hosts and campaigns, no error kind appears with this branch that does not also appear with 1.0.07.

mvn verify (JDK 17): 83 tests, all pass.

🤖 Generated with Claude Code

…the garbage collector

Property values are read into a native VARIANT buffer freed right after the
conversion, instead of a JNA VARIANT structure that allocates a native block
for each pointer field of its union on every creation and read. Scalar values
are converted straight from the buffer, exactly as before; arrays, objects and
unexpected types still go through the JNA structure.

IEnumWbemClassObject::Next reuses two native buffers for all the records.

One Win32_Process query (534 rows) left 151,372 native blocks to the garbage
collector, and now leaves 9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@NassimBtk

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T10:31:30.179213Z e6de18f Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: fdafa89704

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Call VariantClear through a cached JNA Function instead of a library interface
whose method name breaks the naming rule, and remove an unused import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@NassimBtk

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 9f47429eb6

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@NassimBtk

Copy link
Copy Markdown
Contributor Author

Test report: memory gain and non-regression (2026-11-18/19)

Verdict: no regression found.

  • What was compared: 1,521 query runs over 12 real Windows machines, covering 90,590 rows and 14,252 array cells.
  • Identical values: in 1,124 runs, this branch returned exactly the same values and Java types as wmi-java 1.0.07.
  • Volatile columns: in the other 397 runs, the only columns that differed were ones that also change between two runs of 1.0.07, such as counters and timestamps.
  • Failed queries: every query that failed with one version failed with the same error with the other, except in one case where only 1.0.07 failed.
  • Agent, after 60 minutes: private memory went from 2,709 MB to 488 MB, and CPU time from 434 s to 42 s.

Host names are left out on purpose: the test machines are internal.

1. Root cause

The memory is not leaked: it piles up until the GC reclaims it.

  • Allocation: wmi-java 1.0.07 builds a JNA Variant.VARIANT for every WMI value it reads. Its union has 24 *ByReference fields, and JNA allocates a native Memory block for most of them, on every construction and on every read().
  • Per value: that comes to about 57 native blocks for each value read, counting the IEnumWbemClassObject::Next buffers.
  • Per query: 151,372 blocks for 534 rows of 5 properties.
  • Release: none of these blocks is freed explicitly. Each waits until the GC collects its Java Memory object, which then goes through com.sun.jna.internal.Cleaner.

These objects live long enough to be promoted to the old generation. G1 only reclaims them in a concurrent cycle, which happened about every two minutes on the test agent, so millions of native blocks wait between two cycles.

With no -Xmx, G1 has no reason to hurry, since the heap may grow to a quarter of RAM. The native memory, which the GC does not see, comes on top of the heap.

On the agent that showed the problem (5 GB), jcmd GC.class_histogram counted 8.1 million pending Cleaner$CleanerRef / Memory$MemoryDisposer pairs. That is about 1.4 GB of heap for these tracking objects alone.

Capping the heap on the customer's side would reduce the symptom without touching the cause. G1PeriodicGCInterval does not help when GCs already run all the time.

2. Gain measured on the MetricsHub agent

Two MetricsHub Community agents ran side by side for 60 minutes with the same configuration: 3 WMI resources, collected every minute. The only difference was the WMI extension, built with wmi-java 1.0.07 or with this branch.

After 60 min 1.0.07 This branch
Process private memory 2,709 MB 488 MB
Heap used / committed 1,710 / 2,280 MB 73 / 180 MB
CPU time over the 60 min 434 s 42 s
GC time over the 60 min 12.2 s 0.1 s
G1 concurrent cycles over the 60 min about 22 none (3 at startup)
JNA native blocks waiting for the GC (Memory$MemoryDisposer) 2,330,586 1,949

Private memory, sampled every 10 minutes:

Minute 0 10 20 30 40 50 60
1.0.07 (MB) 542 2,520 2,685 2,705 2,700 2,708 2,709
This branch (MB) 512 480 488 485 463 486 488

jstat's CGC column counts two pauses per concurrent cycle, so it shows 52 and 6 for the same period.

3. Unit tests

  • testConvertScalarReturnsWhatConvertReturns:
    • runs 22 VARIANT values against 19 CIM types, including an array type and an unknown type;
    • covers every handled VT, VT_R8 included;
    • each pair must give the same value and class as the old path, or the same exception, or NOT_SCALAR.
  • testQueryLeavesNoNativeMemoryToTheGarbageCollector: a full query must leave fewer than 20 blocks to the GC. It fails on 1.0.07 every time.
  • testUnknownEmbeddedObjectPropertyIsNull: an unknown sub-property of an embedded object is still null, and does not fail the query.

Each new test was run once with its own fix reverted, and failed. mvn verify (JDK 17) ran 83 tests, and all pass.

4. WMI differential test on real machines

Method

  1. Corpus: 234 WQL queries.
    • 112 from community-connectors and 80 from enterprise-connectors (17 connectors, main).
    • 42 generic queries: most CIM types, arrays, references, __PATH, ASSOCIATORS OF and embedded objects.
  2. Parameterized queries: $1 queries are resolved the way the connector does it, with the source query, escaping and up to 3 values. An example is the WinStorageSpaces MSFT_StorageReliabilityCounter queries.
  3. Order: each query runs with 1.0.07, then this branch, then 1.0.07 again, in the same JVM, with two class loaders that share JNA.
  4. Comparison:
    • EXACT: every row is identical, values and Java types included.
    • VOLATILE_OK: a column that changes between the two 1.0.07 runs is volatile. Its values are not compared; only its types and the row count must stay within the bounds of the two 1.0.07 runs.
  5. Retries:
    • a FAIL or FLAKY query is retried, up to 4 attempts in total;
    • every query hit by an RPC error is then rerun in a fresh JVM, in chunks of 12, then alone if needed.

Results per machine

Machine Identical Namespace absent Same error Not tested (RPC) Regressions Rows Array cells Embedded cells
Windows 11 workstation (elevated) 134 87 13 0 0 8,586 1,973 20
Server A (IBM Director) 166 38 30 0 0 6,032 1,096 21
Server B (Hyper-V) 164 72 6 0 0 48,722 4,137 546
Server C 152 76 6 0 0 4,696 1,013 41
Server D 122 95 17 0 0 4,817 810 12
Server E 121 93 20 0 0 2,827 789 12
Server F 119 105 10 0 0 3,608 1,131 12
Server G 118 96 20 0 0 2,757 758 12
Server H 117 84 17 16 0 3,335 678 16
Server I 111 115 8 0 0 2,004 682 38
Server J 103 80 17 34 0 1,837 556 12
Server K 94 84 17 39 0 1,369 629 16
Total 1,521 1,025 181 89 0 90,590 14,252 758

Notes on the columns:

  • Identical:
    • 1,124 EXACT and 397 VOLATILE_OK.
    • 106 of these results are empty in all three runs, so they prove nothing about value conversion.
    • Server B has 242 results instead of 234: its 3 disks give 3 $1 values to each reliability query.
  • Namespace absent: error 8004100e, the same with both versions.
    • Most come from a namespace that does not exist on that machine, such as root\hpq, root\svs or root\ibmsd.
    • 160 come from a namespace: Automatic query that no namespace matched.
  • Same error: WBEM_E_NOT_SUPPORTED, INVALID_CLASS, FAILED, CRITICAL_ERROR and WQL syntax errors, always identical between the two versions.
  • Embedded cells: sub-property cells of embedded objects, such as PerfData.BytesRead.

Coverage

  • 190 of the 234 queries are identical on at least one machine, and 183 of them returned at least one row.
    • That spans 15 of the 17 connectors.
    • Director61NT, Director52NT and Director5NT were covered on the IBM Director host.
  • The 44 queries never exercised need hardware we do not have:
    • HP Insight root\hpq (16);
    • Fujitsu ServerView root\svs (14);
    • ServeRAID or Director 5 classes that are absent (13);
    • Win32_NonExistentClass, which fails by design.
  • Java types compared:
    • scalars: String, Integer, Long, Boolean, OffsetDateTime, Duration, Byte, Short and Float;
    • lists: List<String>, List<Integer>, List<Long>, List<Byte> and empty lists.
  • Types never seen: no real64 (Double) or char16 value exists in the data of these machines, so VT_R8 is covered only by the unit test.

WinStorageSpaces, including the parameterized queries

  • Workstation (elevated): all 17 queries are identical, including the OperationalStatus arrays.
  • $1 queries (ASSOCIATORS OF {MSFT_PhysicalDisk…} WHERE ResultClass = MSFT_StorageReliabilityCounter):
    • they were rerun alone on the 8 servers that were still reachable;
    • they are identical on the 6 that have the Storage namespace, one of them with 3 disks;
    • on the other 2, the namespace is absent with both versions.
  • The 19 FAIL or FLAKY results of the first pass all came from these queries, and all were RPC 0x800706BF.
    • 18 went away once the queries ran alone.
    • The last one, on Server J, could not be rerun. There, 1.0.07 failed with RPC and this branch returned 1 row.

What disturbed the remote runs

On every server, the DCOM connection eventually fails with 0x800706BF and then stays broken for both versions. On 4 servers this happened right after the large Win32_PerfRawData queries; elsewhere it happened earlier or later. That left 1,363 RPC results across the 11 servers in the first pass. Two retry rounds in fresh JVMs brought this down to 89 untested queries.

These 89 are on the 3 servers that stopped resolving in DNS during the retries (H, J, K). 73 of them are identical on other machines. The other 16 are 7 Director52ServeRAIDNT queries, such as CIM_Battery and CIM_StorageVolume, which are among the 44 never exercised.

13 more machines could not be used: 7 refused access with the test accounts, 2 timed out on port 135 and 2 did not resolve in DNS.

5. MetricsHub CLI with this branch

The WMI extension of metricshub-community was rebuilt with this branch. The CLI ran -t win --wmi with automatic detection and 2 collects 20 s apart, in the order 1.0.07, this branch, then 1.0.07.

  • Local host: two campaigns gave output that is identical line by line once numbers are masked: 804, then 774, useful lines, with no error in any of the runs. Monitors, attributes and metrics are the same.
  • Remote hosts: there were 4 campaigns, on 3, 3, 11 and 8 hosts.
    • The output differs from run to run, even between the two 1.0.07 runs: on one host, 312 lines, then 1,840.
    • The cause is detection, which times out (DetectionStrategy operation timed out) or fails with RPC on these servers, at random. A line-by-line comparison proves nothing there.
  • Error categories instead: pooled over all hosts and campaigns, no error category appears with this branch that does not also appear with 1.0.07.
    • The categories seen are:
      • RPC 800706BF / 800706BA;
      • "WMI query failed";
      • detection or collect timeouts;
      • detection criteria that stop matching;
      • WBEM_E_CRITICAL_ERROR;
      • a MetricsHub engine NPE that occurs when detection times out, which has nothing to do with wmi-java.
    • On a single host, a category sometimes appears in only one run, with either version, depending on the RPC failures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@NassimBtk

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: e6de18fcbf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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

This is a MASSIVE improvement of the library! ❤️

@NassimBtk
NassimBtk merged commit eb5b814 into main Nov 19, 2026
4 checks passed
@NassimBtk
NassimBtk deleted the feature/issue-85-jna-native-memory branch November 19, 2026 13:45
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.

WMI queries leave about 50 JNA native memory blocks per value to the garbage collector

2 participants