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

Fallback to textdiffer when csv parsing fails #5876

Merged
merged 4 commits into from
Oct 21, 2024
Merged

Fallback to textdiffer when csv parsing fails #5876

merged 4 commits into from
Oct 21, 2024

Conversation

jorg-vr
Copy link
Contributor

@jorg-vr jorg-vr commented Oct 18, 2024

This pull request lets the differ fallback to the Textdiffer in case the csv is malformed.

This issue was detected by submissions from the postgres judge, which returned to many escaping characters before a newline for a while. This issue is already resolved in the judge as well.

Example of a problematic submission: https://dodona.be/en/submissions/19072577.json

  • Tests were added

@jorg-vr jorg-vr added the bug Something isn't working label Oct 18, 2024
@jorg-vr jorg-vr self-assigned this Oct 18, 2024
Copy link

coderabbitai bot commented Oct 18, 2024

Walkthrough

The pull request introduces modifications to the FeedbackTableRenderer class, specifically enhancing the handling of differencing classes based on test result formats. The method differ(t) has been removed and replaced with with_differ_class(t), which includes error handling for malformed CSV data. Additionally, the SubmissionsControllerTest class has been enhanced with new tests to validate the rendering of SQL query submissions, including a test for handling malformed CSV submissions.

Changes

File Change Summary
app/helpers/renderers/feedback_table_renderer.rb - Removed method differ(t).
- Added method with_differ_class(t) for handling differencing classes.
- Updated method signatures for test_accepted(t) and diff(t) to use the new differencing logic.
test/controllers/submissions_controller_test.rb - Added tests for rendering submissions with specific SQL query results, including a test for handling malformed CSV data.

Possibly related PRs

  • Add csv differ support for empty rows #5864: The changes in the CsvDiffer class regarding handling empty rows in CSV files are related to the main PR's updates in error handling for malformed CSV data, as both involve improving the robustness of CSV processing.

Suggested reviewers

  • bmesuere

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

🧹 Outside diff range and nitpick comments (1)
app/helpers/renderers/feedback_table_renderer.rb (1)

325-328: Consider logging the CSV parsing error when falling back to TextDiffer

In both the render_accepted and differ methods, when a CSV::MalformedCSVError is rescued, the exception is silently ignored. Logging the error would aid in debugging and monitoring potential issues with CSV parsing in the future.

Apply this diff to add logging:

     rescue CSV::MalformedCSVError
         # default to text if parsing failed
+        Rails.logger.warn("CSV parsing failed in render_accepted for expected output.")
     end
     rescue CSV::MalformedCSVError
         # default to text if parsing failed
+        Rails.logger.warn("CSV parsing failed in differ for generated or expected output.")
     end

Also applies to: 336-339

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 76f5ab3 and 655402a.

📒 Files selected for processing (2)
  • app/helpers/renderers/feedback_table_renderer.rb (2 hunks)
  • test/controllers/submissions_controller_test.rb (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
app/helpers/renderers/feedback_table_renderer.rb (2)

346-346: Refactored test_accepted method enhances code readability and modularity

By extracting the rendering logic for accepted tests into the render_accepted method, the code becomes more modular and easier to maintain. This improves readability and aligns with best practices.


334-341: 🛠️ Refactor suggestion

Avoid naming the variable differ to prevent confusion with the method name

In the diff method, the local variable differ is assigned the result of the differ(t) method. This naming can be confusing and may lead to misunderstandings or errors. Consider renaming the variable to something like difference or differ_instance to improve code clarity.

Apply this diff to rename the variable:

 def diff(t)
-    differ = differ(t)
+    difference = differ(t)
     @builder.div(class: "diffs show-#{@diff_type}") do
-        @builder << differ.split
-        @builder << differ.unified
+        @builder << difference.split
+        @builder << difference.unified
     end
 end

Likely invalid or redundant comment.

test/controllers/submissions_controller_test.rb Outdated Show resolved Hide resolved
Copy link
Member

@bmesuere bmesuere left a comment

Choose a reason for hiding this comment

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

I'm not too fond of these changes code-wise.

It duplicates some logic + in the new logic, fallback to the textdiffer is implicit and relies on error handling (i.e. the rescue block is empty)

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)
app/helpers/renderers/feedback_table_renderer.rb (1)

330-331: Consider logging CSV parsing errors for improved diagnostics

When a CSV::MalformedCSVError is rescued, logging the error can aid in diagnosing issues related to malformed CSV inputs. This will help in monitoring and troubleshooting potential problems with CSV data.

Apply this diff to log the exception:

-rescue CSV::MalformedCSVError
+rescue CSV::MalformedCSVError => e
+  Rails.logger.warn("CSV parsing failed: #{e.message}")
   yield(TextDiffer)
 end
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b04b434 and ca9b09e.

📒 Files selected for processing (1)
  • app/helpers/renderers/feedback_table_renderer.rb (2 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
app/helpers/renderers/feedback_table_renderer.rb

[warning] 328-328: app/helpers/renderers/feedback_table_renderer.rb#L328
Added line #L328 was not covered by tests

🔇 Additional comments (1)
app/helpers/renderers/feedback_table_renderer.rb (1)

322-334: Refactored error handling enhances CSV parsing robustness

The introduction of the with_differ_class method and its integration into test_accepted and diff methods significantly improves error handling. By gracefully handling malformed CSV data and appropriately falling back to TextDiffer, the code becomes more robust and maintainable.

Also applies to: 340-342, 353-358

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 328-328: app/helpers/renderers/feedback_table_renderer.rb#L328
Added line #L328 was not covered by tests

Comment on lines 325 to 328
if CsvDiffer.limited_columns?(t[:generated]) && CsvDiffer.limited_columns?(t[:expected])
yield(CsvDiffer)
else
yield(TextDiffer)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add tests to cover fallback when CSV column limits are exceeded

The else branch in the with_differ_class method, where yield(TextDiffer) is called due to column limits being exceeded, is not currently covered by tests as indicated by the static analysis tool. Adding tests for this scenario will ensure that the fallback to TextDiffer functions correctly when CSV inputs exceed column limitations.

Would you like assistance in creating test cases to cover this condition?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 328-328: app/helpers/renderers/feedback_table_renderer.rb#L328
Added line #L328 was not covered by tests

@jorg-vr
Copy link
Contributor Author

jorg-vr commented Oct 21, 2024

I removed the code duplication and also made the choice for the TextDiffer explicit

I think the deduplication is an improvement but I personally prefer the the implicit fallback as it simplifies the amount of cases, because most cases have the same result. With implicit fallback the method would look like this:

  def with_differ_class(t)
    if t[:format] == 'csv'
      begin
        return yield(CsvDiffer) if CsvDiffer.limited_columns?(t[:generated]) && CsvDiffer.limited_columns?(t[:expected])
      rescue CSV::MalformedCSVError
        # use the default differ
      end
    end

    yield(TextDiffer)
  end

@jorg-vr jorg-vr requested a review from bmesuere October 21, 2024 09:01
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

🧹 Outside diff range and nitpick comments (2)
app/helpers/renderers/feedback_table_renderer.rb (2)

322-331: LGTM! Consider adding a comment for clarity.

The implementation of with_differ_class looks good. It correctly handles the CSV format case and implements the fallback to TextDiffer as requested. The error handling for malformed CSV is also appropriate.

Consider adding a brief comment explaining the fallback logic, e.g.:

# Attempt to use CsvDiffer for 'csv' format, fallback to TextDiffer if parsing fails or for other formats

349-354: LGTM! Consider a minor optimization.

The changes to the diff method look good. It correctly uses the new with_differ_class method and renders both split and unified diffs.

Consider creating the differ instance outside the div to potentially improve performance:

with_differ_class(t) do |differ_class|
  differ = differ_class.new(t[:generated], t[:expected])
  @builder.div(class: "diffs show-#{@diff_type}") do
    @builder << differ.split
    @builder << differ.unified
  end
end

This way, the differ instance is created only once, regardless of how many times its methods are called.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ca9b09e and 2d87425.

📒 Files selected for processing (1)
  • app/helpers/renderers/feedback_table_renderer.rb (2 hunks)
🧰 Additional context used
🔇 Additional comments (3)
app/helpers/renderers/feedback_table_renderer.rb (3)

335-339: LGTM! Good use of the new with_differ_class method.

The changes to test_accepted look good. The method now correctly uses the new with_differ_class method, which allows for the appropriate differ class to be used based on the test format.


322-331: Reminder: Add tests for CSV fallback scenario

While the implementation of the fallback logic looks good, we should ensure it's covered by tests, especially for the case when CSV column limits are exceeded.

Would you like assistance in creating test cases to cover this condition? We could add tests to ensure that:

  1. CsvDiffer is used when the format is 'csv' and column limits are met.
  2. TextDiffer is used when the format is 'csv' but column limits are exceeded.
  3. TextDiffer is used when a CSV::MalformedCSVError is raised.

Let me know if you'd like me to propose some test cases or open a GitHub issue to track this task.


Line range hint 322-354: Overall, good implementation with room for minor improvements

The changes effectively implement the fallback mechanism for CSV parsing as requested. The code is generally well-structured and readable. Consider the following suggestions for improvement:

  1. Add a brief comment in with_differ_class to explain the fallback logic.
  2. Optimize the diff method by creating the differ instance outside the div.
  3. Add tests to cover the CSV fallback scenarios, including when column limits are exceeded and when CSV parsing fails.

These minor enhancements will improve code clarity, potentially boost performance, and ensure robustness through proper test coverage.

@jorg-vr jorg-vr merged commit 9c5359b into main Oct 21, 2024
14 checks passed
@jorg-vr jorg-vr deleted the fix/csv-differ branch October 21, 2024 14:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants