Skip to content

Expand unit test suite to 90 tests with numerical correctness coverage#25

Open
wsnoble wants to merge 9 commits into
masterfrom
add-unit-tests
Open

Expand unit test suite to 90 tests with numerical correctness coverage#25
wsnoble wants to merge 9 commits into
masterfrom
add-unit-tests

Conversation

@wsnoble

@wsnoble wsnoble commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

Add ~47 new tests across 6 files covering gaps identified in TESTING_PLAN.md:

  • test_confidence.py: Replace type-only stubs with exact q-value assertions, FDR threshold counts, monotonicity invariants, pep_fdr_type and prot_fdr_type parametrized coverage, and column-presence checks for threshold modes.
  • test_writers.py (new): File creation, column names, row counts, round-trip score fidelity, decoy flag, and threshold filtering.
  • test_edge_cases.py (new): Competition correctness, shared-peptide exclusion, empty/all-target/all-decoy construction errors, all-levels presence.
  • test_qvalues.py: Edge cases (all targets win, decoy wins, hand-computed 4T/2D case), monotonicity parametrize, _fdr2qvalue direct test.
  • test_dataset.py: No-decoys/no-targets ValueError, count correctness, peptide_pairing storage, missing column error, find_best_score edge case.
  • test_parsers.py: Multi-file concatenation, target-only raises, missing column error, copy_data=False, protein_delim storage.
  • conftest.py: Add clean_psm_df/clean_psms fixtures with hand-computed expected q-values (4 targets → q=0.25, 2 decoys → q=0.50/0.75).
  • SCALING_PLAN.md, TESTING_PLAN.md: Add planning documents.

Summary by CodeRabbit

  • Documentation

    • Added a “Crema Scaling Plan” for scaling the pipeline toward out-of-core execution (with phased work across parsing, computation, and formats).
    • Added a “Testing Plan” outlining a step-by-step roadmap to expand and strengthen automated test coverage.
  • Bug Fixes

    • Fixed PsmDataset.protein_delim to correctly return the configured delimiter.
    • Improved CLI reader selection to try all supported readers before failing.
  • New Features

    • Defined an explicit public API surface (__all__) for the crema package.
  • Tests

    • Expanded/rewritten unit and edge-case tests for confidence, datasets, parsers, q-values, and writers, with additional deterministic fixtures.

Add ~47 new tests across 6 files covering gaps identified in TESTING_PLAN.md:

- test_confidence.py: Replace type-only stubs with exact q-value assertions,
  FDR threshold counts, monotonicity invariants, pep_fdr_type and prot_fdr_type
  parametrized coverage, and column-presence checks for threshold modes.
- test_writers.py (new): File creation, column names, row counts, round-trip
  score fidelity, decoy flag, and threshold filtering.
- test_edge_cases.py (new): Competition correctness, shared-peptide exclusion,
  empty/all-target/all-decoy construction errors, all-levels presence.
- test_qvalues.py: Edge cases (all targets win, decoy wins, hand-computed
  4T/2D case), monotonicity parametrize, _fdr2qvalue direct test.
- test_dataset.py: No-decoys/no-targets ValueError, count correctness,
  peptide_pairing storage, missing column error, find_best_score edge case.
- test_parsers.py: Multi-file concatenation, target-only raises, missing
  column error, copy_data=False, protein_delim storage.
- conftest.py: Add clean_psm_df/clean_psms fixtures with hand-computed
  expected q-values (4 targets → q=0.25, 2 decoys → q=0.50/0.75).
- SCALING_PLAN.md, TESTING_PLAN.md: Add planning documents.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@wsnoble wsnoble requested a review from bmx8177 June 18, 2026 18:57
@coderabbitai

coderabbitai Bot commented Jun 18, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@wsnoble, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 57 minutes and 4 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 76945b42-9a8d-4d42-be26-0c91d2c8fbe0

📥 Commits

Reviewing files that changed from the base of the PR and between 925883b and 79d1cca.

📒 Files selected for processing (1)
  • crema/crema.py
📝 Walkthrough

Walkthrough

Adds two planning documents (SCALING_PLAN.md for a phased DuckDB out-of-core scaling roadmap, TESTING_PLAN.md for a structured test coverage roadmap), implements the testing plan with new shared fixtures and expanded/new test modules across q-values, dataset, parsers, confidence, writers, and edge cases, fixes a bug in PsmDataset.protein_delim property, and improves overall code quality through type annotations, parser cleanups, CLI enhancements, and workflow modernization.

Changes

Planning Documents

Layer / File(s) Summary
DuckDB scaling roadmap
SCALING_PLAN.md
Four-phase plan moving from pandas to DuckDB out-of-core execution: Phase 1 removes defensive copies and adds pyarrow CSV; Phase 2 adds streaming/chunked parsing and PsmDatasetStream; Phase 3 ports competition and FDR/q-value computation to SQL window functions; Phase 4 adds Parquet I/O. Includes backward compatibility policy and optional dependency table.
Unit/integration testing roadmap
TESTING_PLAN.md
Inventories existing test gaps and specifies ordered expansions for test_qvalues.py, test_dataset.py, test_parsers.py, test_confidence.py, test_writers.py, and test_edge_cases.py, with projected test counts and recommended implementation order.
Phase 1 implementation summary
PHASE1_SUMMARY.md
Documents Phase 1 completion: removes redundant dataset copying, changes copy_data default to False, adds optional pyarrow CSV parsing with fallback, and includes test cleanup. Adds PR workflow and verification checklist.

Test Implementation

Layer / File(s) Summary
Shared fixtures and dataset property fix
tests/conftest.py, crema/dataset.py
Adds PsmDataset import and two reusable fixtures: clean_psm_df (deterministic 6-spectrum target/decoy DataFrame) and clean_psms (PsmDataset wrapper with configured columns and protein_delim). Fixes protein_delim property to return the stored delimiter string instead of attempting to index _data with it. Updates PsmDataset.methods to use ClassVar typing.
q-values edge-case and monotonicity tests
tests/unit_tests/test_qvalues.py
Removes unused logging import and adds five tests: two single-spectrum TDC edge cases (target wins / decoy wins), a hand-computed 4-target/2-decoy scenario, parametrized monotonicity check across score orderings, unit-interval bounds assertion, and direct _fdr2qvalue monotone-output test.
Dataset validation and error handling tests
tests/unit_tests/test_dataset.py
Adds six tests covering PsmDataset constructor rejection of target-only/decoy-only inputs, _num_targets/_num_decoys count assertions, peptide_pairing persistence, missing score column error handling, and find_best_score RuntimeError at eval_fdr=0.
Parser behavior and multi-file tests
tests/unit_tests/test_parsers.py
Refactors test_read_pepxml call signature and adds five tests covering read_tide multi-file concatenation, target-only ValueError, read_txt missing-column error, copy_data=False shape/targets preservation, and protein_delim storage on the returned dataset.
Confidence numerical correctness and invariant tests
tests/unit_tests/test_confidence.py
Substantially expands coverage: adds psms_with_pairing fixture; exact PSM-level q-value/count/accept assertions; q-value bounds/monotonicity helper and invariants across PSM/peptide/protein levels; protein structural and prot_fdr_type parametrized tests; pep_fdr_type validation with and without pairing; invalid-param and threshold-mode negative tests; TDC vs Mixmax level-presence assertions; and target/decoy separation checks.
Writer output correctness and round-trip tests
tests/unit_tests/test_writers.py
New file testing to_txt: file creation with file_root prefixing and decoys=True, TSV schema validation (score/accept/file/scan in psms, protein column in proteins), row-count match against in-memory estimates, score round-trip correctness, and accept column counts at two FDR thresholds.
Edge-case competition, grouping, and constructor tests
tests/unit_tests/test_edge_cases.py
New file covering per-spectrum competition behavior (target wins / decoy wins), multiple-candidates-per-spectrum selection, multi-protein peptide exclusion from protein output, TDC confidence level key presence, constructor rejection of empty/target-only/decoy-only DataFrames, and PSM/peptide q-value monotonicity invariant.

Code Quality and Refactoring

Layer / File(s) Summary
Package exports and type annotations
crema/__init__.py, crema/dataset.py, crema/confidence.py
Introduces explicit __all__ list for public API exports. Adds ClassVar import and type annotations for PsmDataset.methods and Confidence._level_labs to improve introspection and IDE support.
Confidence module improvements
crema/confidence.py
Refactors _compete method to use argument spreading in sort_values and idiomatic boolean checks. Updates TdcConfidence._assign_confidence to use identity comparisons (is None), corrects error message typo, and refactors list construction. Updates MixmaxConfidence._assign_confidence with consistent identity checks and argument spreading for sorting/deduplication.
Parser cleanups and None checks
crema/parsers/*.py
Standardizes None checks across all parser modules (comet, msamanda, msfragger, msgf, mztab, tide, txt) to use identity comparisons. Removes unused imports (re) and variables (pairing). Refines MSAmanda fields list construction.
CLI reader fallback and q-values optimization
crema/crema.py, crema/qvalues.py
CLI now tries all reader functions and raises error only if all fail, enabling graceful fallback. q-values module simplifies mixmax p-value precomputation by using constant n_decoys=1 and removing redundant score tracking; optimizes calculate_mixmax_qval reverse-scan initialization.
CI/tooling modernization and cleanups
.github/workflows/tests.yml, pyproject.toml, setup.cfg, crema/params.py, crema/utils.py, tests/system_tests/test_cli.py
Updates GitHub Actions workflow to test Python 3.9–3.11, removes branch filtering, adds monthly schedule. Adds ruff configuration for linting with consistent line-length. Removes unused imports. Refactors loop variable naming for clarity. Uses argument unpacking in CLI test.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Poem

🐇 Hop hop, the tests now multiply,
Each q-value checked, no bug slips by.
DuckDB dreams in SCALING_PLAN,
While TESTING_PLAN maps out the span.
protein_delim fixed, the writers ring true—
Code shines bright with types anew! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the PR's primary change: expanding the unit test suite with numerical correctness coverage, growing from ~43 to ~90 tests.
Docstring Coverage ✅ Passed Docstring coverage is 85.56% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch add-unit-tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tests/unit_tests/test_writers.py (1)

1-152: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

This file currently fails CI formatting checks (Black).

Pipeline shows Black would reformat this file. Please run Black on this file before merge to unblock lint.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit_tests/test_writers.py` around lines 1 - 152, The test_writers.py
file fails Black formatting checks and needs to be reformatted to comply with
Black's code style standards. Run Black on this file to automatically fix all
formatting issues. This will ensure the file passes the CI linting checks before
merging.

Source: Pipeline failures

tests/unit_tests/test_edge_cases.py (1)

1-205: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

This file currently fails CI formatting checks (Black).

Pipeline shows Black would reformat this file. Please run Black on this file before merge to unblock lint.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit_tests/test_edge_cases.py` around lines 1 - 205, The test file
test_edge_cases.py is failing Black code formatting checks. Run the Black
formatter on this file to automatically fix all formatting issues. Use the
command black tests/unit_tests/test_edge_cases.py to reformat the entire file
according to Black's style guidelines, then commit the changes. This will
resolve the CI lint failure blocking the merge.

Source: Pipeline failures

🧹 Nitpick comments (1)
tests/unit_tests/test_confidence.py (1)

273-274: ⚡ Quick win

len(...) >= 0 is tautological and does not validate behavior.

This assertion always passes and adds no signal. Replace it with a non-empty or schema/value invariant assertion.

Proposed fix
-    assert len(conf.confidence_estimates["peptides"]) >= 0
+    assert len(conf.confidence_estimates["peptides"]) > 0
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit_tests/test_confidence.py` around lines 273 - 274, The assertion
checking len(conf.confidence_estimates["peptides"]) >= 0 is tautological because
len() always returns a non-negative value, making the assertion always pass
without validating actual behavior. Replace this assertion with a meaningful
check such as asserting the list is non-empty (len > 0) or validating a specific
schema or value invariant that confirms the confidence_estimates["peptides"]
contains the expected data structure.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/unit_tests/test_confidence.py`:
- Around line 359-368: The assertion in the
test_confidence_estimates_contains_only_targets function currently validates
only scan numbers as a subset of expected values, which doesn't directly verify
that rows are actually marked as targets. Replace the scan number subset
assertion with a direct check of the target column in psm_df to ensure all rows
have target set to True. Apply the same fix to the similar assertions around
lines 371-379 that also rely on indirect scan number validation instead of
checking the target flag directly.

In `@tests/unit_tests/test_dataset.py`:
- Around line 103-104: Remove the explicit `== True` comparison in the boolean
filter condition on simple_df and use the column directly (e.g.,
simple_df["target"] instead of simple_df["target"] == True), then convert the
regex pattern string in the pytest.raises match parameter to a raw string by
prefixing it with r (e.g., r"[Nn]o decoy" instead of "[Nn]o decoy"). Apply these
same fixes to the similar violations mentioned at lines 118-119.

In `@tests/unit_tests/test_parsers.py`:
- Line 161: The pytest.raises match parameter on the line with the ValueError
assertion is using a regular string instead of a raw string for the regex
pattern, which triggers Ruff RUF043. Change the match parameter from a regular
string to a raw string by adding the r prefix before the opening quote in the
match argument where it contains the pattern "[Nn]o decoy".
- Line 211: Replace the assertion that directly accesses the private attribute
_protein_delim with an assertion using the public protein_delim interface.
Change assert psms._protein_delim == ";" to assert psms.protein_delim == ";" to
test the public API contract instead of internal implementation details. This
change will expose the upstream bug in crema/dataset.py where the protein_delim
property is incorrectly implemented.

---

Outside diff comments:
In `@tests/unit_tests/test_edge_cases.py`:
- Around line 1-205: The test file test_edge_cases.py is failing Black code
formatting checks. Run the Black formatter on this file to automatically fix all
formatting issues. Use the command black tests/unit_tests/test_edge_cases.py to
reformat the entire file according to Black's style guidelines, then commit the
changes. This will resolve the CI lint failure blocking the merge.

In `@tests/unit_tests/test_writers.py`:
- Around line 1-152: The test_writers.py file fails Black formatting checks and
needs to be reformatted to comply with Black's code style standards. Run Black
on this file to automatically fix all formatting issues. This will ensure the
file passes the CI linting checks before merging.

---

Nitpick comments:
In `@tests/unit_tests/test_confidence.py`:
- Around line 273-274: The assertion checking
len(conf.confidence_estimates["peptides"]) >= 0 is tautological because len()
always returns a non-negative value, making the assertion always pass without
validating actual behavior. Replace this assertion with a meaningful check such
as asserting the list is non-empty (len > 0) or validating a specific schema or
value invariant that confirms the confidence_estimates["peptides"] contains the
expected data structure.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b48037b7-317f-4b71-ace0-69a5310af4c2

📥 Commits

Reviewing files that changed from the base of the PR and between f15785d and 39f46d0.

📒 Files selected for processing (9)
  • SCALING_PLAN.md
  • TESTING_PLAN.md
  • tests/conftest.py
  • tests/unit_tests/test_confidence.py
  • tests/unit_tests/test_dataset.py
  • tests/unit_tests/test_edge_cases.py
  • tests/unit_tests/test_parsers.py
  • tests/unit_tests/test_qvalues.py
  • tests/unit_tests/test_writers.py

Comment thread tests/unit_tests/test_confidence.py Outdated
Comment thread tests/unit_tests/test_dataset.py Outdated
Comment thread tests/unit_tests/test_parsers.py Outdated
Comment thread tests/unit_tests/test_parsers.py Outdated
wsnoble and others added 3 commits June 18, 2026 13:31
- Run Black on test_writers.py and test_edge_cases.py (CI formatting failures)
- Fix tautological assert (>= 0 → > 0) in test_pep_fdr_type_with_pairing
- Use boolean indexing instead of == True/False in test_dataset.py (E712)
- Use raw strings for pytest.raises match= regex (RUF043) in test_dataset.py
  and test_parsers.py
- Improve target/decoy separation assertions: _prettify_tables strips the
  target column from output DataFrames, so use peptide names to distinguish
  targets (PEP1-6) from decoys (PEP1D-6D) in the clean_psms fixture

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Local Black was 21.10b0; CI runs the latest stable (26.x). Reformatted
5 files to resolve lint failures:
- tests/conftest.py: Remove extra alignment spaces in list literals
- tests/unit_tests/test_confidence.py: Fix blank line placement around sections
- tests/unit_tests/test_edge_cases.py: Reformat dict literals in parametrize
- tests/unit_tests/test_qvalues.py: Break long tuples in parametrize args
- tests/unit_tests/test_writers.py: Remove extraneous blank line

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The protein_delim property was doing a column lookup (self[self._protein_delim])
instead of returning the delimiter string. Also update the corresponding test to
assert against the public property rather than the private attribute.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Expands Crema’s unit test coverage with a focus on numerical correctness and edge cases across q-value calculation, dataset/parsers validation, confidence estimation, and TXT output writing; also fixes PsmDataset.protein_delim to return the delimiter string correctly.

Changes:

  • Added substantial new unit tests for TDC/q-value correctness, monotonicity invariants, dataset/parser error handling, and TXT writer outputs.
  • Introduced deterministic clean_psm_df/clean_psms fixtures to support hand-computed expected q-values.
  • Fixed PsmDataset.protein_delim to return self._protein_delim (instead of indexing the dataset).

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/unit_tests/test_writers.py New writer tests validating output file creation, schema, and basic round-trip fidelity.
tests/unit_tests/test_qvalues.py Adds TDC edge-case and monotonicity tests plus direct _fdr2qvalue coverage.
tests/unit_tests/test_parsers.py Adds multi-file concatenation coverage and additional parser error-handling tests.
tests/unit_tests/test_edge_cases.py New cross-module edge-case coverage (competition, shared peptides, empty/degenerate datasets).
tests/unit_tests/test_dataset.py Adds dataset validation/error-handling tests and internal count/pairing checks.
tests/unit_tests/test_confidence.py Replaces type-only stubs with numerical correctness/invariant/parameter validation tests.
tests/conftest.py Adds deterministic fixtures used by multiple new correctness tests.
TESTING_PLAN.md New test roadmap/planning document.
SCALING_PLAN.md New scaling roadmap/planning document.
crema/dataset.py Bug fix: protein_delim property now returns the delimiter string.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/unit_tests/test_confidence.py Outdated
Comment on lines +65 to +67
def test_mixmax_confidence_desc(simple_psms: PsmDataset):
"""Test that we can compute confidence with `TdcConfidence`"""
simple_psms.data["x"] = -1.0 * simple_psms.data["x"]
# Use internal data to avoid the copy() on the .data property
simple_psms._data["x"] = -1.0 * simple_psms._data["x"]
wsnoble and others added 3 commits June 19, 2026 15:45
- Update tests.yml: trigger on all branches (not just master), test Python
  3.9/3.10/3.11, replace flake8 with ruff, upgrade action versions to v4/v5
- Add ruff config to setup.cfg (E/F/W/RUF rules, line-length=88, exclude docs/)
- Add __all__ to crema/__init__.py for explicit public API
- Fix E711/E712: replace == None / != None / == True / == False with
  is None / is not None / truthy checks throughout confidence.py and parsers
- Fix E722: bare except → except Exception in crema.py
- Fix E741: ambiguous variable l → line in params.py
- Fix F401: remove unused imports (re, itertools, pandas, numpy, logging, pytest)
  across parsers, utils, and test files
- Fix F841: remove unused local variable assignments in qvalues.py and parsers
- Fix RUF005/RUF017: list concatenation → unpacking in confidence.py, dataset.py

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Construct a fresh PsmDataset with negated x scores instead of writing
to _data directly, so the test doesn't depend on implementation details.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 28 out of 28 changed files in this pull request and generated 4 comments.

Comment thread crema/crema.py
Comment on lines 69 to 75
for read_fn in readers:
try:
psms = read_fn(args.psm_files)
break
except:
except Exception:
raise ValueError("Unrecognized file type.")

Comment thread crema/confidence.py

LOGGER.info("Building protein groups...")
protein_group, pep_to_prot = _group_proteins(
_protein_group, pep_to_prot = _group_proteins(
Comment thread crema/confidence.py
Comment thread tests/unit_tests/test_writers.py Outdated
Comment on lines +133 to +134
def test_to_txt_roundtrip_accept(clean_psms, tmp_path):
"""Scores written to file and read back must match in-memory values."""
- crema.py: parser loop now continues on failure and raises only after all
  readers are exhausted, restoring the fallback-to-next-reader behavior
- confidence.py: fix typo "infomation" → "information" in error message
- test_writers.py: rename test_to_txt_roundtrip_accept to
  test_to_txt_roundtrip_scores (it tests score values, not accept column)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 (2)
.github/workflows/tests.yml (1)

18-18: ⚡ Quick win

Disable credential persistence to prevent leakage.

The checkout action defaults to persisting GitHub credentials in the workspace, which could leak through artifacts or logs if accidentally referenced by subsequent steps.

🛡️ Proposed fix to disable credential persistence
     steps:
       - uses: actions/checkout@v4
+        with:
+          persist-credentials: false
       - name: Set up Python ${{ matrix.python-version }}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/tests.yml at line 18, In the actions/checkout@v4 step, add
the persist-credentials parameter set to false to prevent GitHub credentials
from being persisted in the workspace. This mitigates the risk of credential
leakage through artifacts or logs if subsequent workflow steps accidentally
reference sensitive information. Add persist-credentials: false as a
configuration parameter to the checkout action step.

Source: Linters/SAST tools

crema/crema.py (1)

69-78: ⚡ Quick win

Add debug logging when readers fail.

The updated control flow correctly tries all readers before failing, fixing the previous bug where the first reader failure would prevent subsequent readers from being attempted. However, when a reader fails, the exception is silently caught and the loop continues. This can make debugging difficult when the expected reader fails for an unexpected reason (e.g., corrupt file, missing required column).

Consider adding debug logging to track which readers were attempted and why they failed:

♻️ Suggested enhancement
 psms = None
 for read_fn in readers:
     try:
         psms = read_fn(args.psm_files)
+        logging.info("Successfully parsed file using %s", read_fn.__name__)
         break
-    except Exception:
+    except Exception as e:
+        logging.debug("Reader %s failed: %s", read_fn.__name__, str(e))
         continue
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crema/crema.py` around lines 69 - 78, In the exception handling block within
the for loop that iterates through readers, capture the exception being caught
in the except Exception clause and add debug logging statements that track which
reader was attempted (reference the read_fn to identify which reader is being
tried) and log the actual exception details and message. This will help with
debugging when a reader fails unexpectedly, such as due to a corrupt file or
missing required column.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/workflows/tests.yml:
- Line 18: Replace the version tag reference in the actions/checkout action
(currently using `@v4`) with a specific commit hash to prevent supply chain
attacks. Find the exact commit SHA that corresponds to v4 from the
actions/checkout repository, then update the uses statement to reference that
commit hash instead of the version tag, and add a comment on the same line
indicating which version the hash corresponds to (e.g., # v4). Apply the same
fix to any other action uses statements that reference version tags instead of
commit hashes, as indicated by the "Also applies to" note.

---

Nitpick comments:
In @.github/workflows/tests.yml:
- Line 18: In the actions/checkout@v4 step, add the persist-credentials
parameter set to false to prevent GitHub credentials from being persisted in the
workspace. This mitigates the risk of credential leakage through artifacts or
logs if subsequent workflow steps accidentally reference sensitive information.
Add persist-credentials: false as a configuration parameter to the checkout
action step.

In `@crema/crema.py`:
- Around line 69-78: In the exception handling block within the for loop that
iterates through readers, capture the exception being caught in the except
Exception clause and add debug logging statements that track which reader was
attempted (reference the read_fn to identify which reader is being tried) and
log the actual exception details and message. This will help with debugging when
a reader fails unexpectedly, such as due to a corrupt file or missing required
column.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 529b5d23-eb0c-4724-86be-5a752f00add0

📥 Commits

Reviewing files that changed from the base of the PR and between 0f2c4d8 and 925883b.

📒 Files selected for processing (24)
  • .github/workflows/tests.yml
  • PHASE1_SUMMARY.md
  • crema/__init__.py
  • crema/confidence.py
  • crema/crema.py
  • crema/dataset.py
  • crema/params.py
  • crema/parsers/comet.py
  • crema/parsers/msamanda.py
  • crema/parsers/msfragger.py
  • crema/parsers/msgf.py
  • crema/parsers/mztab.py
  • crema/parsers/tide.py
  • crema/parsers/txt.py
  • crema/qvalues.py
  • crema/utils.py
  • pyproject.toml
  • setup.cfg
  • tests/system_tests/test_cli.py
  • tests/unit_tests/test_confidence.py
  • tests/unit_tests/test_edge_cases.py
  • tests/unit_tests/test_parsers.py
  • tests/unit_tests/test_qvalues.py
  • tests/unit_tests/test_writers.py
💤 Files with no reviewable changes (4)
  • crema/parsers/msgf.py
  • crema/utils.py
  • crema/qvalues.py
  • tests/unit_tests/test_qvalues.py
✅ Files skipped from review due to trivial changes (8)
  • crema/parsers/txt.py
  • crema/init.py
  • PHASE1_SUMMARY.md
  • pyproject.toml
  • crema/parsers/tide.py
  • crema/parsers/mztab.py
  • crema/params.py
  • crema/parsers/msfragger.py
🚧 Files skipped from review as they are similar to previous changes (4)
  • tests/unit_tests/test_writers.py
  • tests/unit_tests/test_parsers.py
  • tests/unit_tests/test_edge_cases.py
  • tests/unit_tests/test_confidence.py

- name: Test with pytest
run: |
pytest
- uses: actions/checkout@v4

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Pin actions to commit hashes to prevent supply chain attacks.

Using version tags (v4, v5) instead of commit hashes allows an attacker who compromises the upstream action repository to push malicious code under the same tag. Pin to specific commit SHAs and include a comment with the version for maintainability.

🔒 Proposed fix to pin actions
     steps:
-      - uses: actions/checkout@v4
+      - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
       - name: Set up Python ${{ matrix.python-version }}
-        uses: actions/setup-python@v5
+        uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0
         with:

Also applies to: 20-20

🧰 Tools
🪛 zizmor (1.25.2)

[warning] 18-18: credential persistence through GitHub Actions artifacts (artipacked): does not set persist-credentials: false

(artipacked)


[error] 18-18: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)

(unpinned-uses)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/tests.yml at line 18, Replace the version tag reference in
the actions/checkout action (currently using `@v4`) with a specific commit hash to
prevent supply chain attacks. Find the exact commit SHA that corresponds to v4
from the actions/checkout repository, then update the uses statement to
reference that commit hash instead of the version tag, and add a comment on the
same line indicating which version the hash corresponds to (e.g., # v4). Apply
the same fix to any other action uses statements that reference version tags
instead of commit hashes, as indicated by the "Also applies to" note.

Source: Linters/SAST tools

Captures the exception from each failed reader so that users running
with --debug can see which parsers were tried and why they failed,
without changing behavior for normal use.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
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