Skip to content

Conversation

@manstis
Copy link
Contributor

@manstis manstis commented Aug 4, 2025

Description

When multiple successive requests to /readiness are made in quick succession the endpoint fails.

ERROR    2025-08-04 15:37:13,630 app.endpoints.health:49 uncategorized: Failed to check providers health: This event loop is already running          
INFO:     127.0.0.1:37980 - "GET /readiness HTTP/1.1" 503 Service Unavailable
/home/manstis/workspaces/github/manstis/forks/lightspeed-stack/src/app/endpoints/health.py:50: RuntimeWarning: coroutine 'AsyncLlamaStackAsLibraryClient.request' was never awaited
  return [
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

It is plausible this is an issue with llama-stack's LlamaStackAsLibraryClient class.

Whilst it appears to be synchronous it's internal implementation uses AsyncLlamaStackAsLibraryClient.

This PR contains a workaround by using AsyncLlamaStackClientHolder().

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.

The problem can be replicated with this code snippet:

import requests

url = "http://localhost:8080/readiness"

def call():
    result = requests.get(url)
    print(result.text)


def main():
    import threading
    threads = []
    for _ in range(10):
        t = threading.Thread(target=call)
        threads.append(t)
    for t in threads:
        t.start()
    for t in threads:
        t.join()


if __name__ == "__main__":
    main()

Summary by CodeRabbit

  • Refactor

    • Updated health check endpoints to use asynchronous operations for improved responsiveness.
  • Tests

    • Converted health endpoint tests to support asynchronous behavior, ensuring compatibility with async updates.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 4, 2025

Walkthrough

The health endpoint module and its associated unit tests were refactored to support asynchronous operations. Key functions and their tests were updated to use async/await syntax, and synchronous client mocks were replaced with asynchronous mocks. These changes ensure that provider health checks and readiness probes operate asynchronously throughout the codebase.

Changes

Cohort / File(s) Change Summary
Async Health Endpoint Refactor
src/app/endpoints/health.py
Converted health check and readiness probe functions to async; updated client to asynchronous version and adjusted control flow accordingly.
Async Test Updates
tests/unit/app/endpoints/test_health.py
Updated test functions and methods to async; replaced synchronous mocks with AsyncMock; adapted tests to new async health endpoint logic.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant AsyncLlamaStackClient
    Client->>API: GET /readiness
    API->>AsyncLlamaStackClient: await providers.list()
    AsyncLlamaStackClient-->>API: List of providers
    API-->>Client: ReadinessResponse (async)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

Hopping through code with async delight,
Health checks now run in the blink of a byte.
Tests leap in rhythm, mocks dance in tune,
No more waiting—responses come soon!
With every await, our stack feels more spry—
A rabbit’s proud wink as the endpoints fly by.
🐇✨

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 7325060 and 0d2a227.

📒 Files selected for processing (2)
  • src/app/endpoints/health.py (3 hunks)
  • tests/unit/app/endpoints/test_health.py (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/app/endpoints/health.py (2)
src/client.py (3)
  • AsyncLlamaStackClientHolder (55-87)
  • get_client (46-52)
  • get_client (81-87)
src/models/responses.py (2)
  • ProviderHealthStatus (81-92)
  • ReadinessResponse (95-134)
tests/unit/app/endpoints/test_health.py (1)
src/app/endpoints/health.py (2)
  • readiness_probe_get_method (73-91)
  • get_providers_health_statuses (25-57)
⏰ 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
🔇 Additional comments (7)
src/app/endpoints/health.py (3)

14-14: LGTM: Correct import for async operations.

The change from synchronous to AsyncLlamaStackClientHolder is appropriate and directly addresses the event loop conflicts mentioned in the PR objectives.


25-57: LGTM: Proper async conversion with correct await usage.

The function has been correctly converted to async with proper await on the client.providers.list() call. The error handling structure is preserved and will work correctly in the async context. This change directly addresses the event loop conflicts by making the async nature explicit.


73-91: LGTM: Endpoint handler correctly converted to async.

The readiness probe endpoint has been properly converted to async with the correct await on get_providers_health_statuses(). FastAPI handles async endpoint handlers seamlessly, and the business logic for determining readiness remains intact.

tests/unit/app/endpoints/test_health.py (4)

15-37: LGTM: Test correctly converted to async.

The test function has been properly converted to async with the correct await on readiness_probe_get_method(). The mocking strategy and assertions remain valid, ensuring continued test coverage for the unhealthy provider scenario.


40-68: LGTM: Test correctly converted to async.

The test function has been properly converted to async with the correct await on readiness_probe_get_method(). The test logic and assertions are preserved, maintaining coverage for the healthy provider scenario.


101-150: LGTM: Test method correctly updated for async implementation.

The test has been properly converted to async with correct updates:

  • Mock target updated to AsyncLlamaStackClientHolder.get_client
  • Using AsyncMock for the client mock to handle async methods
  • Properly awaiting the call to get_providers_health_statuses()

The test maintains comprehensive coverage of the provider health checking functionality.


152-167: LGTM: Error handling test correctly updated for async.

The test properly covers the error scenario with:

  • Correct async function declaration
  • Proper mock target for the async client holder
  • Correctly awaited call to the async function
  • Maintained test logic for connection error handling
✨ 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.
  • 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.

@manstis manstis requested review from ldjebran and tisnik August 4, 2025 14:41
Copy link
Contributor

@ldjebran ldjebran left a comment

Choose a reason for hiding this comment

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

LGTM

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

@tisnik tisnik merged commit 1faea65 into lightspeed-core:main Aug 4, 2025
17 of 18 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Oct 31, 2025
18 tasks
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