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 + test: query response serialization #1165

Open
wants to merge 9 commits into
base: main
Choose a base branch
from

Conversation

de-sh
Copy link
Contributor

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

Fixes #XXXX.

Description

Improves the testability of QueryResponse


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
    • Introduced a revamped JSON output method for query results, offering flexible representation with options for including fields and handling null values.
  • Bug Fixes
    • Enhanced error handling ensures consistent response status codes for various error scenarios, including new error types.
  • Tests
    • Added comprehensive tests to validate the new JSON conversion under different conditions.
  • Chores
    • Removed legacy JSON conversion functionality to streamline response generation.

Copy link

coderabbitai bot commented Feb 13, 2025

Walkthrough

The changes update the error handling and response formatting in the query handling and response generation logic. A new error variant for Arrow errors is introduced in the QueryError enum, alongside a refined handling for JSON errors. The response method has shifted from HTTP to direct JSON conversion in the QueryResponse struct. Additionally, the utility functions for JSON conversion in Arrow have been modified to align with the new error handling approach.

Changes

File(s) Change Summary
src/handlers/http/query.rs Added ArrowError import and new Arrow variant to the QueryError enum; replaced the JsonParse variant with a general Json variant; updated status_code to include both Json and Arrow errors; renamed timing variable and added debug logging; updated response conversion call from to_http() to to_json().
src/response.rs Replaced the to_http() method with a new to_json() method in QueryResponse, which converts records directly to JSON format; updated handling of null values and output structure; removed the old HTTP response logic.
src/utils/arrow/mod.rs Updated record_batches_to_json return type to arrow::error::Result; simplified return type of add_parseable_fields function; added comments for potential optimizations.

Possibly related PRs

  • refactor: use appropriate error types #1201: The changes in the main PR are related to the modifications in the error handling mechanisms, specifically the introduction of the Arrow variant in the QueryError enum.
  • perf: don't construct a tokio runtime for each query #1226: The changes in the main PR, particularly the updates to the QueryError enum, are related to the modifications in the retrieved PR that also involve the QueryError enum and the execution of queries.
  • feat: prism post datasets API #1236: The changes in the main PR, specifically the modifications to the to_json() method in src/response.rs, are directly related to the changes in the retrieved PR, which also involves the to_json() method and its handling of JSON responses.

Suggested labels

for next release

Suggested reviewers

  • nikhilsinhaparseable

Poem

I’m a rabbit in the codey glade,
Hopping through changes in a merry parade.
Errors now sparkle with clarity anew,
Logging and JSON flow fresh as dew.
With Arrow and JSON, bugs take their leave—
In fields of code, I joyfully weave!
🥕🐇 Happy coding!

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

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/response.rs (2)

31-59: Potential performance improvements
Writing entire RecordBatch data into a single in-memory buffer with arrow_json::ArrayWriter may become memory-intensive for large result sets. Consider a streaming or chunk-based approach if you anticipate very large batches. Also note that setting fill_null to true will require iterating over all objects to find missing fields, which can increase overhead.


62-219: Great test coverage
These tests thoroughly cover multiple scenarios, including handling of null values, empty batches, and field inclusion. However, there is repeated code for creating record batches. Consider refactoring common setup steps into a helper function to reduce duplication.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 20e66a4 and 00d790a.

📒 Files selected for processing (3)
  • src/handlers/http/query.rs (6 hunks)
  • src/response.rs (2 hunks)
  • src/utils/arrow/mod.rs (0 hunks)
💤 Files with no reviewable changes (1)
  • src/utils/arrow/mod.rs
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Build Default x86_64-pc-windows-msvc
  • GitHub Check: Build Default aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-apple-darwin
  • GitHub Check: Build Default aarch64-unknown-linux-gnu
  • GitHub Check: Build Kafka aarch64-apple-darwin
  • GitHub Check: Build Default x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Distributed deployments
  • GitHub Check: Build Kafka x86_64-unknown-linux-gnu
  • GitHub Check: Quest Smoke and Load Tests for Standalone deployments
  • GitHub Check: coverage
🔇 Additional comments (8)
src/response.rs (2)

19-19: No issues
The newly added import for QueryError looks correct.


21-21: Imports for JSON are appropriate
No concerns with the added serde_json imports.

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

22-22: Explicit import
Introducing ArrowError is consistent with the new Arrow error variant.


35-35: New debug logging
No concerns with adding error and debug from tracing.


105-105: Accurate timing logs for quick count queries
Recording and logging elapsed time here is beneficial for performance monitoring.

Also applies to: 126-132


143-143: End-to-end timing for standard queries
Consistent usage of timing metrics here as well ensures comprehensive performance tracking.

Also applies to: 145-145, 150-152


318-321: Enhanced error handling
Adding Arrow and Json variants to QueryError clearly distinguishes error origins and improves debuggability.


327-329: Status code alignment
Treating QueryError::Json and QueryError::Arrow as internal server errors follows the existing pattern for Execute errors and keeps error handling consistent.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 13, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 14, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 18, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 24, 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/response.rs (2)

31-54: Consider adding error handling documentation

The to_json method propagates errors from the record_batches_to_json function, but there's no documentation about what specific error types might be returned. Consider adding documentation that explains the potential error scenarios.

 /// Convert into a JSON response
+/// 
+/// # Errors
+/// 
+/// Returns a `QueryError` if:
+/// - There's an error converting the record batches to JSON (Arrow error)
+/// - JSON serialization fails
 pub fn to_json(&self) -> Result<Value, QueryError> {

32-54: Consider adding support for custom null value representation

The method currently uses Value::Null for missing fields when fill_null is true. Consider extending this functionality to allow clients to specify a custom representation for null values (e.g., empty string, zero, etc.) which could be useful for certain data processing pipelines.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7cd9536 and 184b208.

📒 Files selected for processing (2)
  • src/response.rs (2 hunks)
  • src/utils/arrow/mod.rs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/utils/arrow/mod.rs
🧰 Additional context used
🧬 Code Definitions (1)
src/response.rs (2)
src/handlers/http/query.rs (1)
  • query (70-154)
src/utils/arrow/mod.rs (1)
  • record_batches_to_json (52-66)
🔇 Additional comments (11)
src/response.rs (11)

21-22: Updated import statements to align with new implementation

The imports have been updated to directly use serde_json::Value and the record_batches_to_json utility function, which is appropriate for the new JSON-focused implementation.


32-34: New to_json method correctly converts QueryResponse to serializable JSON

The method appropriately handles the conversion of Arrow RecordBatch data to JSON through the record_batches_to_json utility function. The return type of Result<Value, QueryError> is well-suited for JSON serialization, allowing for proper error propagation.


37-40: Null value handling is implemented correctly

When fill_null is true, the code properly iterates through each JSON object and ensures that any missing field gets a Value::Null entry. This maintains data consistency for clients expecting all fields to be present.


44-51: Response structure correctly implements the configured output format

The logic to conditionally include fields with the records (when with_fields is true) or return just the records is well-implemented. The use of json! macro ensures proper serialization of both formats.


57-66: Well-organized test module setup

The test module is properly structured with appropriate imports, including all the necessary Arrow types for comprehensive testing.


67-77: Test for empty record batches is comprehensive

This test correctly verifies that empty record batches convert to an empty array in JSON format, which is an important edge case to handle.


79-108: Thorough test for basic record batch conversion

The test creates a diverse set of data types (integers, floats, and strings) to ensure proper JSON conversion for various data types. The assertions correctly verify that the structure and values match the expected JSON output.


110-142: Test for including fields in the output is well-implemented

This test properly verifies the behavior when with_fields is set to true, ensuring that both the fields array and records are included in the response as expected.


144-177: Test for handling record batches with nullable fields correctly verifies behavior

This test thoroughly validates that nullable fields are handled correctly when fill_null is false. The test creates records with null values in the string array and verifies that these fields are omitted from the JSON output, which is the expected behavior.


179-211: Test for null value filling is comprehensive

This test validates that when fill_null is set to true, null values are explicitly included in the JSON output rather than being omitted. The assertion correctly checks for the presence of explicit null values in the output.


33-35:

❓ Verification inconclusive

Verify error propagation from record_batches_to_json

The code now directly propagates errors from record_batches_to_json with the ? operator, but it's not clear how Arrow errors are mapped to QueryError. Ensure the QueryError enum has been updated to handle Arrow errors appropriately.


🏁 Script executed:

#!/bin/bash
# Check if QueryError has been updated to handle Arrow errors
rg -A 20 "pub enum QueryError" --type rust

Length of output: 1325


Clarify error mapping for Arrow errors

The updated code now uses the ? operator to propagate errors from record_batches_to_json as-is. Please verify that any errors it may return—particularly those stemming from Arrow operations—are correctly converted into the appropriate QueryError. Currently, the QueryError enum (defined in src/handlers/http/query.rs) includes a variant for DataFusionError (with a #[from] conversion), which may already cover Arrow-related errors (if they are wrapped in a DataFusionError). However, if record_batches_to_json can yield errors that aren’t encapsulated by DataFusionError, an explicit mapping (or a new QueryError variant) might be needed.

  • Confirm that record_batches_to_json returns errors convertible into QueryError (e.g., via DataFusionError).
  • Update QueryError to handle direct Arrow errors if such cases exist.

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.

1 participant