Skip to content

Optimize some files based on CodeFactor. - #117

Merged
ypriverol merged 2 commits into
bigbio:devfrom
Shen-YuFei:dev
Sep 25, 2025
Merged

ypriverol merged 2 commits into
bigbio:devfrom
Shen-YuFei:dev

Conversation

@Shen-YuFei

@Shen-YuFei Shen-YuFei commented Sep 25, 2025 •

Copy link
Copy Markdown
Collaborator

User description

Code Quality Improvements

This PR implements code optimizations based on CodeFactor analysis to improve maintainability and security.

Changes Summary

  • 13 files modified
  • +1,044 additions, -655 deletions
  • Net change: +389 lines

Key Improvements

Code Structure

  • Extracted large methods into smaller, focused functions
  • Improved function and variable naming

Security Fixes

  • Replaced tempfile.mktemp() with tempfile.NamedTemporaryFile()
  • Enhanced resource cleanup and error handling
  • More specific exception handling patterns

Modified Components

  • Core processing modules (idxml.py, mztab.py, psm.py)
  • Utility functions (mztab_utils.py)
  • Test files with improved temp file handling

Testing

All existing tests updated and passing.


PR Type

Bug fix, Enhancement


Description

  • Replace insecure tempfile.mktemp() with tempfile.NamedTemporaryFile()

  • Refactor large methods into smaller focused functions

  • Improve error handling with specific exception types

  • Enhance code structure and maintainability


Diagram Walkthrough

flowchart LR
  A["tempfile.mktemp()"] -- "replace with" --> B["tempfile.NamedTemporaryFile()"]
  C["Large methods"] -- "extract into" --> D["Smaller functions"]
  E["Generic exceptions"] -- "replace with" --> F["Specific exceptions"]
Loading

File Walkthrough

Relevant files
Bug fix
2 files
quantms.py
Replace insecure temporary file creation                                 
+16/-3   
openms.py
Improve meta value extraction error handling                         
+10/-7   
Enhancement
5 files
idxml.py
Extract modification parsing into helper methods                 
+198/-154
feature.py
Refactor modification processing into smaller functions   
+179/-76
mztab.py
Break down large mzTab processing method                                 
+234/-180
psm.py
Extract metadata modification parsing helpers                       
+92/-74 
mztab_utils.py
Refactor OpenMS modification parsing logic                             
+184/-107
Tests
6 files
test_idxml_psm.py
Update test to use secure temp files                                         
+3/-1     
test_duckdb_creation.py
Improve cleanup error handling specificity                             
+6/-4     
test_psm.py
Replace temp file creation in tests                                           
+42/-12 
test_feature.py
Update temp file handling in feature tests                             
+16/-3   
test_msstats_in.py
Extract channel statistics processing functions                   
+61/-33 
test_large_mztab_performance.py
Fix temp file creation in performance test                             
+3/-1     

@coderabbitai

coderabbitai Bot commented Sep 25, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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

Comment @coderabbitai help to get the list of available commands and usage tips.

@qodo-code-review

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Tempfile Handling

The pattern creates a NamedTemporaryFile and immediately unlinks it if it exists before DuckDB uses the path. This may be okay across platforms, but on Windows open file handles can cause issues. Consider using tempfile.mkstemp or pathlib with unique names, and ensure consistent cleanup in exceptions.

temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False)
temp_db_path = temp_db_file.name
temp_db_file.close()
if os.path.exists(temp_db_path):
    os.unlink(temp_db_path)
logger.info(
    f"Creating temporary MzTabIndexer at {temp_db_path} from {mztab_path}"
)
MetaValue Keys

Switching to hit.getKeys(keys) is good, but ensure keys list contents are strings and compatible with getMetaValue; also confirm behavior when keys include non-numeric values—current code silently continues which may hide data issues. Consider logging unexpected types at debug level.

    # Get all meta value keys - PyOpenMS getKeys needs a list to populate
    keys = []
    hit.getKeys(keys)
    for key in keys:
        try:
            value = hit.getMetaValue(key)
            if isinstance(value, (int, float)):
                scores.append({"score_name": key, "score_value": float(value)})
        except (KeyError, TypeError, ValueError, RuntimeError):
            # Skip if meta value key doesn't exist, value can't be converted,
            # or there's a runtime error from OpenMS
            continue
except (AttributeError, RuntimeError):
    # Skip meta values if hit object doesn't support getKeys() or
    # there's a runtime error from OpenMS
    pass
Refactor Integrity

The orchestration refactor introduces context dict and multiple helpers. Validate that counters and parquet writer lifecycle mirror previous behavior, and that metadata batches are written when present. Pay attention to gzip handling and error propagation consistency.

def _process_mztab_to_parquet(self):
    """
    Process mzTab file to parquet files in batches.

    This method orchestrates the processing of mzTab files by coordinating
    setup, file processing, batch writing, and cleanup operations.

    Returns:
        tuple: A tuple containing paths to the created parquet files:
            - metadata_parquet (Path): Path to metadata.parquet
            - proteins_parquet (Path): Path to proteins.parquet
            - protein_details_parquet (Path): Path to protein_details.parquet
            - psms_parquet (Path): Path to psms.parquet

    Raises:
        FileNotFoundError: If the mzTab file doesn't exist
        PermissionError: If there are permission issues accessing the file
        MemoryError: If insufficient memory to process the file
        RuntimeError: If there are insufficient disk space or other processing errors
    """
    # Setup processing environment
    context = self._setup_processing_environment()

    try:
        # Process the mzTab file
        self._process_mztab_file(context)

        # Write final batches
        self._write_final_batches(context)

    except FileNotFoundError:
        raise FileNotFoundError(f"mzTab file not found: {self._mztab_path}")
    except PermissionError:
        raise PermissionError(
            f"Permission denied accessing file: {self._mztab_path}"
        )
    except MemoryError:
        raise MemoryError(
            "Insufficient memory to process mzTab file. Try reducing batch_size."
        )
    except Exception as e:
        self.logger.error(f"Unexpected error processing mzTab file: {e}")
        raise RuntimeError(f"Failed to process mzTab file: {e}")
    finally:
        # Clean up resources
        self._cleanup_processing_resources(context)

    # Log completion statistics
    self._log_processing_completion(context)

    return (
        context["parquet_paths"]["metadata"],
        context["parquet_paths"]["proteins"],
        context["parquet_paths"]["protein_details"],
        context["parquet_paths"]["psms"],
    )

def _setup_processing_environment(self):
    """Setup processing environment and return context dictionary."""
    # Determine if file is gzipped
    is_gzipped = str(self._mztab_path).endswith(".gz")
    output_dir = self._get_output_dir()

    self.logger.debug(f"Processing mzTab file: {self._mztab_path}")
    self.logger.debug(f"File is gzipped: {is_gzipped}")
    self.logger.debug(f"Output directory: {output_dir}")
    self.logger.debug(f"Batch size: {self._batch_size}")

    # Check available disk space
    if not check_disk_space(output_dir):
        raise RuntimeError("Insufficient disk space for processing mzTab file")

    return {
        "is_gzipped": is_gzipped,
        "output_dir": output_dir,
        "parquet_paths": {
            "metadata": output_dir / "metadata.parquet",
            "proteins": output_dir / "proteins.parquet",
            "protein_details": output_dir / "protein_details.parquet",
            "psms": output_dir / "psms.parquet",
        },
        "writers": {"proteins": None, "protein_details": None, "psms": None},
        "counters": {
            "metadata": 0,
            "protein": 0,
            "protein_details": 0,
            "psm": 0,
            "batch": 0,
        },
        "data_buffers": {
            "metadata": [],
            "proteins": [],
            "protein_details": [],
            "psms": [],
        },
    }

def _process_mztab_file(self, context):
    """Process the mzTab file line by line."""
    open_func = gzip.open if context["is_gzipped"] else open

    with open_func(self._mztab_path, "rt") as f:
        for line_num, line in enumerate(f, 1):
            try:
                line = line.strip()
                if not line:
                    continue

                self._process_single_line(line, context, line_num)
                self._write_batches_if_needed(context)

            except Exception as e:
                self.logger.error(f"Error processing line {line_num}: {e}")
                self.logger.error(f"Line content: {line[:100]}...")
                continue

def _process_single_line(self, line, context, line_num):
    """Process a single mzTab line."""
    if is_mztab_line_type(line, "MTD"):
        self._process_metadata_line(line, context)
    elif is_mztab_line_type(line, "PRH"):
        self._process_protein_header_line(line)
    elif is_mztab_line_type(line, "PRT"):
        self._process_protein_line(line, context)
    elif is_mztab_line_type(line, "PSH"):
        self._process_psm_header_line(line)
    elif is_mztab_line_type(line, "PSM"):
        self._process_psm_line(line, context)

def _process_metadata_line(self, line, context):
    """Process metadata line."""
    context["data_buffers"]["metadata"].append(parse_metadata_line(line))
    context["counters"]["metadata"] += 1

def _process_protein_header_line(self, line):
    """Process protein header line."""
    self._protein_header = parse_header_line(line)
    self.logger.debug(
        f"Found protein header with {len(self._protein_header)} columns"
    )

def _process_protein_line(self, line, context):
    """Process protein line."""
    protein_dict = self._parse_protein_line_with_processing(line)
    if protein_dict is None:
        return

    if OPT_GLOBAL_RESULT_TYPE in protein_dict:
        result_type = protein_dict[OPT_GLOBAL_RESULT_TYPE]

        if result_type in [INDISTINGUISHABLE_GROUP, SINGLE_PROTEIN_MZTAB]:
            context["data_buffers"]["proteins"].append(protein_dict)
            context["counters"]["protein"] += 1
        elif result_type == PROTEIN_DETAILS_MZTAB:
            context["data_buffers"]["protein_details"].append(protein_dict)
            context["counters"]["protein_details"] += 1

def _process_psm_header_line(self, line):
    """Process PSM header line."""
    self._psm_header = parse_header_line(line)
    self.logger.debug(f"Found PSM header with {len(self._psm_header)} columns")

def _process_psm_line(self, line, context):
    """Process PSM line."""
    context["data_buffers"]["psms"].append(
        self._parse_psm_line_with_processing(line)
    )
    context["counters"]["psm"] += 1

def _write_batches_if_needed(self, context):
    """Write batches to parquet files if they've reached the batch size limit."""
    # Write protein batch if needed
    if len(context["data_buffers"]["proteins"]) >= self._batch_size:
        context["writers"]["proteins"] = self._write_protein_batch(
            context["data_buffers"]["proteins"],
            context["parquet_paths"]["proteins"],
            context["writers"]["proteins"],
        )
        context["counters"]["batch"] += 1
        self.logger.debug(
            f"Wrote protein batch {context['counters']['batch']} "
            f"({len(context['data_buffers']['proteins'])} proteins)"
        )
        context["data_buffers"]["proteins"] = []

    # Write protein details batch if needed
    if len(context["data_buffers"]["protein_details"]) >= self._batch_size:
        context["writers"]["protein_details"] = self._write_protein_details_batch(
            context["data_buffers"]["protein_details"],
            context["parquet_paths"]["protein_details"],
            context["writers"]["protein_details"],
        )
        self.logger.debug(
            f"Wrote protein_details batch ({len(context['data_buffers']['protein_details'])} entries)"
        )
        context["data_buffers"]["protein_details"] = []

    # Write PSM batch if needed
    if len(context["data_buffers"]["psms"]) >= self._batch_size:
        context["writers"]["psms"] = self._write_psm_batch(
            context["data_buffers"]["psms"],
            context["parquet_paths"]["psms"],
            context["writers"]["psms"],
        )
        context["counters"]["batch"] += 1
        self.logger.debug(
            f"Wrote PSM batch {context['counters']['batch']} ({len(context['data_buffers']['psms'])} PSMs)"
        )
        context["data_buffers"]["psms"] = []

def _write_final_batches(self, context):
    """Write any remaining data batches to parquet files."""
    if context["data_buffers"]["metadata"]:
        self._write_metadata_batch(
            context["data_buffers"]["metadata"],
            context["parquet_paths"]["metadata"],
        )
        self.logger.debug(
            f"Wrote metadata batch ({len(context['data_buffers']['metadata'])} entries)"
        )

    if context["data_buffers"]["proteins"]:
        context["writers"]["proteins"] = self._write_protein_batch(
            context["data_buffers"]["proteins"],
            context["parquet_paths"]["proteins"],
            context["writers"]["proteins"],
        )
        self.logger.debug(
            f"Wrote final protein batch ({len(context['data_buffers']['proteins'])} proteins)"
        )

    if context["data_buffers"]["protein_details"]:
        context["writers"]["protein_details"] = self._write_protein_details_batch(
            context["data_buffers"]["protein_details"],
            context["parquet_paths"]["protein_details"],
            context["writers"]["protein_details"],
        )
        self.logger.debug(
            f"Wrote final protein_details batch ({len(context['data_buffers']['protein_details'])} entries)"
        )

    if context["data_buffers"]["psms"]:
        context["writers"]["psms"] = self._write_psm_batch(
            context["data_buffers"]["psms"],
            context["parquet_paths"]["psms"],
            context["writers"]["psms"],
        )
        self.logger.debug(
            f"Wrote final PSM batch ({len(context['data_buffers']['psms'])} PSMs)"
        )

def _cleanup_processing_resources(self, context):
    """Close all parquet writers safely."""
    try:
        for writer_name, writer in context["writers"].items():
            if writer:
                try:
                    writer.close()
                    self.logger.debug(f"Successfully closed {writer_name} writer")
                except Exception as writer_error:
                    self.logger.warning(
                        f"Error closing {writer_name} writer: {writer_error}"
                    )
    except Exception as e:
        self.logger.error(f"Error closing parquet writers: {e}")

def _log_processing_completion(self, context):
    """Log processing completion statistics."""
    counters = context["counters"]
    self.logger.debug(
        f"Processing complete. Total counts: metadata={counters['metadata']}, "
        f"proteins={counters['protein']}, protein_details={counters['protein_details']}, "
        f"psms={counters['psm']}"
    )

@qodo-code-review

qodo-code-review Bot commented Sep 25, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Security
Use TemporaryDirectory for safer temp files

Replace the manual creation and deletion of a temporary file with
tempfile.TemporaryDirectory to avoid a race condition and simplify the code.

quantmsio/commands/convert/quantms.py [108-112]

-temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False)
-temp_db_path = temp_db_file.name
-temp_db_file.close()
-if os.path.exists(temp_db_path):
-    os.unlink(temp_db_path)
+with tempfile.TemporaryDirectory() as temp_dir:
+    temp_db_path = Path(temp_dir) / "temp.duckdb"
+    logger.info(
+        f"Creating temporary MzTabIndexer at {temp_db_path} from {mztab_path}"
+    )
+    indexer = MzTabIndexer.create(
+        mztab_path=str(mztab_path),
+        msstats_path=msstats_file,
+        sdrf_path=sdrf_file,
+        database_path=temp_db_path,
+    )
+    # The rest of the logic that uses the indexer should be inside this 'with' block.
+    # The temporary directory and its contents are automatically removed on exit.
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a security vulnerability (race condition) in the PR's code, which was intended to fix a similar issue, and proposes a more robust and idiomatic solution using tempfile.TemporaryDirectory.

High
High-level
Refactor complex methods into classes

To improve code structure and adhere to the Single Responsibility Principle,
encapsulate related logic from large classes like IdXML and MzTabIndexer into
new, dedicated classes such as ModificationParser or MzTabProcessor.

Examples:

quantmsio/core/quantms/mztab.py [637-910]
    def _process_mztab_to_parquet(self):
        """
        Process mzTab file to parquet files in batches.

        This method orchestrates the processing of mzTab files by coordinating
        setup, file processing, batch writing, and cleanup operations.

        Returns:
            tuple: A tuple containing paths to the created parquet files:
                - metadata_parquet (Path): Path to metadata.parquet

 ... (clipped 264 lines)
quantmsio/core/idxml.py [261-401]
    def _extract_modification_info(self, modification):
        """
        Extract name, accession, and ID from an OpenMS modification object.

        :param modification: OpenMS modification object
        :return: Tuple of (mod_name, mod_accession, mod_id)
        """
        mod_name = (
            modification.getId() or modification.getFullId() or modification.getName()
        )

 ... (clipped 131 lines)

Solution Walkthrough:

Before:

class MzTabIndexer(DuckDB):
    # ... other methods ...

    def _process_mztab_to_parquet(self):
        context = self._setup_processing_environment()
        try:
            self._process_mztab_file(context)
            self._write_final_batches(context)
        finally:
            self._cleanup_processing_resources(context)
        # ...

    # Many new private helper methods for parsing
    def _setup_processing_environment(self): ...
    def _process_mztab_file(self, context): ...
    def _process_single_line(self, line, context, line_num): ...
    def _process_metadata_line(self, line, context): ...
    def _process_protein_line(self, line, context): ...
    # ... and many more ...

After:

class MzTabFileProcessor:
    def __init__(self, mztab_path, batch_size, output_dir):
        # ... state for processing ...

    def process(self):
        # Main orchestration logic for parsing the file
        ...

    def _process_single_line(self, line, context, line_num): ...
    # ... other private helpers for parsing ...

class MzTabIndexer(DuckDB):
    # ... other methods ...

    def _process_mztab_to_parquet(self):
        output_dir = self._get_output_dir()
        processor = MzTabFileProcessor(
            self._mztab_path, self._batch_size, output_dir
        )
        processor.process()
        # ...
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies that the PR's refactoring, while positive, has increased the complexity of large classes like MzTabIndexer and IdXML. Proposing to extract related logic into dedicated classes is a significant design improvement that enhances modularity and adheres to the Single Responsibility Principle.

Medium
Possible issue
Initialize new columns with appropriate types

Initialize new DataFrame columns with type-appropriate empty values like pd.NA
or empty lists instead of None to ensure type consistency and prevent potential
downstream errors.

quantmsio/core/quantms/feature.py [718-727]

-# TODO Add additional fields with default values
-msstats.loc[:, "additional_intensities"] = None
-msstats.loc[:, "predicted_rt"] = None
-msstats.loc[:, "gg_accessions"] = None
-msstats.loc[:, "gg_names"] = None
-msstats.loc[:, "rt_start"] = None
-msstats.loc[:, "rt_stop"] = None
-msstats.loc[:, "ion_mobility"] = None
-msstats.loc[:, "start_ion_mobility"] = None
-msstats.loc[:, "stop_ion_mobility"] = None
+# Add additional fields with default values
+msstats["additional_intensities"] = [[] for _ in range(len(msstats))]
+msstats["predicted_rt"] = pd.NA
+msstats["gg_accessions"] = [[] for _ in range(len(msstats))]
+msstats["gg_names"] = [[] for _ in range(len(msstats))]
+msstats["rt_start"] = pd.NA
+msstats["rt_stop"] = pd.NA
+msstats["ion_mobility"] = pd.NA
+msstats["start_ion_mobility"] = pd.NA
+msstats["stop_ion_mobility"] = pd.NA

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that initializing columns with None can lead to type inconsistencies and proposes using type-appropriate empty values (pd.NA, empty lists), which improves robustness for downstream operations like Parquet conversion.

Medium
  • Update

@ypriverol
ypriverol requested a review from Copilot September 25, 2025 15:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull Request Overview

Implements security and maintainability improvements based on CodeFactor analysis, addressing insecure temporary file creation, refactoring large methods, and enhancing error handling specificity.

  • Replaces insecure tempfile.mktemp() with secure tempfile.NamedTemporaryFile() across all files
  • Extracts large methods into smaller, focused helper functions to improve maintainability
  • Improves error handling with specific exception types instead of generic Exception catches

Reviewed Changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
quantms.py Secure temp file creation in quantms commands
openms.py Specific exception handling for meta value extraction
idxml.py Refactored modification parsing into helper methods
feature.py Extracted modification processing into smaller functions
mztab.py Decomposed large mzTab processing method
psm.py Modularized metadata modification parsing
mztab_utils.py Refactored OpenMS modification parsing logic
test files Updated temp file handling in all test files
test_duckdb_creation.py Enhanced cleanup error handling specificity
test_msstats_in.py Extracted channel statistics processing functions

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment on lines +108 to +112
temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False)
temp_db_path = temp_db_file.name
temp_db_file.close()
if os.path.exists(temp_db_path):
os.unlink(temp_db_path)

Copilot AI Sep 25, 2025

Copy link

Choose a reason for hiding this comment

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

The pattern of creating a temporary file only to immediately close it and potentially delete it creates race conditions and unnecessary complexity. Consider using tempfile.NamedTemporaryFile with a context manager for proper resource management, or use tempfile.mkstemp() if you need the file to persist.

Suggested change
temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False)
temp_db_path = temp_db_file.name
temp_db_file.close()
if os.path.exists(temp_db_path):
os.unlink(temp_db_path)
fd, temp_db_path = tempfile.mkstemp(suffix=".duckdb")
os.close(fd)

Copilot uses AI. Check for mistakes.
Comment on lines +28 to +32
temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False)
temp_db_path = temp_db_file.name
temp_db_file.close()
if os.path.exists(temp_db_path):
os.unlink(temp_db_path)

Copilot AI Sep 25, 2025

Copy link

Choose a reason for hiding this comment

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

The pattern of immediately deleting a file after creating it defeats the purpose of secure temporary file creation. Consider using tempfile.mkstemp() which returns a file descriptor and path, or restructure to use the temporary file properly.

Suggested change
temp_db_file = tempfile.NamedTemporaryFile(suffix=".duckdb", delete=False)
temp_db_path = temp_db_file.name
temp_db_file.close()
if os.path.exists(temp_db_path):
os.unlink(temp_db_path)
fd, temp_db_path = tempfile.mkstemp(suffix=".duckdb")
os.close(fd)

Copilot uses AI. Check for mistakes.
def parse_modifications_openms(
def _create_mod_name_to_accession_map(reference_modifications: dict) -> dict:
"""Create a mapping from modification name to accession."""
return {val[0]: key for key, val in reference_modifications.items()}

Copilot AI Sep 25, 2025

Copy link

Choose a reason for hiding this comment

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

This function assumes that val is a sequence with at least one element, but no validation is performed. If any value in reference_modifications is None, an empty sequence, or not indexable, this will raise an IndexError or TypeError.

Suggested change
return {val[0]: key for key, val in reference_modifications.items()}
return {
val[0]: key
for key, val in reference_modifications.items()
if isinstance(val, (list, tuple)) and len(val) > 0
}

Copilot uses AI. Check for mistakes.
Comment on lines +82 to +83
if os.path.exists(temp_db_path):
os.unlink(temp_db_path)

Copilot AI Sep 25, 2025

Copy link

Choose a reason for hiding this comment

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

This pattern is repeated multiple times throughout the test file. Consider extracting it into a helper function to eliminate code duplication and improve maintainability.

Suggested change
if os.path.exists(temp_db_path):
os.unlink(temp_db_path)
cleanup_test_resources(temp_db_path=temp_db_path)

Copilot uses AI. Check for mistakes.
Comment on lines +186 to +191
def _extract_modification_values(self, row_value):
"""Extract accession and name from row value."""
values = row_value.replace("[", "").replace("]", "").split(",")
if len(values) >= 3:
return values[1].strip(), values[2].strip()
return None, None

Copilot AI Sep 25, 2025

Copy link

Choose a reason for hiding this comment

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

The function accesses values[1] and values[2] after only checking len(values) >= 3. If values has exactly 3 elements (indices 0, 1, 2), accessing index 2 is valid, but the logic suggests it should check for at least 3 elements. Consider clarifying the required format or adjusting the validation.

Copilot uses AI. Check for mistakes.
Comment on lines +658 to +660
except (AttributeError, RuntimeError, OSError):
# Ignore cleanup errors - connection may already be closed or invalid
pass

Copilot AI Sep 25, 2025

Copy link

Choose a reason for hiding this comment

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

[nitpick] While the specific exception types are more appropriate than generic Exception, consider logging the cleanup failure at a DEBUG level rather than silently ignoring all exceptions, as this could help diagnose resource leaks or other issues during development.

Copilot uses AI. Check for mistakes.
@ypriverol
ypriverol merged commit 9309c24 into bigbio:dev Sep 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants