Skip to content

Conversation

@clementsicard
Copy link
Contributor

@clementsicard clementsicard commented Jul 18, 2025

Description of the problem

  • If some failing data tests samples contain some Infinity values (possible in BigQuery, this is equivalent to float("inf"), then the generated output when serializing the fetched report data to JSON, then dumping it to elementary_output.json contains Infinity values, since allow_nan flag to json.dumps is True by default (see here).
  • The result is that the HTML report cannot interpret Infinity in the JSON, as it doesn't comply with the JSON specification
  • This leads to the generated HTML report appearing as empty because the embedded JSON cannot be successfully decoded.

Resolution

  • This PR introduces inf_and_nan_to_str, so that float("inf") gets turned into "Infinity" and float("nan") into "NaN" as a json_utils method (hopefully that is an appropriate location).
  • The method is called right before the json.dumps call.

Note

Note that we couldn't simply use a default= or cls= method in the dumps arg, something like

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, float):
            if math.isinf(obj):
                return "Infinity" if obj > 0 else "-Infinity"
            elif math.isnan(obj):
                return "NaN"
        return super().default(obj)

json_str = json.dumps(data, cls=CustomEncoder)

because the json modules intercepts these values and turns them into unquoted strings before the custom encoder can be applied...

Summary by CodeRabbit

  • New Features

    • Improved handling of special float values (Infinity, -Infinity, NaN) in data monitoring reports by converting them to string representations, ensuring successful JSON serialization.
  • Tests

    • Added a test to verify conversion of special float values to strings before JSON serialization.

@coderabbitai
Copy link

coderabbitai bot commented Jul 18, 2025

Walkthrough

A utility function was introduced to convert infinite and NaN float values to strings within data structures. This function is now used during report generation to ensure proper JSON serialization. Additionally, a unit test was added to demonstrate the function's behavior with various float values.

Changes

File(s) Change Summary
elementary/utils/json_utils.py Added inf_and_nan_to_str function to recursively convert inf/NaN floats to strings in data structures.
elementary/monitor/data_monitoring/report/data_monitoring_report.py Updated report generation to use inf_and_nan_to_str before JSON serialization of output data.
tests/unit/utils/test_dicts.py Added test function to demonstrate and verify the conversion of inf/NaN in a sample dictionary.

Poem

In data’s warren, floats may stray—
Infinity and NaN hop our way.
With a clever new utility,
They’re strings now, oh what agility!
Reports are safe, JSON’s neat,
This bunny’s code can’t be beat.
🐇


📜 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 5dff8c3 and 0d394f1.

📒 Files selected for processing (1)
  • tests/unit/utils/test_dicts.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/unit/utils/test_dicts.py
✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@github-actions
Copy link
Contributor

👋 @clementsicard
Thank you for raising your pull request.
Please make sure to add tests and document all user-facing changes.
You can do this by editing the docs files in this pull request.

@clementsicard clementsicard changed the title Fix float("inf") and float("nan") JSON serialization Fix float("inf") and float("nan") JSON serialization breaking reports Jul 18, 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: 1

🧹 Nitpick comments (1)
elementary/utils/json_utils.py (1)

84-84: Fix typo in docstring.

The docstring has a typo: "for" should be "and".

-    """Replaces occurrences of float("nan") for float("infinity") in the given dict object."""
+    """Replaces occurrences of float("nan") and float("infinity") in the given object."""

Note: Also consider updating "dict object" to just "object" since the function handles more than just dictionaries.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c07f8d6 and 5dff8c3.

📒 Files selected for processing (3)
  • elementary/monitor/data_monitoring/report/data_monitoring_report.py (2 hunks)
  • elementary/utils/json_utils.py (2 hunks)
  • tests/unit/utils/test_dicts.py (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
tests/unit/utils/test_dicts.py (1)
elementary/utils/json_utils.py (1)
  • inf_and_nan_to_str (83-97)
elementary/monitor/data_monitoring/report/data_monitoring_report.py (1)
elementary/utils/json_utils.py (1)
  • inf_and_nan_to_str (83-97)
🔇 Additional comments (3)
elementary/utils/json_utils.py (1)

83-97: Well-implemented utility function with correct logic.

The function properly handles the recursive traversal of data structures and correctly identifies and converts infinity and NaN values to their string representations. The use of numpy's isinf() and isnan() functions ensures reliable detection of these special float values.

elementary/monitor/data_monitoring/report/data_monitoring_report.py (2)

24-24: Proper import addition for the utility function.

The import is correctly placed and follows the existing import organization.


78-78: Excellent integration of the utility function.

The placement of json_utils.inf_and_nan_to_str(output_data) before JSON serialization is perfect. This ensures that any infinity or NaN values in the report data are converted to strings, preventing the JSON serialization issues described in the PR objectives.

@clementsicard clementsicard temporarily deployed to elementary_test_env July 18, 2025 13:22 — with GitHub Actions Inactive
@arbiv arbiv self-requested a review July 23, 2025 09:36
@arbiv arbiv merged commit 8e97187 into elementary-data:master Jul 23, 2025
4 checks passed
@arbiv
Copy link
Contributor

arbiv commented Jul 23, 2025

Thanks @clementsicard! Merging :)

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.

2 participants