Skip to content

Conversation

@umago
Copy link
Contributor

@umago umago commented Jul 31, 2025

Description

This patch moves the setup_model_metrics() from the service startup to the first time the /metrics endpoint is called. This speed up the lightspeed-stack service initialization and also make lightspeed-stack more resilient regarding service initialization order because it no longer requires llama-stack to be started first (as setup_model_metrics() tries to connect to llama-stack and fetch the list of models from it).

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library
  • Bump-up library or tool used for development (does not change the final image)
  • CI configuration change
  • Konflux configuration change
  • Unit tests improvement
  • Integration tests improvement
  • End to end tests improvement

Related Tickets & Documents

  • Related Issue #
  • Closes #

Checklist before requesting a review

  • I have performed a self-review of my code.
  • PR has passed all pre-merge test jobs.
  • If it is a core feature, I have added thorough tests.

Testing

  • Please provide detailed steps to perform tests related to this code change.
  • How were the fix/results from this change verified? Please provide relevant screenshots or results.

Summary by CodeRabbit

  • New Features

    • Improved reliability of metrics setup by ensuring model metrics are initialized only once before serving metrics data.
    • Updated container and deployment configuration to build the application image locally for streamlined development.
  • Bug Fixes

    • Enhanced the /metrics endpoint to handle setup asynchronously, preventing redundant or repeated setup calls.
  • Tests

    • Updated tests for the metrics endpoint to support asynchronous execution and verify correct setup behavior.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 31, 2025

Walkthrough

The /metrics endpoint handler was converted to an asynchronous function, now awaiting a one-time setup of model metrics using a decorated async function to ensure it runs only once. Related imports and startup logic were removed, a new decorator was introduced, and tests were updated to accommodate the asynchronous changes and verify correct execution.

Changes

Cohort / File(s) Change Summary
/metrics Endpoint Async Refactor
src/app/endpoints/metrics.py, tests/unit/app/endpoints/test_metrics.py
Converted the /metrics endpoint handler and its test to async functions. The handler now awaits setup_model_metrics(), and the test mocks and asserts its invocation.
Startup Logic Cleanup
src/app/main.py
Removed import and invocation of setup_model_metrics from the application startup event.
Async Run-Once Decorator
src/utils/common.py
Added run_once_async decorator to ensure an async function executes only once per process, storing and returning a single task result for all calls.
Model Metrics Setup Improvements
src/metrics/utils.py
Decorated setup_model_metrics with @run_once_async and added logging at start and completion to control and trace one-time setup execution.
Container Build and Deployment Updates
Containerfile, docker-compose.yaml
Modified uv sync command by removing --no-install-project flag; changed lightspeed-stack service in docker-compose.yaml to build image locally using Containerfile instead of pulling pre-built image.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MetricsEndpoint
    participant SetupModelMetrics
    participant PrometheusExporter

    Client->>MetricsEndpoint: HTTP GET /metrics
    MetricsEndpoint->>SetupModelMetrics: await setup_model_metrics()
    SetupModelMetrics-->>MetricsEndpoint: (runs once, subsequent calls await same task)
    MetricsEndpoint->>PrometheusExporter: generate_latest(metrics_registry)
    PrometheusExporter-->>MetricsEndpoint: metrics data
    MetricsEndpoint->>Client: PlainTextResponse(metrics)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

  • LCORE-220: Add metrics to lightspeed-stack #256: The main PR modifies the existing /metrics endpoint handler to be asynchronous and adds an awaited call to setup_model_metrics(), while the retrieved PR originally introduced the /metrics endpoint handler synchronously and added the setup_model_metrics() function and related metrics; thus, the main PR builds directly on and changes the same endpoint handler and setup function introduced in the retrieved PR.

Suggested reviewers

  • tisnik

Poem

A hop to async, metrics anew,
One setup runs, then hops are few.
Decorators guard with gentle might,
Logs now twinkle in the night.
Tests await, the code is neat—
Bunny’s metrics can’t be beat! 🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1acf3da and 19bf660.

📒 Files selected for processing (1)
  • test.containerfile (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • test.containerfile
⏰ 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: e2e_tests
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

Support

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

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 generate unit tests to generate unit tests for 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.

@umago
Copy link
Contributor Author

umago commented Jul 31, 2025

The E2E test is not using the proposed changes. This PR deletes the setup_model_metrics() from main.py:startup_event() but looking at the logs for the E2E test, it still failing on that point. It seems like it's checking out from some already committed changes, I think we need to rework how we setup the E2E test.

@tisnik
Copy link
Contributor

tisnik commented Aug 1, 2025

/retest

@umago
Copy link
Contributor Author

umago commented Aug 1, 2025

@tisnik the E2E test is not using the code from PR, we need to fix that first:

lightspeed-stack  |   File "/app-root/src/app/main.py", line 85, in startup_event
lightspeed-stack  |     await setup_model_metrics()
lightspeed-stack  |   File "/app-root/src/metrics/utils.py", line 17, in setup_model_metrics

@umago
Copy link
Contributor Author

umago commented Aug 1, 2025

Rebased it on top of main, let's see

@umago umago force-pushed the setup-metrics branch 2 times, most recently from 8d190e4 to 576341d Compare August 1, 2025 13:35
This patch moves the setup_model_metrics() from the service startup to
the first time the /metrics endpoint is called. This speed up the
lightspeed-stack service initialization and also make lightspeed-stack
more resilient regarding service initialization order because it no
longer requires llama-stack to be started first (as
setup_model_metrics() tries to connect to llama-stack and fetch the list
of models from it).

Signed-off-by: Lucas Alvares Gomes <[email protected]>

build actual image instead of using the actual one

fix tests
Copy link
Contributor

@tisnik tisnik left a comment

Choose a reason for hiding this comment

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

LGTM

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.

3 participants