Skip to content

Conversation

anitacaron
Copy link
Collaborator

@anitacaron anitacaron commented Oct 10, 2024

Fixes #133

Preview using CDAO as example

Screenshot 2024-10-10 at 18 03 55

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling with structured logging for better issue tracking.
  • New Features

    • Enhanced report processing with controlled sampling of rows based on error levels and rule names.
    • Updated HTML output to reflect filtered and sampled report data.

@anitacaron anitacaron self-assigned this Oct 10, 2024
@anitacaron
Copy link
Collaborator Author

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

✅ Actions performed

Full review triggered.

Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

📝 Walkthrough

Walkthrough

The changes enhance util/create_report_html.py by introducing a sampling mechanism that includes all "ERROR" level entries and samples other levels to respect a line limit. It adds structured logging for errors, updates file handling modes, and modifies HTML output to reflect the filtered data. No changes were made to other files.

Changes

File Change Summary
util/create_report_html.py Added sampling of report rows by "Level" and "Rule Name" to include all ERRORs and sample others up to a limit; improved error handling with logging; changed file mode to read-write; updated HTML output to use filtered data.

Assessment against linked issues

Objective Addressed Explanation
Include all ERROR, increase rows to 1000, and strip out owlclassexpression hashcodes (#133)
Stratify the cut-off by shrinking large groups where necessary (#133) Sampling groups by "Level", "Rule Name", and "Subject" implements stratified cut-off.

Poem

In the garden where reports bloom bright,
We sample errors, a wondrous sight.
With lines truncated, the data flows,
A dashboard dance, where knowledge grows.
Hopping through code, with joy we play,
Celebrating changes, hip-hip-hooray! 🐇✨

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

Copy link
Contributor

@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: 5

🧹 Outside diff range and nitpick comments (1)
Makefile (1)

Line range hint 1-27: Overall impact on Makefile is minimal and aligned with objectives.

The removal of the truncate_reports_for_github target is the only change in this Makefile. This modification doesn't affect the execution of other targets or introduce any new dependencies. The overall structure for building and managing the dashboard remains intact.

Consider updating any documentation that might reference the removed truncate_reports_for_github target to reflect this change. This will help maintain consistency between the code and its documentation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ea99dd2 and 32c9dbb.

📒 Files selected for processing (3)
  • Makefile (1 hunks)
  • util/create_report_html.py (1 hunks)
  • util/dashboard_config.py (1 hunks)
🧰 Additional context used
🔇 Additional comments (1)
util/dashboard_config.py (1)

78-79: Verify the impact of disabling GitHub post-processing

The lines for post-processing files for GitHub have been commented out. This change may affect how the dashboard files are handled after their generation.

To ensure this change doesn't negatively impact the workflow, please run the following script:

This script will help identify any potential issues arising from the removal of this functionality. Please review the results to ensure that no critical GitHub-related processing is being overlooked.

Consider the following points:

  1. If this change is intentional, update any documentation that might reference the GitHub post-processing step.
  2. Ensure that any downstream processes or scripts that may have depended on this post-processing step are updated accordingly.
  3. If this is a temporary change for debugging or testing purposes, consider using a feature flag instead of commenting out the code to make it easier to re-enable in the future.
✅ Verification successful

Verified: Disabling GitHub post-processing has no adverse effects

The commented-out lines for post-processing files for GitHub in util/dashboard_config.py do not impact the current functionality:

  • The truncate_reports_for_github make target does not exist in the Makefile, indicating that this functionality is not in use.
  • Other GitHub-related references found are confined to comments and documentation, posing no risk to the workflow.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any references to the truncate_reports_for_github make target

# Test 1: Search for references to the make target in Python files
echo "Searching for references to truncate_reports_for_github in Python files:"
rg --type python "truncate_reports_for_github"

# Test 2: Check if the make target still exists in the Makefile
echo "Checking if the truncate_reports_for_github target exists in the Makefile:"
rg --type make "^truncate_reports_for_github:"

# Test 3: Look for any GitHub-related processing in other parts of the codebase
echo "Searching for other GitHub-related processing:"
rg --type python "github"

Length of output: 600


Script:

#!/bin/bash
# Description: Re-verify references to truncate_reports_for_github and GitHub-related processing

# Test 1: Search for references to the make target in Python files
echo "Searching for references to truncate_reports_for_github in Python files:"
rg "truncate_reports_for_github" -- '*.py'

# Test 2: Check if the truncate_reports_for_github target exists in the Makefile
echo "Checking if the truncate_reports_for_github target exists in the Makefile:"
rg "^truncate_reports_for_github:" Makefile

# Test 3: Look for any GitHub-related processing in other parts of the codebase
echo "Searching for other GitHub-related processing in Python files:"
rg "github" -- '*.py'

Length of output: 649


Script:

#!/bin/bash
# Description: Re-verify references to truncate_reports_for_github and GitHub-related processing

# Test 1: Search for references to the make target in Python files
echo "Searching for references to truncate_reports_for_github in Python files:"
rg "truncate_reports_for_github" --glob "*.py"

# Test 2: Check if the truncate_reports_for_github target exists in the Makefile
echo "Checking if the truncate_reports_for_github target exists in the Makefile:"
rg "^truncate_reports_for_github:" Makefile

# Test 3: Look for any GitHub-related processing in Python files
echo "Searching for other GitHub-related processing in Python files:"
rg "github" --glob "*.py"

Length of output: 8422


Script:

#!/bin/bash
# Description: Re-verify references to truncate_reports_for_github and GitHub-related processing

# Test 1: Search for references to the make target in Python files
echo "Searching for references to truncate_reports_for_github in Python files:"
rg "truncate_reports_for_github" --glob "*.py"

# Test 2: Check if the truncate_reports_for_github target exists in the Makefile
echo "Checking if the truncate_reports_for_github target exists in the Makefile:"
rg "^truncate_reports_for_github:" Makefile

# Test 3: Look for any GitHub-related processing in Python files
echo "Searching for other GitHub-related processing in Python files:"
rg "github" --glob "*.py"

Length of output: 8422

Copy link
Contributor

@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: 4

♻️ Duplicate comments (2)
util/create_report_html.py (2)

65-68: Good implementation of column validation.

This properly addresses the previous review comment about ensuring required columns exist.


84-89: Good implementation of structured exception handling.

This properly addresses the previous review comment about using logging instead of print statements.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 32c9dbb and 634ede8.

📒 Files selected for processing (1)
  • util/create_report_html.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: QC
🔇 Additional comments (1)
util/create_report_html.py (1)

5-5: LGTM! Good addition of structured logging.

The logging configuration provides better error tracking with timestamps and log levels.

Also applies to: 13-14

parser = argparse.ArgumentParser(description='Create a report HTML page')
parser.add_argument('report',
type=argparse.FileType('r'),
type=argparse.FileType('r+'),
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consider using a separate output file instead of overwriting the input.

Opening the report file in 'r+' mode and overwriting it at line 82 is risky. If an error occurs during processing, the original data could be lost.

Consider adding a separate output parameter for the filtered report:

 parser.add_argument('report',
-                    type=argparse.FileType('r+'),
+                    type=argparse.FileType('r'),
                     help='TSV report to convert to HTML')
+parser.add_argument('--output-report',
+                    type=argparse.FileType('w'),
+                    help='Output filtered report TSV file (optional)')

Then modify line 82:

-if len(report_filtered) > args.limitlines:
-    report_filtered.to_csv(args.report, sep="\t", index=False)
+if args.output_report and len(report) > args.limitlines:
+    report_filtered.to_csv(args.output_report, sep="\t", index=False)

Also applies to: 82-82

🤖 Prompt for AI Agents
In util/create_report_html.py at line 21, the argument parser currently opens
the input report file in 'r+' mode, which risks overwriting the original file if
an error occurs. To fix this, add a new command-line argument for a separate
output file to write the filtered report. Then, at line 82, change the code to
write to this new output file instead of overwriting the input file. This
ensures the original input remains intact in case of processing errors.

Comment on lines +81 to +82
if len(report_filtered) > args.limitlines:
report_filtered.to_csv(args.report, sep="\t", index=False)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove or fix the illogical condition.

The condition len(report_filtered) > args.limitlines doesn't make sense after filtering. The filtered report should already be within the limit.

Either remove this block or change the logic to save the filtered report when the original report exceeds the limit:

-if len(report_filtered) > args.limitlines:
-    report_filtered.to_csv(args.report, sep="\t", index=False)
+# Save filtered report if original exceeded limit
+if len(report) > args.limitlines and args.output_report:
+    report_filtered.to_csv(args.output_report, sep="\t", index=False)

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In util/create_report_html.py around lines 81 to 82, the condition checking if
the filtered report length exceeds the limit is illogical since filtering should
already enforce the limit. Fix this by changing the condition to check if the
original report length exceeds args.limitlines before saving the filtered
report, or remove the condition entirely to always save the filtered report.

Comment on lines +71 to +75
report_filtered = report.groupby(by=["Level","Rule Name","Subject"])[
["Level", "Rule Name", "Subject", "Property", "Value"]
].apply(
lambda x: x.sample(calculate_sample_size(x, rest))
).reset_index(drop=True)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Make the sampling more robust against edge cases.

The current implementation could fail if groups are empty or if sampling parameters are invalid.

Consider adding error handling:

 # Get a sample of each Level type
-report_filtered = report.groupby(by=["Level","Rule Name","Subject"])[
-    ["Level", "Rule Name", "Subject", "Property", "Value"]
-].apply(
-    lambda x: x.sample(calculate_sample_size(x, rest))
-).reset_index(drop=True)
+def safe_sample(group, sample_size_func):
+    try:
+        n = sample_size_func(group)
+        if n > 0 and len(group) > 0:
+            return group.sample(min(n, len(group)))
+        return group
+    except Exception as e:
+        logging.warning(f"Sampling failed for group: {e}")
+        return group
+
+report_filtered = report.groupby(by=["Level","Rule Name","Subject"])[
+    ["Level", "Rule Name", "Subject", "Property", "Value"]
+].apply(
+    lambda x: safe_sample(x, calculate_sample_size)
+).reset_index(drop=True)

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In util/create_report_html.py around lines 71 to 75, the current groupby
sampling can fail if groups are empty or sampling parameters are invalid. To fix
this, add error handling inside the lambda function to check if the group is
empty or if the sample size is valid before calling sample. If invalid, return
the group as is or an empty DataFrame to avoid exceptions during sampling.

Comment on lines +56 to +64
rest = args.limitlines - error_count_level["ERROR"]

# Calculate the sample number for each level based on group size
def calculate_sample_size(group, rest):
if group["Level"].iloc[0] == "ERROR":
return group.shape[0]

return min(group.shape[0], rest)

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the sampling logic to properly distribute remaining lines.

The current logic incorrectly uses the full rest value for each non-ERROR group, which could exceed the limit when multiple groups exist.

The sampling should distribute the remaining lines proportionally among non-ERROR levels:

-error_count_error = error_count_level.get("ERROR", 0)
-if error_count_error < args.limitlines:
-    rest = args.limitlines - error_count_level["ERROR"]
-
-    # Calculate the sample number for each level based on group size
-    def calculate_sample_size(group, rest):
-        if group["Level"].iloc[0] == "ERROR":
-            return group.shape[0]
-
-        return min(group.shape[0], rest)
+error_count_error = error_count_level.get("ERROR", 0)
+if error_count_error < args.limitlines:
+    rest = args.limitlines - error_count_error
+    
+    # Calculate proportional sample sizes for non-ERROR levels
+    non_error_counts = {level: count for level, count in error_count_level.items() if level != "ERROR"}
+    total_non_error = sum(non_error_counts.values())
+    
+    level_sample_sizes = {"ERROR": error_count_error}
+    if total_non_error > 0:
+        for level, count in non_error_counts.items():
+            # Proportionally distribute remaining lines
+            level_sample_sizes[level] = int(rest * count / total_non_error)
+    
+    def calculate_sample_size(group):
+        level = group["Level"].iloc[0]
+        group_key = (level, group["Rule Name"].iloc[0], group["Subject"].iloc[0])
+        # Distribute level sample size among groups of that level
+        level_sample = level_sample_sizes.get(level, 0)
+        # This is a simplified approach - you may want to further distribute among groups
+        return min(group.shape[0], max(1, level_sample))

Also, line 56 still uses direct dictionary access instead of .get():

-rest = args.limitlines - error_count_level["ERROR"]
+rest = args.limitlines - error_count_error

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In util/create_report_html.py around lines 56 to 64, fix the sampling logic by
replacing the direct dictionary access on line 56 with .get() to avoid KeyError,
and update the calculate_sample_size function to distribute the remaining lines
proportionally among non-ERROR groups instead of using the full rest value for
each group. Compute the total size of non-ERROR groups, then allocate sample
sizes based on each group's proportion of that total, ensuring the sum does not
exceed the limit.

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.

[ROBOT report] Show a sample of each rule type
1 participant