Skip to content

initiate metrics#37

Merged
eranco74 merged 2 commits intoopenshift-assisted:masterfrom
maorfr:initiate-metrics
Jul 21, 2025
Merged

initiate metrics#37
eranco74 merged 2 commits intoopenshift-assisted:masterfrom
maorfr:initiate-metrics

Conversation

@maorfr
Copy link
Copy Markdown
Member

@maorfr maorfr commented Jul 21, 2025

part of https://issues.redhat.com/browse/MGMT-21159

metrics are published on the first increment or observe, and are unavailable until then.

Summary by CodeRabbit

  • New Features
    • Metrics collection is now initialized automatically when the server starts, improving observability of server activity.

@openshift-ci
Copy link
Copy Markdown

openshift-ci Bot commented Jul 21, 2025

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: maorfr

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jul 21, 2025

Warning

Rate limit exceeded

@maorfr has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 24 minutes and 57 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between dc64838 and 33a383c.

📒 Files selected for processing (2)
  • server.py (2 hunks)
  • service_client/metrics.py (1 hunks)

Walkthrough

A new function, initiate_metrics, was introduced to initialize metrics at server startup. This function is now publicly exported by the service_client package and invoked in server.py before the server begins handling requests, ensuring that metrics are set up as soon as the server starts.

Changes

File(s) Change Summary
server.py Imported and invoked initiate_metrics before starting the server and adding the /metrics route.
service_client/init.py Re-exported initiate_metrics in __all__ to make it part of the public API.
service_client/metrics.py Added the initiate_metrics() function to initialize metrics at server startup.

Sequence Diagram(s)

sequenceDiagram
    participant Server
    participant Metrics

    Server->>Metrics: initiate_metrics()
    Metrics-->>Metrics: Increment request count, record zero latency
    Server->>Server: Add /metrics route
    Server->>Server: Start Uvicorn server
Loading

Estimated code review effort

2 (10–30 minutes)

Possibly related PRs

  • Implement Prometheus metrics endpoint #35: The main PR builds directly on the metrics functionality introduced in the retrieved PR by adding an explicit initiate_metrics() function call at server startup to initialize metrics, extending the existing metrics setup rather than introducing new metrics or endpoints.

Suggested labels

size/L, ok-to-test

Poem

A hop, a skip, some metrics to start,
With initiate_metrics, we’re playing our part.
Before the server leaps into the fray,
We count and time in a rabbit-y way.
So let the requests come, let the numbers grow—
This bunny’s ready, metrics in tow!
🐇📈

✨ 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.

@openshift-ci openshift-ci Bot added the size/S Denotes a PR that changes 10-29 lines, ignoring generated files. label Jul 21, 2025
Copy link
Copy Markdown

@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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a8a69b1 and dc64838.

📒 Files selected for processing (3)
  • server.py (2 hunks)
  • service_client/__init__.py (1 hunks)
  • service_client/metrics.py (1 hunks)
⏰ 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). (1)
  • GitHub Check: Red Hat Konflux / assisted-service-mcp-saas-main-on-pull-request
🔇 Additional comments (4)
server.py (2)

18-18: Import integration looks good.

The addition of initiate_metrics to the import statement is properly placed and follows the existing import pattern.


549-549: Metrics initialization placement is appropriate.

Calling initiate_metrics() before adding the /metrics route ensures that metrics are properly initialized before they become available through the endpoint, which aligns with the PR objective.

service_client/__init__.py (2)

10-10: Import statement correctly updated.

The addition of initiate_metrics to the import statement properly exposes the new function from the metrics module.


12-12: Public API exposure is appropriate.

Adding initiate_metrics to the __all__ list correctly makes it part of the package's public API, allowing it to be imported by consumers like server.py.

Comment thread service_client/metrics.py Outdated
Comment on lines +36 to +40
def initiate_metrics() -> None:
"""Initiate metrics."""
REQUEST_COUNT.labels(tool="").inc()
REQUEST_LATENCY.labels(tool="").observe(0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving the metrics initialization approach.

While the function achieves the goal of making metrics available upon startup, there are several concerns with the current implementation:

  1. Empty label concern: Using an empty string "" as the tool label may create confusing metrics output and doesn't follow Prometheus best practices for label values.

  2. Zero latency impact: Recording a 0-second observation in the histogram could potentially skew latency statistics and percentile calculations.

  3. Lack of idempotency: The function doesn't prevent multiple calls, which could increment counters unexpectedly.

Consider this improved approach:

def initiate_metrics() -> None:
-    """Initiate metrics."""
-    REQUEST_COUNT.labels(tool="").inc()
-    REQUEST_LATENCY.labels(tool="").observe(0)
+    """Initiate metrics by creating initial metric instances."""
+    # Initialize metrics without incrementing counters
+    # This creates the metric families in Prometheus without artificial data
+    REQUEST_COUNT.labels(tool="__init__")
+    REQUEST_LATENCY.labels(tool="__init__")

Alternatively, consider initializing the metrics by simply accessing the .labels() method without incrementing/observing, which creates the metric instances without adding artificial data points.

📝 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
def initiate_metrics() -> None:
"""Initiate metrics."""
REQUEST_COUNT.labels(tool="").inc()
REQUEST_LATENCY.labels(tool="").observe(0)
def initiate_metrics() -> None:
"""Initiate metrics by creating initial metric instances."""
# Initialize metrics without incrementing counters
# This creates the metric families in Prometheus without artificial data
REQUEST_COUNT.labels(tool="__init__")
REQUEST_LATENCY.labels(tool="__init__")
🤖 Prompt for AI Agents
In service_client/metrics.py around lines 36 to 40, the initiate_metrics
function currently increments counters and observes zero latency with empty
string labels, which can skew metrics and produce confusing output. To fix this,
modify the function to only access the .labels() method with valid, non-empty
label values to initialize the metrics without incrementing or observing any
values. Also, ensure the function is idempotent by preventing multiple
increments or observations on repeated calls.

Comment thread service_client/metrics.py Outdated
@maorfr maorfr force-pushed the initiate-metrics branch from 490bb18 to 33a383c Compare July 21, 2025 11:30
@eranco74 eranco74 merged commit d7fb34d into openshift-assisted:master Jul 21, 2025
12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/S Denotes a PR that changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants