Skip to content
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

refactor: promql engine to load data in steps #3783

Merged
merged 17 commits into from
Jun 24, 2024
Merged

refactor: promql engine to load data in steps #3783

merged 17 commits into from
Jun 24, 2024

Conversation

taimingl
Copy link
Collaborator

@taimingl taimingl commented Jun 20, 2024

While previous pr #3736 improved both memory/throughput for aggregation, binary, and unary PromQL queries by loading only necessary columns into memory. Other queries still load the entire parquet file, resulting in high memory usage and slow throughput.

This pr breaks the data loading process into two steps by utilizing __hash__ columns.

  1. find the unique combinations of __hash__ and all k-v pairs of labels
  2. load only __hash__, _timestamp, and value columns into memory for querying

This will greatly improve the performance for vector/matrix selector queries.

Simple metric selector query, e.g. container_memory_usage_bytes

Before

time range | fetching ms | processing ms | total ms
1 days     | 552         | 61            | 603
2 days     | 1075        | 140           | 1215
7 days     | 7666        | 540           | 8206
2 weeks    | too long
1 month    | too long

After

time range | step1  | step2 | process2 | step3 | process3  | total
1 days     | 38     | 162   | 1        | 74    | 31        | 309
2 days     | 56     | 197   | 1        | 134   | 60        | 450
7 days     | 104    | 447   | 3        | 556   | 233       | 1345
2 weeks    | 100    | 706   | 9        | 1103  | 432       | 2351
1 month    | 185    | 1529  | 16       | 2436  | 1003      | 5170

Aggregation query, e.g. max by (node) (container_memory_usage_bytes) raised by #3091

Before

time range | max_mem_usage | fetching ms | processing ms | total ms
1 days     | 569mb         | 119         | 62            | 182
2 days     | 852mb         | 219         | 124           | 343
7 days     | 2.9g          | 820         | 488           | 1308
2 weeks    | 4.5g          | 1491        | 842           | 2333
1 month    | 8.9g          | 3498        | 1851          | 5349

After

time range | max_mem_usage | step1  | step2 | process2 | step3 | process3  | total
1 days     | 499mb         | 28     | 19    | 0        | 61    | 60        | 169
2 days     | 714mb         | 41     | 51    | 0        | 127   | 60        | 282
7 days     | 2.1g          | 65     | 123   | 0        | 542   | 227       | 960
2 weeks    | 3.2g          | 93     | 267   | 0        | 1038  | 426       | 1826
1 month    | 6.7g          | 175    | 412   | 2        | 2478  | 1074      | 4142

PromQL compliance result

================================================================================
General query tweaks:
*  Openobserve is sometimes off by 1ms when parsing floating point start/end timestamps.
*  Openobserve fractional tolerance amount for <agg>_over_time queries
================================================================================
Total: 538 / 548 (98.18%) passed, 0 unsupported

Summary by CodeRabbit

  • New Features

    • Improved data aggregation, filtering, and selection logic for metrics retrieval, enhancing performance and accuracy.
  • Refactor

    • Renamed constant LE_LABEL to BUCKET_LABEL to improve clarity in histogram processing.
    • Simplified and refined column filtering logic to streamline data processing.
  • Improvements

    • Enhanced handling of modifiers and column filters for better data processing efficiency.

Copy link

coderabbitai bot commented Jun 20, 2024

Walkthrough

The updates primarily involve refinements to data processing logic in a Rust project using DataFusion, including enhanced data aggregation, filtering, and selection mechanisms for metrics retrieval. Additionally, there are adaptations in how histogram bucket labels are handled and a renaming of constants for improved readability.

Changes

Files Change Summary
src/service/promql/engine.rs Modified data aggregation, filtering, and selection processes. Refined column and modifier handling.
src/common/meta/prom.rs Renamed constant LE_LABEL to BUCKET_LABEL.
src/service/promql/functions/histogram.rs Updated histogram bucket label handling to use BUCKET_LABEL.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

@taimingl taimingl marked this pull request as ready for review June 20, 2024 18:49
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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e7a158e and 0870f42.

Files selected for processing (1)
  • src/service/promql/engine.rs (4 hunks)
Additional context used
Path-based instructions (1)
src/service/promql/engine.rs (1)

Pattern **/*.rs: You are a smart rustlang pull request reviewer.
You are going to review all the rustlang files.
Be concise, and add a brief explanation to your suggestions

Make sure the responses are not too verbose and keep the suggestions to the point i.e. actionable.

Additional comments not posted (3)
src/service/promql/engine.rs (3)

25-25: Ensure that the newly introduced max function is utilized appropriately in the context of aggregations or wherever maximum values are needed.


1134-1188: The logic for filtering and aggregating data appears to be correct. However, consider optimizing the data retrieval and processing by reducing the number of clones and potentially caching frequently accessed data.
[REFACTOR_SUGGESTion]

// Possible optimization by reducing clones and using more efficient data structures or caching mechanisms.

Line range hint 1219-1252: This batch processing section is critical for performance. Ensure that the sorting and filtering operations are optimized for large datasets. Consider using more efficient data structures or algorithms if performance issues arise.

src/service/promql/engine.rs Show resolved Hide resolved
src/service/promql/engine.rs Show resolved Hide resolved
src/service/promql/engine.rs Show resolved Hide resolved
src/service/promql/engine.rs Outdated Show resolved Hide resolved
src/service/promql/engine.rs Outdated Show resolved Hide resolved
src/service/promql/engine.rs Outdated Show resolved Hide resolved
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: 1

Outside diff range and nitpick comments (1)
src/service/promql/engine.rs (1)

47-48: Clarify the purpose of col_filters.

Consider adding a comment explaining the role of col_filters in the context of the Engine struct, especially since it plays a crucial role in the new data loading strategy.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0870f42 and 1f87ce4.

Files selected for processing (1)
  • src/service/promql/engine.rs (9 hunks)
Additional context used
Path-based instructions (1)
src/service/promql/engine.rs (1)

Pattern **/*.rs: You are a smart rustlang pull request reviewer.
You are going to review all the rustlang files.
Be concise, and add a brief explanation to your suggestions

Make sure the responses are not too verbose and keep the suggestions to the point i.e. actionable.

Additional comments not posted (5)
src/service/promql/engine.rs (5)

25-25: Refactor import statement for clarity.

The import line includes max which is a new addition. Make sure it's used appropriately in the context of the file.


92-104: Optimize the handling of column filters.

The logic for extending col_filters based on VectorMatchCardinality and BinModifier is clear and seems efficient. However, ensure that the performance implications of dynamically modifying col_filters during query parsing are well-understood and documented.


1069-1082: Optimize label column handling.

The extraction of label columns could potentially be optimized. Consider caching commonly used label columns or reusing them across different parts of the code to avoid repeated schema lookups.
[REFACTOR_Suggestion]

- let label_cols = df_group
-     .schema()
-     .fields()
-     .iter()
-     .filter_map(|field| {
-         let name = field.name();
-         if name == &cfg.common.column_timestamp || name == VALUE_LABEL {
-             None
-         } else {
-             Some(col(name))
-         }
-     })
-     .collect::<Vec<_>>();
+ // Example refactor to cache label columns
+ static LABEL_COLS: OnceCell<Vec<_>> = OnceCell::new();
+ let label_cols = LABEL_COLS.get_or_init(|| {
+     df_group
+         .schema()
+         .fields()
+         .iter()
+         .filter_map(|field| {
+             let name = field.name();
+             if name != &cfg.common.column_timestamp && name != VALUE_LABEL {
+                 Some(col(name))
+             } else {
+                 None
+             }
+         })
+         .collect::<Vec<_>>()
+ });

138-144: Review the clearing of col_filters.

Clearing col_filters in certain cases (like topk and bottomk queries) could lead to unintended side effects if not handled carefully. Verify that this behavior is intended and test for edge cases where this might lead to incorrect data filtering.

Verification successful

Clearing of col_filters is correctly handled.

The eval_top function, which is used by both topk and bottomk, processes the cleared col_filters by applying the appropriate label modifiers (Include and Exclude). This ensures that the intended behavior is maintained and no unintended side effects occur.

  • src/service/promql/engine.rs: Lines 138-144
  • src/service/promql/aggregations/mod.rs: eval_top function
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify edge cases for clearing col_filters in topk and bottomk queries.
# Test: Search for usages of topk and bottomk to ensure they handle the clear operation correctly.
rg --type rust $'token::T_TOPK | token::T_BOTTOMK'

Length of output: 257



Script:

#!/bin/bash
# Extract lines around the identified usages of token::T_TOPK and token::T_BOTTOMK to understand the context
rg --type rust -A 10 -B 10 'token::T_TOPK | token::T_BOTTOMK' src/service/promql/engine.rs

Length of output: 2109



Script:

#!/bin/bash
# Search for the implementations of aggregations::topk and aggregations::bottomk
rg --type rust 'fn topk' --context 10
rg --type rust 'fn bottomk' --context 10

Length of output: 2702



Script:

#!/bin/bash
# Search for the implementation of eval_top to understand how it handles the cleared col_filters
rg --type rust 'fn eval_top' --context 10

Length of output: 1348



Script:

#!/bin/bash
# Extract the complete implementation of eval_top function to understand its handling of col_filters
rg --type rust -A 50 'fn eval_top' src/service/promql/aggregations/mod.rs

Length of output: 1886


1040-1058: Ensure selected columns are necessary.

The selection of columns based on col_filters is a critical operation. Double-check that all necessary columns (HASH_LABEL, cfg.common.column_timestamp, VALUE_LABEL) are indeed required and used efficiently in subsequent operations.

Verification successful

Selected columns are necessary and used.

The columns HASH_LABEL, cfg.common.column_timestamp, and VALUE_LABEL are indeed used extensively throughout the codebase. The search results confirm their necessity in various operations across multiple modules.

  • HASH_LABEL is used in src/service/promql/engine.rs, src/service/metrics/mod.rs, and other files.
  • cfg.common.column_timestamp is used in src/service/promql/engine.rs, src/service/schema.rs, and numerous other files.
  • VALUE_LABEL is used in src/service/promql/engine.rs, src/service/metrics/prom.rs, and several other files.

These usages indicate that the selected columns are integral to the functioning of the system.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify that selected columns are used in subsequent operations.
# Test: Search for usages of the selected columns to ensure they are necessary.
rg --type rust $'HASH_LABEL|cfg.common.column_timestamp|VALUE_LABEL'

Length of output: 14348

src/service/promql/engine.rs Show resolved Hide resolved
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1f87ce4 and 977f64d.

Files selected for processing (1)
  • src/service/promql/engine.rs (9 hunks)
Additional context used
Path-based instructions (1)
src/service/promql/engine.rs (1)

Pattern **/*.rs: You are a smart rustlang pull request reviewer.
You are going to review all the rustlang files.
Be concise, and add a brief explanation to your suggestions

Make sure the responses are not too verbose and keep the suggestions to the point i.e. actionable.

Additional comments not posted (11)
src/service/promql/engine.rs (11)

25-25: Import optimally utilized.

The addition of max function from DataFusion's prelude aligns with the changes in the aggregation methods in this file.


47-48: Clarification on column filters.

The comment on line 47 has been simplified to directly reflect the purpose of col_filters. This change improves code readability and understanding.


57-57: Initialization of col_filters.

Initializing col_filters with an empty HashSet is appropriate here, ensuring that no columns are filtered unless specified later in the code.


93-110: Refinement in column extraction logic.

The logic for extracting columns based on binary expression modifiers has been refined. The handling of group_left with labels is particularly noteworthy, ensuring only specified labels are selected. This is crucial for performance and correctness in data querying.


144-150: Simplification of column filtering logic.

The clearing of col_filters for specific operations like topk and bottomk ensures that all columns are considered during these operations, which is necessary for their correct execution. This change simplifies and clarifies the behavior.


1046-1065: Optimized column selection.

The logic for including only necessary columns (__hash__, _timestamp, value) and any additional specified labels is a critical optimization. This prevents unnecessary data loading and processing, aligning with the PR's goal of improving performance.


1075-1087: Efficient label column handling.

The method for filtering out timestamp and value columns when collecting label columns is efficient and prevents redundancy. This contributes to the streamlined processing of data.


1089-1097: Aggregation logic for timestamp.

The use of the max function to aggregate timestamps is a smart choice, ensuring that only the most recent timestamps are processed further. This is an effective use of DataFusion's capabilities.


1119-1125: Filter application in data selection.

Applying a filter based on the most recent timestamps to fetch relevant series data is a crucial step that ensures efficiency in data handling and aligns with the overall optimization goals of the PR.


1135-1157: Hash-based data filtering and label management.

The logic to filter data based on hash values and to manage labels efficiently ensures that only relevant data is processed. This is essential for performance and memory usage optimization.


1185-1190: Efficient sample appending.

Appending samples based on hash values directly into the corresponding RangeValue is an efficient way to handle incoming data streams. This method minimizes overhead and aligns with the performance objectives.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 977f64d and da0457e.

Files selected for processing (1)
  • src/service/promql/engine.rs (9 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/service/promql/engine.rs

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between da0457e and 925a54a.

Files selected for processing (1)
  • src/service/promql/engine.rs (9 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/service/promql/engine.rs

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 925a54a and c31abcc.

Files selected for processing (1)
  • src/service/promql/engine.rs (9 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/service/promql/engine.rs

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c31abcc and f3581b2.

Files selected for processing (1)
  • src/service/promql/engine.rs (8 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/service/promql/engine.rs

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f3581b2 and 51461a0.

Files selected for processing (3)
  • src/common/meta/prom.rs (1 hunks)
  • src/service/promql/engine.rs (8 hunks)
  • src/service/promql/functions/histogram.rs (2 hunks)
Files skipped from review due to trivial changes (1)
  • src/common/meta/prom.rs
Files skipped from review as they are similar to previous changes (1)
  • src/service/promql/engine.rs
Additional context used
Path-based instructions (1)
src/service/promql/functions/histogram.rs (1)

Pattern **/*.rs: You are a smart rustlang pull request reviewer.
You are going to review all the rustlang files.
Be concise, and add a brief explanation to your suggestions

Make sure the responses are not too verbose and keep the suggestions to the point i.e. actionable.

Additional comments not posted (2)
src/service/promql/functions/histogram.rs (2)

20-20: Update to constants is consistent with project-wide changes.

The renaming of LE_LABEL to BUCKET_LABEL across the project is reflected here, ensuring consistency.


70-70: Proper error handling for bucket label parsing.

The use of match for error handling when parsing the BUCKET_LABEL value is idiomatic in Rust and ensures that the loop continues smoothly in case of parsing errors.

src/service/promql/functions/histogram.rs Show resolved Hide resolved
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 51461a0 and fc9780b.

Files selected for processing (1)
  • src/service/promql/engine.rs (8 hunks)
Files skipped from review as they are similar to previous changes (1)
  • src/service/promql/engine.rs

@taimingl taimingl merged commit 9baa5cd into main Jun 24, 2024
21 of 23 checks passed
@taimingl taimingl deleted the refactor/promql3 branch June 24, 2024 16:51
@hengfeiyang
Copy link
Contributor

fixed #2710

taimingl added a commit that referenced this pull request Jul 12, 2024
This pr breaks the data loading process into two steps by utilizing
`__hash__` columns.
1. find the unique combinations of `__hash__` and all k-v pairs of
labels
2. load only `__hash__`, `_timestamp`, and `value` columns into memory
for querying

---------

Co-authored-by: Hengfei Yang <hengfei.yang@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants