Skip to content

Extract shared WindowsGpuStats logic into common base class - #3277

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:refactor/gpu-dedup
May 20, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:refactor/gpu-dedup

Conversation

@dbwiddis

@dbwiddis dbwiddis commented May 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Addresses Issue 1 (JNA ↔ FFM Parallel Implementations) from #3274 for the WindowsGpuStats class (222 lines duplicated).

Changes

  • New: oshi-common/.../WindowsGpuStats.java (483 lines) — all business logic for GPU metrics
  • Simplified: WindowsGpuStatsJNA (311→121 lines) — native dispatch only
  • Simplified: WindowsGpuStatsFFM (287→121 lines) — native dispatch only

Pattern

The common base class holds all GPU metrics logic:

  • Tick aggregation from PDH GPU Engine counters
  • Utilization calculation (LHM → PDH tick-delta fallback)
  • VRAM/shared memory from PDH Adapter Memory counters
  • Temperature/power/clock/fan fallback chains (NVML → ADL → LHM)
  • Device caching for NVML and ADL

Subclasses implement 18 abstract methods that dispatch to platform-specific utilities:

  • PDH: queryGpuEngineCounters(), queryGpuAdapterMemoryCounters()
  • LHM WMI: queryLhmSensors()
  • NVML: isNvmlAvailable(), nvmlFindDevice(), nvmlFindDeviceByName(), nvmlGet*()
  • ADL: isAdlAvailable(), adlFindAdapterIndex(), adlGet*()

Testing

  • All existing tests pass (Linux CI)
  • spotless:apply clean

Notes

  • Also reconciled a minor behavioral difference: FFM had a counter-reset guard (dActive < 0 || dIdle < 0) in getGpuUtilization() that JNA lacked. The common class includes this guard (safer behavior).

Summary by CodeRabbit

  • New Features

    • Added GPU statistics monitoring for Windows, including utilization, temperature, power draw, memory usage, and fan speed metrics with multi-source support.
  • Refactor

    • Consolidated GPU statistics implementations into a shared base class to reduce code duplication and improve maintainability.

Review Change Stack

Move all GPU metrics business logic (tick aggregation, utilization
calculation, VRAM/shared memory queries, temperature/power/clock/fan
fallback chains) into a common abstract WindowsGpuStats class.

JNA and FFM subclasses implement 18 abstract dispatch methods for
NVML, ADL, PDH (GpuInformation), and LHM WMI calls.

Eliminates ~222 lines of duplicated logic between the two
implementations.

Partial fix for #3274 (Issue 1: JNA/FFM parallel implementations)
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 1efac6ac-5094-4ad7-8fac-c88b1f6b1a1d

📥 Commits

Reviewing files that changed from the base of the PR and between f06494d and aa6d263.

📒 Files selected for processing (3)
  • oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsGpuStats.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsJNA.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). (11)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, windows-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Test JDK 25, macos-latest (+ JNA==FFM)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: JMH Benchmarks, macos-latest
  • GitHub Check: JMH Benchmarks, ubuntu-latest
  • GitHub Check: JMH Benchmarks, windows-latest
  • GitHub Check: Lint (Spotless, Checkstyle, ForbiddenAPIs, Javadoc)
  • GitHub Check: Analyze (java)
🧰 Additional context used
🧠 Learnings (2)
📚 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/hardware/platform/windows/WindowsGpuStatsJNA.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/hardware/common/platform/windows/WindowsGpuStats.java
🔇 Additional comments (18)
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsJNA.java (4)

26-30: LGTM!


32-45: LGTM!


47-85: LGTM!


87-120: LGTM!

oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.java (4)

22-30: LGTM!


32-45: LGTM!


47-85: LGTM!


87-120: LGTM!

oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsGpuStats.java (10)

1-46: LGTM!


47-182: LGTM!


183-234: LGTM!


236-265: LGTM!


267-297: LGTM!


299-341: LGTM!


343-407: LGTM!


409-433: LGTM!


435-464: LGTM!


466-481: LGTM!


📝 Walkthrough

Walkthrough

Introduces a shared abstract WindowsGpuStats base class that consolidates all Windows GPU metrics logic (session lifecycle, ticks, utilization, memory, power, thermal, clocks, fan) with multi-source fallback, then refactors JNA and FFM implementations to extend this base while providing only platform-specific data source overrides.

Changes

Windows GPU Stats Base Class and Adapters

Layer / File(s) Summary
Base class structure and abstractions
oshi-common/src/main/java/oshi/hardware/common/platform/windows/WindowsGpuStats.java (lines 1–184)
Abstract WindowsGpuStats class introduced with identifying fields, NVML/ADL device cache, baseline tick state, protected constructor, and abstract method declarations for platform-native GPU engine counters, adapter memory counters, LHM sensors, and NVML/ADL metric reads.
Core metric implementations in base class
oshi-common/.../WindowsGpuStats.java (lines 185–407)
All synchronized public GPU metrics implemented in base class: close()/isClosed() manage session state; getGpuTicks() aggregates engine tick counts filtered by LUID prefix; getGpuUtilization() derives from tick deltas or LHM sensor; getVramUsed() and getSharedMemoryUsed() query memory via PDH/LHM; getTemperature(), getPowerDraw(), getCoreClockMhz(), getMemoryClockMhz(), getFanSpeedPercent() use NVML→ADL→LHM fallback chain.
Internal helpers and utilities in base class
oshi-common/.../WindowsGpuStats.java (lines 409–482)
Helper methods: checkOpen() validates session state; queryAdapterMemory() filters adapter instances by case-insensitive LUID prefix; findNvmlDevice() and findAdlIndex() cache device/adapter lookup results; lhmFloatSensor() safely queries LHM sensors with exception catching and debug logging.
JNA adapter refactoring to extend base class
oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsJNA.java
WindowsGpuStatsJNA refactored from standalone GpuStats to extend WindowsGpuStats; imports rewritten to reference base class and JNA utility classes; constructor delegates to super(); all public metrics and session state removed; protected overrides added for GPU engine/memory counters (via GpuInformationJNA), LHM sensors (via LhmSensorJNA), and NVML/ADL device/metric accessors (via NvmlUtilJNA/AdlUtilJNA).
FFM adapter refactoring to extend base class
oshi-core-ffm/src/main/java/oshi/hardware/platform/windows/WindowsGpuStatsFFM.java
WindowsGpuStatsFFM refactored from standalone GpuStats to extend WindowsGpuStats; all public metrics, session management, and internal caching logic removed; protected overrides added for GPU engine/memory counters (via GpuInformationFFM), LHM sensors (via LhmSensorFFM), and NVML/ADL device/metric accessors (via NvmlUtilFFM/AdlUtilFFM).

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant WindowsGpuStats as WindowsGpuStats<br/>(base)
  participant JNA as WindowsGpuStatsJNA
  participant NvmlUtil as NvmlUtilJNA
  participant AdlUtil as AdlUtilJNA
  participant LhmSensor as LhmSensorJNA

  Client->>WindowsGpuStats: getTemperature()
  WindowsGpuStats->>WindowsGpuStats: checkOpen()
  WindowsGpuStats->>WindowsGpuStats: isNvmlAvailable()?
  alt NVML available
    WindowsGpuStats->>JNA: nvmlGetTemperature(device)
    JNA->>NvmlUtil: getTemperature(device)
    NvmlUtil-->>JNA: temp value
    JNA-->>WindowsGpuStats: temp value
  else ADL available
    WindowsGpuStats->>JNA: adlGetTemperature(index)
    JNA->>AdlUtil: getTemperature(index)
    AdlUtil-->>JNA: temp value
    JNA-->>WindowsGpuStats: temp value
  else LHM fallback
    WindowsGpuStats->>WindowsGpuStats: lhmFloatSensor("Temperature")
    WindowsGpuStats->>LhmSensor: queryLhmSensors()
    LhmSensor-->>WindowsGpuStats: sensor values
    WindowsGpuStats-->>WindowsGpuStats: extract by name
  end
  WindowsGpuStats-->>Client: temperature or -1
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • oshi/oshi#3095: Introduces the session-oriented WindowsGpuStats base class with lifecycle management that is the core focus of this PR.
  • oshi/oshi#3089: Implements the multi-source NVML→ADL→LHM fallback pattern for GPU metrics that this PR consolidates into the shared base class.
  • oshi/oshi#3159: Updates ADL query integration for Windows GPU stats that aligns with the ADL metric overrides introduced in the JNA adapter refactoring.

Suggested reviewers

  • mprins

Poem

🐰 A base class hops in, neat and clean,
GPU metrics shared in a single sheen.
JNA and FFM now delegate with grace,
Multi-source fallback finds its rightful place. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.40% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main change: extracting shared GPU stats logic from platform-specific implementations into a reusable Windows base class.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

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

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented May 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 74.75%. Comparing base (f06494d) to head (aa6d263).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##             master    #3277   +/-   ##
=========================================
  Coverage     74.75%   74.75%           
  Complexity       73       73           
=========================================
  Files           410      410           
  Lines         15894    15894           
  Branches       2534     2534           
=========================================
  Hits          11882    11882           
- Misses         2549     2550    +1     
+ Partials       1463     1462    -1     
Flag Coverage Δ
linux 39.82% <ø> (+0.01%) ⬆️
macos 40.47% <ø> (ø)
windows 48.10% <ø> (-0.02%) ⬇️

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.

@dbwiddis
dbwiddis merged commit 01540c0 into oshi:master May 20, 2026
20 checks passed
@dbwiddis
dbwiddis deleted the refactor/gpu-dedup branch May 26, 2026 16:19
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