Skip to content

Use async for model metrics initialization#294

Closed
omertuc wants to merge 1 commit intolightspeed-core:mainfrom
omertuc:asyncmetrics
Closed

Use async for model metrics initialization#294
omertuc wants to merge 1 commit intolightspeed-core:mainfrom
omertuc:asyncmetrics

Conversation

@omertuc
Copy link
Contributor

@omertuc omertuc commented Jul 25, 2025

Description

LlamaStackClientHolder is sync, but internally within llama-stack it glues into the async client, by instantiating its own event loop. This somehow interferes with the async event loop of uvicorn:

Traceback
Traceback (most recent call last):
  File "/app-root/src/lightspeed_stack.py", line 91, in <module>
    main()
  File "/app-root/src/lightspeed_stack.py", line 86, in main
    start_uvicorn(configuration.service_configuration)
  File "/app-root/src/runners/uvicorn.py", line 20, in start_uvicorn
    uvicorn.run(
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/main.py", line 580, in run
    server.run()
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/server.py", line 67, in run
    return asyncio.run(self.serve(sockets=sockets))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.12/asyncio/runners.py", line 195, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.12/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.12/asyncio/base_events.py", line 691, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/server.py", line 71, in serve
    await self._serve(sockets)
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/server.py", line 78, in _serve
    config.load()
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/config.py", line 436, in load
    self.loaded_app = import_from_string(self.app)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/importer.py", line 19, in import_from_string
    module = importlib.import_module(module_str)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.12/importlib/__init__.py", line 90, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 999, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "/app-root/src/app/main.py", line 77, in <module>
    setup_model_metrics()
  File "/app-root/src/metrics/utils.py", line 16, in setup_model_metrics
    for model in client.models.list()
                 ^^^^^^^^^^^^^^^^^^^^
  File "/app-root/.venv/lib64/python3.12/site-packages/llama_stack_client/resources/models.py", line 93, in list
    return self._get(
           ^^^^^^^^^^
  File "/app-root/.venv/lib64/python3.12/site-packages/llama_stack_client/_base_client.py", line 1178, in get
    return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app-root/llama-stack/llama_stack/distribution/library_client.py", line 177, in request
    result = loop.run_until_complete(self.async_client.request(*args, **kwargs))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.12/asyncio/base_events.py", line 667, in run_until_complete
    self._check_running()
  File "/usr/lib64/python3.12/asyncio/base_events.py", line 628, in _check_running
    raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running
sys:1: RuntimeWarning: coroutine 'AsyncLlamaStackAsLibraryClient.request' was never awaited

Not sure why this was not caught earlier, maybe it only happens when running llama-stack in library mode?

I've changed the setup_model_metrics function to be async and use AsyncLlamaStackClientHolder instead of LlamaStackClientHolder. It also means we should call it from startup_event

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.

I've ran it manually in the same setup where the error occurs and made sure the error no longer occurs

`LlamaStackClientHolder` is sync, but internally within llama-stack it
glues into the async client, by instantiating its own event loop. This
somehow interferes with the async event loop of uvicorn:

<details>
<summary>Traceback</summary>
```
Traceback (most recent call last):
  File "/app-root/src/lightspeed_stack.py", line 91, in <module>
    main()
  File "/app-root/src/lightspeed_stack.py", line 86, in main
    start_uvicorn(configuration.service_configuration)
  File "/app-root/src/runners/uvicorn.py", line 20, in start_uvicorn
    uvicorn.run(
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/main.py", line 580, in run
    server.run()
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/server.py", line 67, in run
    return asyncio.run(self.serve(sockets=sockets))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.12/asyncio/runners.py", line 195, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.12/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.12/asyncio/base_events.py", line 691, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/server.py", line 71, in serve
    await self._serve(sockets)
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/server.py", line 78, in _serve
    config.load()
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/config.py", line 436, in load
    self.loaded_app = import_from_string(self.app)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app-root/.venv/lib64/python3.12/site-packages/uvicorn/importer.py", line 19, in import_from_string
    module = importlib.import_module(module_str)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.12/importlib/__init__.py", line 90, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 999, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "/app-root/src/app/main.py", line 77, in <module>
    setup_model_metrics()
  File "/app-root/src/metrics/utils.py", line 16, in setup_model_metrics
    for model in client.models.list()
                 ^^^^^^^^^^^^^^^^^^^^
  File "/app-root/.venv/lib64/python3.12/site-packages/llama_stack_client/resources/models.py", line 93, in list
    return self._get(
           ^^^^^^^^^^
  File "/app-root/.venv/lib64/python3.12/site-packages/llama_stack_client/_base_client.py", line 1178, in get
    return cast(ResponseT, self.request(cast_to, opts, stream=stream, stream_cls=stream_cls))
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/app-root/llama-stack/llama_stack/distribution/library_client.py", line 177, in request
    result = loop.run_until_complete(self.async_client.request(*args, **kwargs))
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib64/python3.12/asyncio/base_events.py", line 667, in run_until_complete
    self._check_running()
  File "/usr/lib64/python3.12/asyncio/base_events.py", line 628, in _check_running
    raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running
sys:1: RuntimeWarning: coroutine 'AsyncLlamaStackAsLibraryClient.request' was never awaited
```
</details>

Not sure why this was not caught earlier, maybe it only happens when
running llama-stack in library mode?

I've changed the `setup_model_metrics` function to be async and use
`AsyncLlamaStackClientHolder` instead of `LlamaStackClientHolder`. It
also means we should call it from `startup_event`
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 25, 2025

Walkthrough

The changes refactor the model metrics setup process to be asynchronous. The setup_model_metrics function is now async, uses an asynchronous client, and is invoked during the application's async startup event rather than at module load time. Related imports and docstrings are updated to reflect these changes.

Changes

File(s) Change Summary
src/app/main.py Moved setup_model_metrics() call into the async startup_event function; updated docstring.
src/metrics/utils.py Converted setup_model_metrics to async, switched to async client, updated function signature/imports.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

In the warren of code, async hops anew,
Metrics now awaken when startup is due.
No more at import, the rabbits all cheer—
Awaiting their models as launch time draws near.
With paws on the future, we leap and we bound,
Async and alive, where improvements are found!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 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.
    • @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 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.

Copy link
Contributor

@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 (1)
src/app/main.py (1)

81-86: Consider error handling for startup operations

While the async integration is correct, consider adding error handling around setup_model_metrics() to prevent startup failures from completely breaking the application. The current implementation may cause the entire application to fail to start if model metrics setup encounters issues.

Consider wrapping the call in a try-except block:

async def startup_event() -> None:
    """Perform logger setup and other initializations on service startup."""
    try:
        await setup_model_metrics()
    except Exception as e:
        logger.error("Failed to setup model metrics: %s", e)
        # Consider whether to continue startup or fail fast based on requirements
    logger.info("Registering MCP servers")
    await register_mcp_servers_async(logger, configuration.configuration)
    get_logger("app.endpoints.handlers")
    logger.info("App startup complete")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e534d93 and 17a8eb8.

📒 Files selected for processing (2)
  • src/app/main.py (1 hunks)
  • src/metrics/utils.py (1 hunks)
🔇 Additional comments (5)
src/metrics/utils.py (3)

4-4: LGTM: Correct import for async pattern

The import change from LlamaStackClientHolder to AsyncLlamaStackClientHolder aligns with the async conversion requirements.


11-11: LGTM: Function correctly converted to async

The function signature is properly updated to async, which is necessary to support the awaited client operations.


16-16: LGTM: Correct async pattern for model listing

The await client.models.list() call is properly implemented for the async client pattern.

src/app/main.py (2)

80-80: LGTM: Docstring accurately updated

The docstring correctly reflects that the function now performs additional initializations beyond just logger setup.


81-81: LGTM: Proper async integration with startup event

The await setup_model_metrics() call is correctly placed in the async startup event, resolving the event loop conflict described in the PR objectives.

async def setup_model_metrics() -> None:
"""Perform setup of all metrics related to LLM model and provider."""
client = LlamaStackClientHolder().get_client()
client = AsyncLlamaStackClientHolder().get_client()
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify error handling for async client initialization

The async client initialization looks correct, but ensure that any potential exceptions from AsyncLlamaStackClientHolder().get_client() are properly handled upstream.


🏁 Script executed:

#!/bin/bash
# Description: Check if AsyncLlamaStackClientHolder.get_client() can raise exceptions that need handling
# Expected: Find the implementation and any exception handling patterns

ast-grep --pattern $'class AsyncLlamaStackClientHolder {
  $$$
  get_client($$$) {
    $$$
  }
  $$$
}'

Length of output: 104


🏁 Script executed:

#!/usr/bin/env bash
# Locate the AsyncLlamaStackClientHolder class and its get_client method

echo "==> Searching for class AsyncLlamaStackClientHolder definition"
rg -n "class AsyncLlamaStackClientHolder" .

echo
echo "==> Searching for get_client method definition"
rg -n "def get_client" .

Length of output: 528


🏁 Script executed:

#!/usr/bin/env bash
# Display the AsyncLlamaStackClientHolder class and its get_client implementation
echo "==> Showing lines 45–120 of src/client.py for context"
sed -n '45,120p' src/client.py

Length of output: 1974


🏁 Script executed:

#!/usr/bin/env bash
# Display the first 200 lines of src/metrics/utils.py to review get_client usage
echo "==> Showing lines 1–200 of src/metrics/utils.py"
sed -n '1,200p' src/metrics/utils.py

Length of output: 1733


Handle potential RuntimeError from uninitialized async client

AsyncLlamaStackClientHolder.get_client() will raise a RuntimeError if load() hasn’t been called. In src/metrics/utils.py at line 13, wrap the call in a try/except or otherwise ensure the client is initialized before fetching metrics:

Possible fix:

diff --git a/src/metrics/utils.py b/src/metrics/utils.py
@@ async def setup_model_metrics() -> None:
-    client = AsyncLlamaStackClientHolder().get_client()
+    try:
+        client = AsyncLlamaStackClientHolder().get_client()
+    except RuntimeError as e:
+        logger.error("Metrics setup skipped: %s", e)
+        return

This will prevent an uncaught exception during metrics initialization.

📝 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
client = AsyncLlamaStackClientHolder().get_client()
try:
client = AsyncLlamaStackClientHolder().get_client()
except RuntimeError as e:
logger.error("Metrics setup skipped: %s", e)
return
🤖 Prompt for AI Agents
In src/metrics/utils.py at line 13, the call to
AsyncLlamaStackClientHolder().get_client() can raise a RuntimeError if the
client is not initialized. To fix this, wrap the get_client() call in a
try/except block to catch RuntimeError and handle it gracefully, or ensure that
load() is called on AsyncLlamaStackClientHolder before calling get_client().
This will prevent uncaught exceptions during metrics initialization.

@omertuc
Copy link
Contributor Author

omertuc commented Jul 25, 2025

Oh are you kidding me... #293

@omertuc omertuc closed this Jul 25, 2025
@manstis
Copy link
Contributor

manstis commented Jul 25, 2025

Yes, sorry @omertuc .

I spotted it earlier today and @umago fixed it.

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.

2 participants