Skip to content

Enhance run information retrieval and trigger graph functionality#340

Merged
NiveditJain merged 5 commits intoexospherehost:mainfrom
NiveditJain:fixes
Sep 3, 2025
Merged

Enhance run information retrieval and trigger graph functionality#340
NiveditJain merged 5 commits intoexospherehost:mainfrom
NiveditJain:fixes

Conversation

@NiveditJain
Copy link
Member

  • Updated get_run_info to calculate total run counts more efficiently by storing the result in a variable, improving readability and performance.
  • Modified the status assignment in get_run_info to return RunStatusEnum.FAILED when no runs are found, enhancing error handling.
  • Refactored trigger_graph to only insert new stores if there are any, preventing unnecessary database operations and improving efficiency.

- Updated `get_run_info` to calculate total run counts more efficiently by storing the result in a variable, improving readability and performance.
- Modified the status assignment in `get_run_info` to return `RunStatusEnum.FAILED` when no runs are found, enhancing error handling.
- Refactored `trigger_graph` to only insert new stores if there are any, preventing unnecessary database operations and improving efficiency.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 3, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Avoids unnecessary database writes when no new stores exist.
    • Returns empty results cleanly when no runs are found.
    • Improves accuracy of per-run status when mixed states occur.
  • Refactor

    • Switched run listing to bulk aggregation for faster, scalable summaries.
    • Derives status from aggregated counts and sorts results by newest.
  • Chores

    • Added a database index to speed queries by run and status.
  • Tests

    • Reworked unit tests to cover aggregation flow, pagination, edge cases, and large datasets.

Walkthrough

Replaced per-run counting with a bulk PyMongo aggregation in get_runs, removed two helper functions and build RunListItem entries from aggregation (with new status logic and early-empty return), added a guard to skip Store.insert_many when no items, and added a non-unique index on (run_id, status) in the State model.

Changes

Cohort / File(s) Summary
Run listing & aggregation
state-manager/app/controller/get_runs.py
Removed get_run_status and get_run_info; use a single PyMongo aggregation across runs to compute counts (total, success, pending, errored, retried); build RunListItem entries directly from aggregation (status = PENDING if pending>0 else FAILED if errored>0 else SUCCESS); early return empty RunsResponse when no runs; append runs missing from aggregation with zero counts and status FAILED; sort by created_at desc.
Trigger graph DB guard
state-manager/app/controller/trigger_graph.py
Add guard: call Store.insert_many only when new_stores is non-empty (skip DB insert for empty lists).
State model index
state-manager/app/models/db/state.py
Add non-unique index IndexModel([("run_id", 1), ("status", 1)], name="run_id_status_index") to Settings.indexes.
Tests (get_runs)
state-manager/tests/unit/controller/test_get_runs.py
Refactor tests to exercise aggregation-based path and pagination; remove tests for removed helpers; introduce mocks for PyMongo collection aggregate cursor and assert aggregation pipeline structure and various edge cases (empty, pagination, missing aggregation rows).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant Controller as GetRuns Controller
  participant DB as MongoDB (States)
  participant Lookup as Local lookup_table

  Client->>Controller: Request runs for namespace (page/size)
  Controller->>DB: Query runs list (namespace) -> runs + total count
  DB-->>Controller: runs list
  alt no runs
    Controller-->>Client: Return empty RunsResponse
  else runs exist
    Controller->>DB: Aggregation across run_id -> counts (total, success, pending, errored, retried)
    DB-->>Controller: Aggregated rows
    Controller->>Lookup: Build run_id -> Run (graph_name, created_at)
    loop For each aggregation row
      Controller->>Controller: Determine status (PENDING if pending>0 else FAILED if errored>0 else SUCCESS)
      Controller-->>Client: Add RunListItem(run_id, counts, status, created_at)
    end
    alt runs missing from aggregation
      Controller->>Controller: Append RunListItem for missing runs (zero counts, status=FAILED)
    end
    Controller-->>Client: Return RunsResponse(sorted by created_at desc, total)
  end
Loading
sequenceDiagram
  autonumber
  participant Orchestrator as Trigger Graph
  participant Store as Store Model / DB

  Orchestrator->>Orchestrator: Build new_stores list
  alt new_stores not empty
    Orchestrator->>Store: insert_many(new_stores)
    Store-->>Orchestrator: insert result
  else new_stores empty
    note right of Orchestrator: Skip DB insert
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • nk-ag

Poem

I hop through indexes, quick and spry,
I count the runs beneath the sky.
If baskets are empty, I skip the store,
I stitch the list and sort once more.
A twitch, a hop — the states align, hooray! 🐇


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c3df51f and 585365a.

📒 Files selected for processing (2)
  • state-manager/app/controller/get_runs.py (1 hunks)
  • state-manager/tests/unit/controller/test_get_runs.py (8 hunks)
✨ 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.
    • 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.
  • 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 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/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @NiveditJain, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request focuses on enhancing the efficiency and robustness of the state management system. It optimizes data retrieval for run information and refines database interactions during graph triggering, leading to more performant and reliable operations.

Highlights

  • Run Information Retrieval Optimization: The get_run_info function now calculates the total run count once and stores it in a variable, improving efficiency by reducing redundant database queries and enhancing code readability.
  • Improved Run Status Handling: The get_run_info function has been updated to correctly assign RunStatusEnum.FAILED when no runs are found, providing better error handling for empty run states.
  • Efficient Graph Triggering: The trigger_graph function now conditionally inserts new stores into the database only if the new_stores list is not empty, preventing unnecessary database operations and improving performance.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@NiveditJain NiveditJain linked an issue Sep 3, 2025 that may be closed by this pull request
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces some good efficiency improvements. The change to get_run_info reduces one database call, and the change in trigger_graph avoids a database call for empty stores. My review focuses on a significant performance optimization in get_run_info by using a database aggregation query to fetch all run statistics in a single call, which will resolve a potential N+1 query problem. I also suggest a minor stylistic improvement in trigger_graph to follow Python best practices.

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: 3

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 65767e2 and 11aa5e3.

📒 Files selected for processing (2)
  • state-manager/app/controller/get_runs.py (1 hunks)
  • state-manager/app/controller/trigger_graph.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
state-manager/app/controller/get_runs.py (4)
state-manager/app/models/db/state.py (1)
  • State (13-97)
dashboard/src/types/state-manager.ts (1)
  • RunListItem (192-202)
state-manager/app/models/run_models.py (2)
  • RunListItem (14-24)
  • RunStatusEnum (9-12)
state-manager/app/models/state_status_enum.py (1)
  • StateStatusEnum (4-20)
state-manager/app/controller/trigger_graph.py (2)
state-manager/app/models/db/store.py (1)
  • Store (5-36)
state-manager/app/models/db/state.py (1)
  • insert_many (55-61)
🔇 Additional comments (1)
state-manager/app/controller/get_runs.py (1)

31-32: Behavior change: zero-state runs now surface as FAILED — confirm product intent.

If a Run exists without any State rows (e.g., partial failures, legacy data), the UI will show FAILED. Verify this is desired; otherwise consider PENDING or a distinct “EMPTY” state.

- Updated the `get_runs` function to utilize MongoDB aggregation for improved efficiency in retrieving run statistics.
- Introduced a lookup table to map run IDs to their corresponding run objects, streamlining data processing.
- Enhanced error handling by returning an empty response when no runs are found, ensuring clarity in API responses.
- Refactored the response structure to include detailed run statistics, improving the overall data returned to the client.
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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
state-manager/app/controller/get_runs.py (2)

1-2: Remove unused imports to fix Ruff errors.

These imports are no longer used after the refactoring and are causing pipeline failures.

-import asyncio
-from beanie.operators import In, NotIn

136-138: Remove obsolete get_run_status references in tests
In state-manager/tests/unit/controller/test_get_runs.py, delete the get_run_status import and all its usages to match its removal from app/controller/get_runs.py.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between af63b64 and c3df51f.

📒 Files selected for processing (1)
  • state-manager/app/controller/get_runs.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
state-manager/app/controller/get_runs.py (5)
dashboard/src/types/state-manager.ts (2)
  • RunsResponse (204-210)
  • RunListItem (192-202)
state-manager/app/models/run_models.py (3)
  • RunsResponse (26-32)
  • RunListItem (14-24)
  • RunStatusEnum (9-12)
state-manager/app/models/db/state.py (1)
  • State (13-104)
state-manager/app/models/state_status_enum.py (1)
  • StateStatusEnum (4-20)
state-manager/app/models/db/run.py (1)
  • Run (7-25)
🪛 GitHub Actions: State Manager Unit Tests
state-manager/app/controller/get_runs.py

[error] 1-1: ImportError: cannot import name 'get_run_status' from 'app.controller.get_runs'. The tests import get_run_status in tests/unit/controller/test_get_runs.py; ensure the function is defined or exported in get_runs.py and the import path is correct. Failing command: 'pytest tests/ --cov=app --cov-report=xml --cov-report=term-missing --cov-report=html -v --junitxml=full-pytest-report.xml'.

🪛 GitHub Actions: Ruff check on changed files only
state-manager/app/controller/get_runs.py

[error] 1-1: Ruff: F401 - 'asyncio' imported but unused.


[error] 2-2: Ruff: F401 - 'beanie.operators.In' imported but unused.


[error] 2-2: Ruff: F401 - 'beanie.operators.NotIn' imported but unused.

🔇 Additional comments (3)
state-manager/app/controller/get_runs.py (3)

33-87: Excellent optimization using bulk aggregation!

The refactoring from multiple per-run queries to a single bulk aggregation significantly reduces database round-trips from O(n) to O(1), which will dramatically improve performance for pages with many runs.


105-105: Verify the status logic change for empty runs.

The status logic has been changed from the original implementation. The new logic sets status to PENDING if there are pending states, otherwise FAILED if there are errors, otherwise SUCCESS. This differs from the original which returned FAILED for empty runs (total_count=0). Please confirm this behavior change is intentional, especially for runs with no states.

The original implementation had:

  • FAILED when total_count == 0 or errored_count > 0
  • SUCCESS when pending_count == 0
  • PENDING otherwise

Your implementation has:

  • PENDING when pending_count > 0
  • FAILED when errored_count > 0 (and pending_count == 0)
  • SUCCESS otherwise

This means runs with both pending and errored states will now show as PENDING instead of FAILED.


111-126: Good handling of runs without states.

The logic correctly handles runs that exist in the namespace but have no associated states, marking them as FAILED with zero counts. This maintains data integrity and provides a complete view of all runs.

- Updated the `get_runs` function to utilize MongoDB aggregation for enhanced performance in retrieving run statistics.
- Modified the total count calculation to directly query the database, ensuring accurate results when no runs are found.
- Refactored test cases to include new scenarios for handling empty results and verifying aggregation pipeline structure.
- Improved the overall clarity and organization of the test suite, ensuring comprehensive coverage of run status calculations and edge cases.
@codecov
Copy link

codecov bot commented Sep 3, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@NiveditJain NiveditJain merged commit d3cdb84 into exospherehost:main Sep 3, 2025
4 checks passed
@coderabbitai coderabbitai bot added the enhancement New feature or request label Sep 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Empty store throwing exception on Trigger state

1 participant