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

fix(bigquery): correctly format the scientific notation decimal #1068

Merged
merged 5 commits into from
Feb 25, 2025

Conversation

douenergy
Copy link
Contributor

@douenergy douenergy commented Feb 24, 2025

Fixes formatting issues in BigQuery when handling scientific notation decimals, ensuring accurate representation

Summary by CodeRabbit

  • Refactor
    • Enhanced numeric formatting in query responses for consistent display of zero and other values.
  • Tests
    • Added tests to verify correct handling of numeric data in query responses.
    • Improved tests ensuring accurate retrieval of CSV table columns.

Copy link

coderabbitai bot commented Feb 24, 2025

Walkthrough

This pull request restructures the value formatting logic in the _to_json_obj function by introducing a nested helper function, format_value, to handle floats and decimal.Decimal types. It also adds a new asynchronous test (test_scientific_notation) in the BigQuery router to verify that a zero value is properly formatted and modifies an existing test in the local file router to filter and select the intended CSV table by name.

Changes

File(s) Change Summary
ibis-server/app/util.py Updated _to_json_obj function to use a nested format_value helper that formats floats with nine significant digits and handles decimal.Decimal values by returning "0" for zero values.
ibis-server/tests/routers/v2/connector/test_bigquery.py
ibis-server/tests/routers/v2/connector/test_local_file.py
Added an asynchronous test (test_scientific_notation) to validate query output formatting and modified the CSV files listing test to filter for the table named "type-test-csv" for accurate column checks.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant QueryEndpoint
    participant Formatter
    Client->>QueryEndpoint: POST /query with SQL (CAST 0 AS col)
    QueryEndpoint->>Formatter: Process query result via _to_json_obj()
    Formatter->>Formatter: Call format_value (if type float/Decimal)
    Formatter-->>QueryEndpoint: Return formatted value ("0")
    QueryEndpoint-->>Client: Respond with 200 and JSON { data: [["0"]] }
Loading
sequenceDiagram
    participant TestSuite
    participant CSVHandler
    participant FileScanner
    TestSuite->>CSVHandler: Request list of CSV files
    CSVHandler->>FileScanner: Retrieve available CSV tables
    FileScanner-->>CSVHandler: Return list of tables
    CSVHandler->>CSVHandler: Filter for table "type-test-csv"
    CSVHandler-->>TestSuite: Return columns for the matched table
Loading

Possibly related PRs

Suggested reviewers

  • wwwy3y3

Poem

(_/)
( •_•) Hop through lines of code so bright,
Values now formatted, precise in sight.
Floats and decimals get a brand-new spin,
Tests ensure clean data flows within.
I’m a happy rabbit, with carrots in a row—
Hopping with joy as our improvements grow!


📜 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 1e7fa0b and 9342cf5.

📒 Files selected for processing (3)
  • ibis-server/app/util.py (1 hunks)
  • ibis-server/tests/routers/v2/connector/test_bigquery.py (1 hunks)
  • ibis-server/tests/routers/v2/connector/test_local_file.py (1 hunks)
🔇 Additional comments (3)
ibis-server/tests/routers/v2/connector/test_bigquery.py (1)

201-213: Appropriate test case for scientific notation decimal formatting

This test verifies that a numeric zero value is correctly formatted as "0" rather than a scientific notation string. It complements the changes made in the _to_json_obj function that properly handle zero decimal values.

ibis-server/tests/routers/v2/connector/test_local_file.py (1)

334-334: Good improvement to test reliability

This change increases test reliability by filtering for the specific table by name rather than assuming it's at a specific index. This makes the test more robust against changes in test data order.

ibis-server/app/util.py (1)

32-43: Fix for scientific notation decimal formatting

The refactoring of the formatting logic correctly handles the scientific notation issue with zero decimals by treating decimal zero as a special case and returning the string "0" directly.

However, there's a missed opportunity to implement error handling for extreme values as suggested in a previous review:

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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>, 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. (Beta)
  • @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.

@github-actions github-actions bot added bigquery ibis python Pull requests that update Python code labels Feb 24, 2025
@douenergy douenergy requested a review from goldmedal February 24, 2025 09:36
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

🧹 Nitpick comments (2)
ibis-server/tests/routers/v2/connector/test_bigquery.py (1)

201-213: Add more test cases for scientific notation handling.

While the test verifies basic numeric formatting, it would be beneficial to add more test cases covering:

  • Large numbers (e.g., 1e10)
  • Small numbers (e.g., 1e-10)
  • Numbers with significant decimal places
 async def test_scientific_notation(client, manifest_str):
     response = await client.post(
         url=f"{base_url}/query",
         json={
             "connectionInfo": connection_info,
             "manifestStr": manifest_str,
-            "sql": "SELECT cast(0 as numeric) as col",
+            "sql": """
+                SELECT
+                    cast(0 as numeric) as zero,
+                    cast(1e10 as numeric) as large_num,
+                    cast(1e-10 as numeric) as small_num,
+                    cast(123.456789 as numeric) as precise_num
+            """,
         },
     )
     assert response.status_code == 200
     result = response.json()
-    assert result["data"][0] == ["0.000"]
+    assert result["data"][0] == ["0.000", "10000000000.000", "0.000", "123.457"]
ibis-server/app/util.py (1)

32-38: Consider standardizing decimal place formatting.

The current implementation uses different formatting rules for float (9 significant digits) and decimal.Decimal (3 decimal places), which might lead to inconsistent output presentation.

Consider either:

  1. Standardizing both to use the same number of decimal places:
     data = df.map(
-        lambda x: f"{x:.9g}"
+        lambda x: f"{x:.3f}"
         if isinstance(x, float)
         else f"{x:.3f}"
         if isinstance(x, decimal.Decimal)
         else x
     ).to_dict(orient="split")
  1. Or making the precision configurable:
-def _to_json_obj(df: pd.DataFrame) -> dict:
+def _to_json_obj(df: pd.DataFrame, float_precision: int = 9, decimal_places: int = 3) -> dict:
     data = df.map(
-        lambda x: f"{x:.9g}"
+        lambda x: f"{x:.{float_precision}g}"
         if isinstance(x, float)
-        else f"{x:.3f}"
+        else f"{x:.{decimal_places}f}"
         if isinstance(x, decimal.Decimal)
         else x
     ).to_dict(orient="split")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 90cd416 and 2c64f6e.

📒 Files selected for processing (2)
  • ibis-server/app/util.py (1 hunks)
  • ibis-server/tests/routers/v2/connector/test_bigquery.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: ci

Comment on lines 32 to 38
data = df.map(
lambda x: f"{x:.9g}"
if isinstance(x, float)
else f"{x:.3f}"
if isinstance(x, decimal.Decimal)
else x
).to_dict(orient="split")
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

❓ Verification inconclusive

Add error handling for extreme values.

The current implementation might fail when handling very large or small numbers that could overflow the string formatting.

Add try-except block to handle potential overflow:

     data = df.map(
-        lambda x: f"{x:.9g}"
-        if isinstance(x, float)
-        else f"{x:.3f}"
-        if isinstance(x, decimal.Decimal)
-        else x
+        lambda x: (
+            try_format(x, "{:.9g}") if isinstance(x, float)
+            else try_format(x, "{:.3f}") if isinstance(x, decimal.Decimal)
+            else x
+        )
     ).to_dict(orient="split")

+def try_format(value, format_str: str) -> str:
+    try:
+        return format_str.format(value)
+    except (OverflowError, ValueError):
+        return str(value)

🏁 Script executed:

#!/bin/bash
# Description: Check if there are any existing test cases for extreme values
rg -A 5 "1e\+?[0-9]{3,}|1e-[0-9]{3,}" tests/

Length of output: 93


Action: Verify handling of extreme numerical values with proper error catching

The current implementation does not handle potential overflow errors when formatting very large or small floats and decimal values. I recommend wrapping the formatting logic in a try-except block (using a helper like try_format) to catch OverflowError and ValueError exceptions. Note that our exploratory test search did not locate any extreme value test cases (no tests folder found), so please verify manually that these scenarios are appropriately covered or add tests where needed.

Locations to address:

  • File: ibis-server/app/util.py (Lines 32-38)
  • Suggested diff:
         data = df.map(
    -        lambda x: f"{x:.9g}"
    -        if isinstance(x, float)
    -        else f"{x:.3f}"
    -        if isinstance(x, decimal.Decimal)
    -        else x
    +        lambda x: (
    +            try_format(x, "{:.9g}") if isinstance(x, float)
    +            else try_format(x, "{:.3f}") if isinstance(x, decimal.Decimal)
    +            else x
    +        )
         ).to_dict(orient="split")
    
    +def try_format(value, format_str: str) -> str:
    +    try:
    +        return format_str.format(value)
    +    except (OverflowError, ValueError):
    +        return str(value)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
data = df.map(
lambda x: f"{x:.9g}"
if isinstance(x, float)
else f"{x:.3f}"
if isinstance(x, decimal.Decimal)
else x
).to_dict(orient="split")
data = df.map(
lambda x: (
try_format(x, "{:.9g}") if isinstance(x, float)
else try_format(x, "{:.3f}") if isinstance(x, decimal.Decimal)
else x
)
).to_dict(orient="split")
def try_format(value, format_str: str) -> str:
try:
return format_str.format(value)
except (OverflowError, ValueError):
return str(value)

@douenergy douenergy marked this pull request as draft February 25, 2025 08:12
@douenergy douenergy marked this pull request as ready for review February 25, 2025 09:58
@douenergy
Copy link
Contributor Author

@goldmedal We still have BigQuery secret issue, but all test include bigquery pass on my local. So i think it is ready for reveiw.

Copy link
Contributor

@goldmedal goldmedal left a comment

Choose a reason for hiding this comment

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

Thanks @douenergy, it looks good to me.

@goldmedal goldmedal merged commit 850eba7 into Canner:main Feb 25, 2025
6 of 7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bigquery ibis python Pull requests that update Python code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants