Skip to content

perf: don't construct a tokio runtime for each query #1226

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 8, 2025

Conversation

de-sh
Copy link
Contributor

@de-sh de-sh commented Mar 6, 2025

Fixes #XXXX.

Description


This PR has:

  • been tested to ensure log ingestion and log query works.
  • added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
  • added documentation for new or modified features or behaviors.

Summary by CodeRabbit

  • New Features

    • Extended the public interface to support direct streaming, offering more precise notifications when a data stream is unavailable.
    • Introduced a new error variant, StreamNotFound, for enhanced error reporting related to stream retrieval issues.
  • Refactor

    • Streamlined query execution by shifting to fully asynchronous processing, reducing overhead and complexity.
    • Unified error handling for clearer and faster responses during query operations.
    • Simplified control flow in alert handling by improving stream name retrieval logic.
    • Enhanced data retrieval by utilizing time partitions for more accurate data access.

Copy link

coderabbitai bot commented Mar 6, 2025

Walkthrough

This pull request refactors the query execution flow across multiple modules. The changes remove the use of blocking tasks in favor of direct asynchronous calls. In the airplane and HTTP handlers, the query execution now obtains a stream directly from a central parser module and executes queries asynchronously with improved error handling. Additionally, the public interface is expanded with a new Stream export, and the Query.execute method signature is updated to use a reference to a Stream instead of a string.

Changes

File(s) Change Summary
src/handlers/airplane.rs, src/handlers/http/query.rs Refactored query execution: Removed blocking tasks and redundant match statements; directly obtain streams via PARSEABLE.get_stream; removed execute_query function; added StreamNotFound error variant for granular error handling.
src/query/mod.rs Introduced new asynchronous execute function; updated Query.execute and get_dataframe signatures to accept Option<&String> for time partitions; streamlined logic for obtaining time partitions.
src/parseable/mod.rs Expanded public exports to include the Stream type from the streams module.
src/alerts/alerts_utils.rs, src/alerts/mod.rs Introduced time_partition variable for data retrieval; added StreamNotFound variant to AlertError enum; simplified control flow for stream name retrieval.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant AirService
    participant Parseable
    participant Query

    Client->>AirService: GET query request
    AirService->>Parseable: get_stream(stream_name)
    Parseable-->>AirService: stream / error
    AirService->>Query: query.execute(&stream)
    Query->>stream: get_time_partition()
    Query-->>AirService: results / error
    AirService-->>Client: response
Loading

Suggested labels

for next release

Suggested reviewers

  • nikhilsinhaparseable

Poem

I'm a rabbit, hopping through the code,
Dropping blocks for streams down the road.
Queries flow swift and oh so light,
With each byte, I leap with delight.
Carrots & code — together, we unite!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

@de-sh de-sh marked this pull request as ready for review March 6, 2025 18:48
coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 6, 2025
Copy link

@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: 0

🧹 Nitpick comments (2)
src/alerts/alerts_utils.rs (1)

34-34: Avoid potential confusion with global usage
By referencing PARSEABLE directly, you rely on a global context, which may make testing or concurrency more complex. Consider documenting concurrency safety or injecting dependencies if feasible.

src/query/mod.rs (1)

65-77: Dedicated async runtime for queries
Providing a specialized QUERY_RUNTIME can improve performance and isolation for query processing. Ensure it does not conflict with any existing runtime usage within your application.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 868ada3 and f55dee4.

📒 Files selected for processing (6)
  • src/alerts/alerts_utils.rs (2 hunks)
  • src/alerts/mod.rs (4 hunks)
  • src/handlers/airplane.rs (2 hunks)
  • src/handlers/http/query.rs (3 hunks)
  • src/parseable/mod.rs (1 hunks)
  • src/query/mod.rs (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/handlers/airplane.rs
  • src/parseable/mod.rs
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: coverage
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
🔇 Additional comments (13)
src/alerts/alerts_utils.rs (1)

141-143: Time partition usage is consistent
Retrieving time_partition from the stream ensures precise data filtering. This approach is consistent with the rest of the code for retrieving time-based partitions.

src/handlers/http/query.rs (3)

42-44: New imports for streamlined error handling and query execution
Importing StreamNotFound, PARSEABLE, and execute is a clear approach, aligning with the new asynchronous query strategy.


133-134: Switch to the new execute function
Replacing the old blocking query approach with execute(query, &table_name).await? improves performance by leveraging the dedicated async runtime.


322-323: Extended error types
The addition of StreamNotFound to QueryError improves clarity when indicating that a stream was not located.

src/alerts/mod.rs (3)

40-40: Introduced global reference for parseable
Importing PARSEABLE and StreamNotFound ensures consistent usage of the global context and specialized error in the alerts system.


706-707: New StreamNotFound variant
Defining a dedicated error variant clarifies potential missing stream issues within the alerts module.


721-721: Specific HTTP status for missing streams
Mapping StreamNotFound to NOT_FOUND status code provides precise error responses for clients.

src/query/mod.rs (6)

45-45: Add Runtime import
Importing tokio::runtime::Runtime is crucial for creating the dedicated query execution environment.


150-150: Revised signature for execute
Allowing an optional time_partition reference clarifies partition usage, enabling fallback behavior if no partition is provided.


173-176: get_dataframe with optional time partition
This adaptation ensures consistent interface design across the module, especially for partition-based queries.


185-185: final_logical_plan now supports optional partition
Extending the function signature to accept Option<&String> aligns with the rest of the code handling partitions gracefully.


505-506: transform function parameter
By passing Option<&String> for the partition, the code can branch between a custom partition key and the default timestamp key.


563-563: table_contains_any_time_filters includes optional partition
Recognizing both user-specified partition and default timestamp is essential for correct filter application.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 7, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 7, 2025
Signed-off-by: Devdutt Shenoi <devdutt@outlook.in>
Copy link

@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: 0

🧹 Nitpick comments (1)
src/query/mod.rs (1)

69-80: Consider handling the JoinError instead of using expect.

The implementation correctly spawns query execution on the dedicated runtime. However, the .expect("The Join should have been successful") on line 79 could lead to a panic if the spawned task fails. Consider handling this error case more gracefully.

pub async fn execute(
    query: Query,
    stream_name: &str,
) -> Result<(Vec<RecordBatch>, Vec<String>), ExecuteError> {
    let time_partition = PARSEABLE.get_stream(stream_name)?.get_time_partition();
    QUERY_RUNTIME
        .spawn(async move { query.execute(time_partition.as_ref()).await })
        .await
-        .expect("The Join should have been successful")
+        .map_err(|e| ExecuteError::Datafusion(DataFusionError::Execution(format!("Join error: {}", e))))?
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ad7b48 and ec21e29.

📒 Files selected for processing (1)
  • src/query/mod.rs (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: coverage
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
🔇 Additional comments (6)
src/query/mod.rs (6)

64-66: Good initialization of a dedicated runtime for queries.

The static runtime provides a single, shared Tokio runtime for all queries, which aligns with the PR's objective of avoiding runtime creation for each query. The use of Lazy::new() ensures the runtime is only initialized once when needed.


151-154: Signature change aligns with the centralized runtime approach.

The method now accepts a reference to a time partition instead of a stream name string, which fits well with the new architecture where time partition resolution happens in the outer execute function. This change helps avoid redundant work.


176-179: Consistent parameter changes to support the new approach.

The get_dataframe method has been updated to match the pattern used in execute, accepting a time partition reference instead of a stream name. This ensures consistency across the API and supports the centralized time partition resolution.


188-188: Parameter type simplification is appropriate.

Changed from taking a reference to an Option to directly taking an Option of a reference, which is a more ergonomic approach and aligns with the parameter changes in other methods.


504-509: Parameter type consistency maintained throughout codebase.

The transform function's signature has been updated to match the changes in related functions, ensuring consistency across the module. This type of parameter is more efficient as it avoids unnecessary cloning.


564-567: Simplified time_partition check with is_some_and.

The code now uses is_some_and for a more concise check against the time partition field. This improves readability while maintaining functionality.

Also applies to: 580-581

Copy link
Contributor

@nikhilsinhaparseable nikhilsinhaparseable left a comment

Choose a reason for hiding this comment

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

looks good

@nitisht nitisht merged commit 824f642 into parseablehq:main Mar 8, 2025
14 checks passed
@de-sh de-sh deleted the fix-multi-threading branch March 9, 2025 12:30
This was referenced Mar 28, 2025
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