Skip to content

feat: Add JVM memory metrics support for accurate Java application resource recommendations #440

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

research-devops
Copy link

Description

This PR addresses the issue #367 by adding support for JVM memory metrics to provide more accurate resource recommendations for Java applications. Currently, KRR relies on container-level memory metrics, which can be misleading for JVM applications since they often pre-allocate memory. This change introduces JVM-specific memory analysis using heap memory metrics.

Changes

New JVM Metrics Support

  • Added new metric loaders for JVM memory analysis:
    • JVMMemoryLoader: Collects JVM heap memory usage
    • MaxJVMMemoryLoader: Collects maximum JVM heap memory usage
    • JVMMemoryAmountLoader: Counts JVM memory data points
    • JVMDetector: Detects if a container is running a JVM application

Strategy Updates

  • Modified SimpleStrategy to support JVM memory analysis:
    • Added JVM detection logic
    • Introduced separate buffer percentages for JVM and non-JVM applications
    • Enhanced memory recommendation calculation for JVM applications
    • Added JVM-specific information in recommendation output

Configuration

  • Added new configuration option:
    • jvm_memory_buffer_percentage: Configurable buffer percentage for JVM applications (default: 30%)

Testing

Added comprehensive test coverage:

JVM Metrics Tests (test_jvm_metrics.py)

  • Tests for JVM metric loaders:
    • Query generation tests
    • Response parsing tests
    • Data point collection tests
    • Metric conversion tests

Strategy Tests (test_jvm_strategy.py)

  • Tests for JVM-aware memory analysis:
    • JVM application detection
    • Non-JVM application handling
    • OOMKill event handling with JVM
    • HPA integration
    • Custom buffer percentage configuration

Usage

The JVM memory analysis is automatically enabled when JVM metrics are detected. No additional configuration is required if your Prometheus is already collecting JVM metrics.

Example usage:

# Default settings
krr simple

# Custom JVM buffer percentage
krr simple --jvm_memory_buffer_percentage=40

Requirements

  • Prometheus with JVM metrics collection (via JMX Exporter or Micrometer)
  • JVM metrics should include jvm_memory_bytes_used with area="heap" label

Related Issues

Closes #367

@CLAassistant
Copy link

CLAassistant commented Jun 15, 2025

CLA assistant check
All committers have signed the CLA.

Copy link

coderabbitai bot commented Jun 15, 2025

"""

Walkthrough

The changes introduce JVM-specific memory metric loaders and detection logic into the resource recommendation strategy. New classes for querying and parsing JVM memory metrics from Prometheus are added, and the strategy is updated to use these metrics and a distinct buffer percentage when a JVM is detected. Comprehensive unit tests for these features are also included.

Changes

File(s) Change Summary
robusta_krr/core/integrations/prometheus/metrics/memory.py Added JVMMemoryLoader, MaxJVMMemoryLoader, JVMMemoryAmountLoader, and JVMDetector classes for JVM memory metrics.
robusta_krr/strategies/simple.py Integrated JVM metric loaders and detection into the strategy; added JVM buffer percentage setting and logic.
tests/test_jvm_metrics.py New test module for JVM metric loaders: query generation and response parsing.
tests/test_jvm_strategy.py New test module for JVM detection and JVM-specific recommendation logic in the strategy.

Sequence Diagram(s)

Loading
sequenceDiagram
    participant Strategy as SimpleStrategy
    participant Metrics as PrometheusMetric Loaders
    participant Prometheus as Prometheus
    participant K8s as K8sObjectData

    Strategy->>Metrics: Request JVMDetector query for object
    Metrics->>Prometheus: Query for JVM memory usage
    Prometheus-->>Metrics: Return JVM metric data
    Metrics-->>Strategy: Indicate JVM presence (or absence)

    alt JVM detected
        Strategy->>Metrics: Use MaxJVMMemoryLoader and JVMMemoryAmountLoader
        Metrics->>Prometheus: Fetch JVM-specific memory metrics
        Prometheus-->>Metrics: Return JVM memory data
        Metrics-->>Strategy: Provide JVM memory stats
        Strategy->>Strategy: Apply JVM buffer percentage
    else Not JVM
        Strategy->>Metrics: Use standard memory loaders
        Metrics->>Prometheus: Fetch standard memory metrics
        Prometheus-->>Metrics: Return standard memory data
        Metrics-->>Strategy: Provide standard memory stats
        Strategy->>Strategy: Apply standard buffer percentage
    end

    Strategy-->>Strategy: Calculate memory recommendation

Assessment against linked issues

Objective (Issue #) Addressed Explanation
Add support for Java/JVM metrics in recommendations (#367)
Enable detection of JVM workloads and use JVM-specific memory metrics (#367)
Use JVM-specific buffer percentage for memory recommendations (#367)
Provide tests for JVM metric loaders and JVM-aware recommendation logic (#367)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found.
"""

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
robusta_krr/strategies/simple.py (1)

86-100: ⚠️ Potential issue

JVM-specific loaders are never scheduled – will raise KeyError at runtime

__calculate_memory_proposal expects history_data to contain "MaxJVMMemoryLoader" and "JVMMemoryAmountLoader", yet the metrics property only registers JVMDetector alongside the generic loaders.
In a JVM workload the first history_data[...] access will therefore blow up with a KeyError.

Add the two JVM loaders to the list (optionally only when JVM support is enabled):

         metrics = [
             PercentileCPULoader(self.settings.cpu_percentile),
             MaxMemoryLoader,
             CPUAmountLoader,
             MemoryAmountLoader,
             JVMDetector,
+            MaxJVMMemoryLoader,
+            JVMMemoryAmountLoader,
         ]

This also eliminates the Ruff “unused import” warnings on lines 24-27.

🧹 Nitpick comments (3)
tests/test_jvm_metrics.py (1)

1-4: Remove unused datetime/timedelta imports to silence Ruff

They are not referenced anywhere in this module.

-import pytest
-from datetime import datetime, timedelta
-import numpy as np
+import pytest
+import numpy as np
🧰 Tools
🪛 Ruff (0.11.9)

2-2: datetime.datetime imported but unused

Remove unused import

(F401)


2-2: datetime.timedelta imported but unused

Remove unused import

(F401)

tests/test_jvm_strategy.py (1)

1-11: Prune unused imports (Ruff F401)

datetime, timedelta, MetricsPodData, and all JVM loader symbols are unused in this file – they generate CI noise.

-import pytest
-import numpy as np
-from datetime import datetime, timedelta
-
-from robusta_krr.core.abstract.strategies import MetricsPodData, K8sObjectData, PodData
-from robusta_krr.core.integrations.prometheus.metrics.memory import (
-    JVMMemoryLoader,
-    MaxJVMMemoryLoader,
-    JVMMemoryAmountLoader,
-    JVMDetector,
-)
+import pytest
+import numpy as np
+
+from robusta_krr.core.models.objects import K8sObjectData, PodData
+
+# No need to import JVM loaders – the strategy accesses them internally
🧰 Tools
🪛 Ruff (0.11.9)

3-3: datetime.datetime imported but unused

Remove unused import

(F401)


3-3: datetime.timedelta imported but unused

Remove unused import

(F401)


5-5: robusta_krr.core.abstract.strategies.MetricsPodData imported but unused

Remove unused import: robusta_krr.core.abstract.strategies.MetricsPodData

(F401)


7-7: robusta_krr.core.integrations.prometheus.metrics.memory.JVMMemoryLoader imported but unused

Remove unused import

(F401)


8-8: robusta_krr.core.integrations.prometheus.metrics.memory.MaxJVMMemoryLoader imported but unused

Remove unused import

(F401)


9-9: robusta_krr.core.integrations.prometheus.metrics.memory.JVMMemoryAmountLoader imported but unused

Remove unused import

(F401)


10-10: robusta_krr.core.integrations.prometheus.metrics.memory.JVMDetector imported but unused

Remove unused import

(F401)

robusta_krr/core/integrations/prometheus/metrics/memory.py (1)

111-132: Minor: query label list may miss a comma before cluster label

If get_prometheus_cluster_label() returns something that does not start with a comma, the rendered PromQL will be syntactically invalid because the preceding container="{object.container}" line lacks a trailing comma.

Consider guaranteeing the leading comma inside get_prometheus_cluster_label() or add one here conditionally.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 70b194c and a6067d0.

📒 Files selected for processing (4)
  • robusta_krr/core/integrations/prometheus/metrics/memory.py (1 hunks)
  • robusta_krr/strategies/simple.py (7 hunks)
  • tests/test_jvm_metrics.py (1 hunks)
  • tests/test_jvm_strategy.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
tests/test_jvm_metrics.py (3)
robusta_krr/core/integrations/prometheus/metrics/memory.py (12)
  • JVMMemoryLoader (111-132)
  • MaxJVMMemoryLoader (134-155)
  • JVMMemoryAmountLoader (157-178)
  • JVMDetector (180-199)
  • get_query (13-25)
  • get_query (33-48)
  • get_query (56-71)
  • get_query (81-109)
  • get_query (119-132)
  • get_query (139-155)
  • get_query (162-178)
  • get_query (187-199)
robusta_krr/core/models/objects.py (2)
  • K8sObjectData (38-107)
  • PodData (14-19)
tests/test_jvm_strategy.py (1)
  • mock_pod_data (16-26)
robusta_krr/strategies/simple.py (2)
robusta_krr/core/integrations/prometheus/metrics/memory.py (4)
  • JVMMemoryLoader (111-132)
  • MaxJVMMemoryLoader (134-155)
  • JVMMemoryAmountLoader (157-178)
  • JVMDetector (180-199)
robusta_krr/core/abstract/strategies.py (2)
  • description (117-122)
  • ResourceRecommendation (21-36)
🪛 Ruff (0.11.9)
tests/test_jvm_metrics.py

2-2: datetime.datetime imported but unused

Remove unused import

(F401)


2-2: datetime.timedelta imported but unused

Remove unused import

(F401)

tests/test_jvm_strategy.py

3-3: datetime.datetime imported but unused

Remove unused import

(F401)


3-3: datetime.timedelta imported but unused

Remove unused import

(F401)


5-5: robusta_krr.core.abstract.strategies.MetricsPodData imported but unused

Remove unused import: robusta_krr.core.abstract.strategies.MetricsPodData

(F401)


7-7: robusta_krr.core.integrations.prometheus.metrics.memory.JVMMemoryLoader imported but unused

Remove unused import

(F401)


8-8: robusta_krr.core.integrations.prometheus.metrics.memory.MaxJVMMemoryLoader imported but unused

Remove unused import

(F401)


9-9: robusta_krr.core.integrations.prometheus.metrics.memory.JVMMemoryAmountLoader imported but unused

Remove unused import

(F401)


10-10: robusta_krr.core.integrations.prometheus.metrics.memory.JVMDetector imported but unused

Remove unused import

(F401)

robusta_krr/strategies/simple.py

24-24: robusta_krr.core.integrations.prometheus.metrics.JVMMemoryLoader imported but unused

Remove unused import

(F401)


25-25: robusta_krr.core.integrations.prometheus.metrics.MaxJVMMemoryLoader imported but unused

Remove unused import

(F401)


26-26: robusta_krr.core.integrations.prometheus.metrics.JVMMemoryAmountLoader imported but unused

Remove unused import

(F401)

🔇 Additional comments (1)
robusta_krr/strategies/simple.py (1)

54-63: Buffer selection now depends on is_jvm – good but drop the unused ternary on NaN

np.max(data_) already returns -inf on empty input, but you gate for len(data_) == 0 above; safe. Implementation looks correct after the JVM buffer addition.

- Add MaxJVMMemoryLoader and JVMMemoryAmountLoader to metrics property
- Fix KeyError when processing JVM workloads
- Resolve unused import warnings for JVM metric loaders

This change ensures that JVM-specific metrics are properly collected
when a JVM application is detected, preventing runtime KeyError exceptions
in __calculate_memory_proposal method.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
robusta_krr/strategies/simple.py (2)

105-112: Update strategy description to reflect the new JVM-specific buffer.

The help text still states
Memory request: max + {self.settings.memory_buffer_percentage}% …
which is misleading for JVM workloads now governed by jvm_memory_buffer_percentage. Consider appending a sentence such as:

“For JVM containers the buffer defaults to {self.settings.jvm_memory_buffer_percentage}% of max JVM heap.”

Keeps the CLI self-documentation accurate.


174-179: Minor readability: avoid re-using data_count variable name.

data_count first holds the loader result object, then is re-assigned to a dict of point counts. Renaming the second usage (e.g. points_per_pod) would prevent mental context switches and ease debugging.

No functional impact, pure clarity.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a6067d0 and 9f1d06b.

📒 Files selected for processing (1)
  • robusta_krr/strategies/simple.py (7 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
robusta_krr/strategies/simple.py (2)
robusta_krr/core/integrations/prometheus/metrics/memory.py (4)
  • JVMMemoryLoader (111-132)
  • MaxJVMMemoryLoader (134-155)
  • JVMMemoryAmountLoader (157-178)
  • JVMDetector (180-199)
robusta_krr/core/abstract/strategies.py (2)
  • description (117-122)
  • ResourceRecommendation (21-36)
🪛 Ruff (0.11.9)
robusta_krr/strategies/simple.py

24-24: robusta_krr.core.integrations.prometheus.metrics.JVMMemoryLoader imported but unused

Remove unused import: robusta_krr.core.integrations.prometheus.metrics.JVMMemoryLoader

(F401)

Comment on lines +24 to +27
JVMMemoryLoader,
MaxJVMMemoryLoader,
JVMMemoryAmountLoader,
JVMDetector,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Unused import triggers Ruff F401 – drop or actually use JVMMemoryLoader.

JVMMemoryLoader is imported but never referenced. Ruff flags this as F401, which will fail lint-only CI steps.
Either add the loader to the metrics list or remove the import:

-    JVMMemoryLoader,
     MaxJVMMemoryLoader,

If a plain (non-max) JVM timeseries is not needed here, simply deleting the import keeps the strategy lean and CI green.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
JVMMemoryLoader,
MaxJVMMemoryLoader,
JVMMemoryAmountLoader,
JVMDetector,
MaxJVMMemoryLoader,
JVMMemoryAmountLoader,
JVMDetector,
🧰 Tools
🪛 Ruff (0.11.9)

24-24: robusta_krr.core.integrations.prometheus.metrics.JVMMemoryLoader imported but unused

Remove unused import: robusta_krr.core.integrations.prometheus.metrics.JVMMemoryLoader

(F401)

🤖 Prompt for AI Agents
In robusta_krr/strategies/simple.py around lines 24 to 27, the import
JVMMemoryLoader is unused and triggers a Ruff F401 lint error. To fix this,
either remove the JVMMemoryLoader import if it is not needed or add
JVMMemoryLoader to the metrics list or wherever appropriate in the code to
ensure it is used. This will resolve the lint error and keep the code clean.

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.

Is there a way to support Java and JVM metrics?
2 participants