Skip to content

feat: Add the metadata interface to the reporter class #6

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

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

Conversation

LKress
Copy link

@LKress LKress commented Mar 16, 2025

This is required, to allow custom metadata in the report (snakemake/snakemake#3452).

Summary by CodeRabbit

  • New Features
    • Added support for including optional metadata when creating reports.
  • Bug Fixes
    • Improved validation for metadata to ensure only supported data types are accepted, preventing errors during report generation.

Copy link

coderabbitai bot commented Mar 16, 2025

📝 Walkthrough

Walkthrough

The constructor of the ReporterBase class in snakemake_interface_report_plugins/reporter.py was updated to accept an optional metadata parameter with a stricter type hint allowing only flat dictionaries with string keys and values of type str, int, float, or lists thereof. New validation functions were added to enforce this constraint, raising a TypeError if validation fails. The import statement was updated accordingly.

Changes

File(s) Change Summary
snakemake_interface_report_plugins/reporter.py Changed ReporterBase.__init__ metadata parameter type to Optional[Dict[str, Union[str, int, float, List[str], List[int], List[float]]]] with default {}; added is_valid_flat_value and validate_flat_dict functions for metadata validation; added validation logic in constructor; updated imports.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant ReporterBase

    Caller->>ReporterBase: __init__(..., metadata)
    alt metadata is None or empty
        ReporterBase->>ReporterBase: self.metadata = {}
    else metadata provided
        ReporterBase->>ReporterBase: validate_flat_dict(metadata)
        alt validation fails
            ReporterBase->>Caller: raise TypeError
        else validation succeeds
            ReporterBase->>ReporterBase: self.metadata = metadata
        end
    end
Loading

Possibly related issues

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

@LKress LKress changed the title feat:Add the metadata interface to the reporter class feat: add the metadata interface to the reporter class Mar 16, 2025
@LKress LKress changed the title feat: add the metadata interface to the reporter class feat: Add the metadata interface to the reporter class Mar 26, 2025
@@ -27,6 +28,7 @@ def __init__(
jobs: List[JobRecordInterface],
settings: ReportSettingsBase,
workflow_description: str,
metadata: MetadataRecordInterface,
Copy link
Contributor

Choose a reason for hiding this comment

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

Turn this into a keyword arg with a default of None that is then initialized as an empty dict.

Copy link
Contributor

Choose a reason for hiding this comment

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

Reason: this way, we don't need a breaking change in the interface.


@property
@abstractmethod
def parse_yte(self) -> dict: ...
Copy link
Contributor

Choose a reason for hiding this comment

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

Why does the plugin need to be able to parse this? I would just pass a dict with the metadata to the Reporter class below.

Copy link
Contributor

Choose a reason for hiding this comment

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

Then, there is not even an interface needed for the metadata record.

Copy link
Author

Choose a reason for hiding this comment

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

Makes sense, I removed the MetadataRecordInterface and adapted the snakemake code in pull request #3452

@@ -28,6 +28,7 @@ def __init__(
settings: ReportSettingsBase,
workflow_description: str,
dag: DAGReportInterface,
metadata: Dict[Any, Any] = None,
Copy link
Contributor

Choose a reason for hiding this comment

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

What can we assume about the dict? Is is always single level? Are the keys always strings and the values str or int? Probably yes. In that case, the corresponding Snakemake PR should ensure that and throw an error otherwise, and here we should annotate it as Dict[str, Union[str, int, float]].

Copy link
Contributor

Choose a reason for hiding this comment

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

@LKress Do you have the chance to consider this? I have also tried to contact you via discord (hopefully I found the correct username). If not, just send me a PM via discord.

Copy link
Author

Choose a reason for hiding this comment

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

I think lists of the above mentioned types should be possible too. Therefore, the current implementation allows lists of str, int and float too. The snakemake reporter already handles this. I have added an additional test that checks that an error is thrown, if the metadata is nested in the snakemake repo (snakemake/snakemake@b0cae83).

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

♻️ Duplicate comments (1)
snakemake_interface_report_plugins/reporter.py (1)

31-33: Fix the mutable default argument issue.

The current implementation uses a mutable default argument {}, which is flagged by static analysis and violates Python best practices. Based on the past review comments, this should use None as the default and initialize an empty dict inside the constructor.

Apply this diff to fix the mutable default argument:

-        metadata: Optional[
-            Dict[str, Union[str, int, float, List[str], List[int], List[float]]]
-        ] = {},
+        metadata: Optional[
+            Dict[str, Union[str, int, float, List[str], List[int], List[float]]]
+        ] = None,
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 592243d and 0370982.

📒 Files selected for processing (1)
  • snakemake_interface_report_plugins/reporter.py (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

🪛 Ruff (0.11.9)
snakemake_interface_report_plugins/reporter.py

33-33: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)


53-54: ReporterBase.__post_init__ is an empty method in an abstract base class, but has no abstract decorator

(B027)

🪛 GitHub Actions: CI
snakemake_interface_report_plugins/reporter.py

[error] 46-46: flake8: line too long (115 > 88 characters) (E501)

🔇 Additional comments (4)
snakemake_interface_report_plugins/reporter.py (4)

8-8: LGTM: Import statement properly updated.

The import statement correctly adds the necessary typing components for the metadata interface implementation.


49-49: LGTM: Metadata assignment is correct.

The assignment of the validated metadata to the instance attribute is properly implemented.


60-67: LGTM: Helper function is well-implemented.

The is_valid_flat_value function correctly validates individual values according to the specified type constraints.


69-79: LGTM: Validation function is robust.

The validate_flat_dict function properly validates the dictionary structure, checking both key types and value types using the helper function.

Comment on lines 43 to 48
# ensure that metadata is a key value dictionary
if not validate_flat_dict(metadata):
raise TypeError(
"Metadata must be single level dict[str, str | int | float | list[str] | list[int] | list[float]]]"
)

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix line length and adjust validation for None default.

The validation logic needs to be updated to handle the None default value, and the error message line is too long (115 > 88 characters).

Apply this diff to fix both issues:

-        # ensure that metadata is a key value dictionary
-        if not validate_flat_dict(metadata):
-            raise TypeError(
-                "Metadata must be single level dict[str, str | int | float | list[str] | list[int] | list[float]]]"
-            )
+        # ensure that metadata is a key value dictionary
+        if metadata is None:
+            metadata = {}
+        if not validate_flat_dict(metadata):
+            raise TypeError(
+                "Metadata must be single level dict[str, str | int | float | "
+                "list[str] | list[int] | list[float]]]"
+            )
📝 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
# ensure that metadata is a key value dictionary
if not validate_flat_dict(metadata):
raise TypeError(
"Metadata must be single level dict[str, str | int | float | list[str] | list[int] | list[float]]]"
)
# ensure that metadata is a key value dictionary
if metadata is None:
metadata = {}
if not validate_flat_dict(metadata):
raise TypeError(
"Metadata must be single level dict[str, str | int | float | "
"list[str] | list[int] | list[float]]]"
)
🧰 Tools
🪛 GitHub Actions: CI

[error] 46-46: flake8: line too long (115 > 88 characters) (E501)

🤖 Prompt for AI Agents
In snakemake_interface_report_plugins/reporter.py around lines 43 to 48, update
the validation logic to allow for the metadata parameter to be None by adding a
condition to skip validation if metadata is None. Also, split the long error
message string into multiple shorter lines to ensure no line exceeds 88
characters, improving readability and adhering to style guidelines.

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

♻️ Duplicate comments (2)
snakemake_interface_report_plugins/reporter.py (2)

31-33: Fix mutable default argument to align with past review feedback.

The current implementation uses a mutable default argument, which violates Python best practices and contradicts past review comments requesting a keyword arg with None default.

Apply this diff to fix the mutable default argument:

-        metadata: Optional[
-            Dict[str, Union[str, int, float, List[str], List[int], List[float]]]
-        ] = {},
+        metadata: Optional[
+            Dict[str, Union[str, int, float, List[str], List[int], List[float]]]
+        ] = None,

43-52: Fix line length violation and handle None default.

The validation logic has line length issues and needs to handle the None default case.

Apply this diff to fix both issues:

-        # ensure that metadata is a key value dictionary
-        if not validate_flat_dict(metadata):
-            raise TypeError(
-                (
-                    "Metadata must be single level "
-                    "dict[str, str | int | float | list[str] | list[int] | list[float]]]"
-                )
-            )
-
-        self.metadata = metadata
+        # ensure that metadata is a key value dictionary
+        if metadata is None:
+            metadata = {}
+        if not validate_flat_dict(metadata):
+            raise TypeError(
+                "Metadata must be single level "
+                "dict[str, str | int | float | "
+                "list[str] | list[int] | list[float]]]"
+            )
+
+        self.metadata = metadata
🧹 Nitpick comments (1)
snakemake_interface_report_plugins/reporter.py (1)

56-57: Consider making __post_init__ abstract if subclasses should implement it.

The empty __post_init__ method could be made abstract if subclasses are expected to provide implementations, or add a docstring explaining its purpose as an optional hook.

If subclasses should implement this method:

+    @abstractmethod
     def __post_init__(self):
-        pass
+        ...
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0370982 and e487225.

📒 Files selected for processing (1)
  • snakemake_interface_report_plugins/reporter.py (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

🪛 Ruff (0.11.9)
snakemake_interface_report_plugins/reporter.py

33-33: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)


56-57: ReporterBase.__post_init__ is an empty method in an abstract base class, but has no abstract decorator

(B027)

🪛 GitHub Actions: CI
snakemake_interface_report_plugins/reporter.py

[error] 48-48: flake8: line too long (89 > 88 characters) (E501)

🔇 Additional comments (2)
snakemake_interface_report_plugins/reporter.py (2)

8-8: LGTM! Import additions are appropriate.

The added typing imports are necessary for the metadata type annotations.


63-82: LGTM! Helper functions are well-implemented.

The validation functions correctly enforce the metadata constraints:

  • is_valid_flat_value properly checks for valid types and lists
  • validate_flat_dict ensures dictionary structure with string keys
  • Logic is comprehensive and handles edge cases appropriately

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

♻️ Duplicate comments (2)
snakemake_interface_report_plugins/reporter.py (2)

31-33: Fix the mutable default argument issue.

The use of {} as a default argument creates a mutable default, which can lead to shared state issues. This was flagged in previous reviews and by static analysis.

Apply this diff to fix the mutable default:

-        metadata: Optional[
-            Dict[str, Union[str, int, float, List[str], List[int], List[float]]]
-        ] = {},
+        metadata: Optional[
+            Dict[str, Union[str, int, float, List[str], List[int], List[float]]]
+        ] = None,

43-51: Handle None default and improve validation logic.

The validation logic doesn't properly handle the None default value that should be used instead of the mutable default. This was identified in previous reviews.

Apply this diff to fix the None handling:

-        # ensure that metadata is a key value dictionary
-        if not validate_flat_dict(metadata):
-            raise TypeError(
-                (
-                    "Metadata must be single level "
-                    "dict[str, str | int | float | "
-                    "list[str] | list[int] | list[float]]]"
-                )
-            )
+        # ensure that metadata is a key value dictionary
+        if metadata is None:
+            metadata = {}
+        if not validate_flat_dict(metadata):
+            raise TypeError(
+                (
+                    "Metadata must be single level "
+                    "dict[str, str | int | float | "
+                    "list[str] | list[int] | list[float]]]"
+                )
+            )
🧹 Nitpick comments (1)
snakemake_interface_report_plugins/reporter.py (1)

57-58: Consider making the empty __post_init__ method abstract.

The empty __post_init__ method in an abstract base class should be decorated with @abstractmethod if subclasses are expected to implement it, or removed if it's not needed.

If subclasses should implement this method, apply this diff:

+    @abstractmethod
     def __post_init__(self):
-        pass
+        ...

If this method is not needed, consider removing it entirely.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e487225 and 214535a.

📒 Files selected for processing (1)
  • snakemake_interface_report_plugins/reporter.py (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

🪛 Ruff (0.11.9)
snakemake_interface_report_plugins/reporter.py

33-33: Do not use mutable data structures for argument defaults

Replace with None; initialize within function

(B006)


57-58: ReporterBase.__post_init__ is an empty method in an abstract base class, but has no abstract decorator

(B027)

🔇 Additional comments (4)
snakemake_interface_report_plugins/reporter.py (4)

8-8: LGTM on the import additions.

The new typing imports are correctly added to support the enhanced type annotations for the metadata parameter.


53-53: LGTM on the metadata assignment.

The assignment is correct and will work properly once the None handling is fixed in the validation logic above.


64-71: LGTM on the value validation helper function.

The is_valid_flat_value function correctly validates individual values and lists of allowed types. The logic properly checks for the supported types (str, int, float) and validates that lists contain only these types.


73-83: LGTM on the dictionary validation helper function.

The validate_flat_dict function correctly validates the entire dictionary structure, ensuring all keys are strings and all values pass the flat value validation. The logic is sound and matches the type constraints defined in the constructor.

Comment on lines +43 to +51
# ensure that metadata is a key value dictionary
if not validate_flat_dict(metadata):
raise TypeError(
(
"Metadata must be single level "
"dict[str, str | int | float | "
"list[str] | list[int] | list[float]]]"
)
)
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you please move this check into the main snakemake, before the Report class is called?
The reason is that the type already asserts that the dictionary is valid. Hence, the validation has to happen before the dict is passed to the metadata argument.

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