Skip to content

fix(ProSE): per-file output isolation, dangling decoy refs, FDR:PSM deferral (#9197) - #9201

Closed
timosachsenberg wants to merge 12 commits into
developfrom
feat/prose-9197-fixes
Closed

timosachsenberg wants to merge 12 commits into
developfrom
feat/prose-9197-fixes

Conversation

@timosachsenberg

@timosachsenberg timosachsenberg commented Apr 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes items 1 and 3 of #9197.

Summary

  • Fix 1a — write-order isolation: -out_merged write failure no longer discards per-file outputs. Per-file -out_idxml/-out_pin/-out_qpx/-out_parquet writes now complete before the merged write is attempted, and the merged write is wrapped in try/catch so its failure becomes a logged error rather than a terminal exception.
  • Fix 1b — dangling decoy refs: merged idXML write no longer crashes with Invalid protein reference 'DECOY_...' when target+decoy shared peptides are present and FDR:protein > 0. applyPickedProteinFDR deletes decoy ProteinHits while removeDecoyHits keeps target+decoy PSMs (their target_decoy meta is target+decoy, not decoy), so kept PSMs retain PeptideEvidence entries pointing at deleted decoy proteins. Added IDFilter::removeDanglingProteinReferences pass after decoy/protein cleanup.
  • Fix 3 — FDR:PSM deferral: mirror the existing FDR:protein deferral. With -percolator_executable set, FDR:PSM is now zeroed in the search params before ProSEAlgorithm::run() and re-applied per-file using Percolator q-values. Previously FDR:PSM stripped decoys pre-Percolator and the rescoring silently failed with No decoys found.
  • BREAKING (minor): -out_pin now contains raw HyperScore PSMs even when -percolator_executable is set, matching the parameter's "external rescoring input" semantic. Use -out_idxml for Percolator-rescored output.

Architecture

Per-file output loop body order is now:

  1. Write -out_pin (raw HyperScore — preserves "external rescoring input" semantic)
  2. Run PercolatorAdapter (mutates result.peptide_ids in place)
  3. Re-apply deferred FDR:PSM cutoff using Percolator q-values
  4. Write -out_idxml / -out_qpx / -out_parquet (rescored, FDR-filtered)

The hoisted decoy check stays before the loop (whole-run decision). Skipped/failed Percolator paths log explicitly that the deferred FDR:PSM cutoff was not applied. Percolator-success uses stage-then-swap so a throwing loadIdentifications leaves the raw HyperScore result intact.

The merged-write block moved AFTER the per-file loop and is wrapped in try/catch so its failure does not propagate.

Test Plan

  • All 20 TOPP_ProSE_* topp tests pass against the branch (existing fixtures don't exercise Percolator or target+decoy paths, so they're unchanged)
  • Manual: rerun the original repro (multi-file MHC-I with Percolator, FDR:PSM > 0, FDR:protein > 0, decoys present, shared target+decoy peptides) — verify per-file outputs land on disk regardless of merged-write outcome AND verify merged write succeeds
  • Manual: -out_pin content check — confirm it contains raw HyperScore even when -percolator_executable is set
  • Manual: -percolator_executable with FDR:PSM=0.05 — confirm Percolator runs successfully (decoys present at runtime) and per-file idXML is q-value filtered

Out of scope (tracked separately)

Spec & plan

Brainstormed design and implementation plan are checked into docs/superpowers/specs/2026-04-21-prose-9197-fixes-design.md and docs/superpowers/plans/2026-04-21-prose-9197-fixes.md.

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Per-file outputs are now protected from loss if merged output operations encounter errors.
    • Fixed crash issues that could occur during merged output file generation.
    • Corrected FDR:PSM rescoring control flow when using external Percolator rescoring.
  • Updated Features

    • -out_pin output semantics updated: now contains raw PSM results for external Percolator rescoring workflows.

timosachsenberg and others added 12 commits April 21, 2026 09:55
Captures the brainstormed approach for accommodating bigbio/msgfplus PR #23
(pin-as-default output, no more mzid). Single PR, additive: variant probe at
startup branches between the existing mzid path and a new pin path that reuses
PercolatorInfile::load() (same as SageAdapter). Covers parameter surface,
validation matrix, feature-set extension, redundancy analysis, testing, and
risks.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Captures the brainstormed approach for: (1a) write-order isolation so
merged-write failure doesn't discard per-file outputs, (1b) calling
IDFilter::removeDanglingProteinReferences to fix the target+decoy
peptide-evidence dangling-pointer crash that triggered the original
issue, (3) extending the FDR:protein deferral pattern to FDR:PSM with
post-Percolator re-application using q-values. Also moves -out_pin
above Percolator so pin contains raw HyperScore as the "external
rescoring input" semantic intends.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Sharpen item 1b mechanism: applyPickedProteinFDR drops decoy ProteinHits
  via setScoresAndRemoveDecoys_; filterHitsByScore drops below-cutoff
  targets. Net: decoy proteins gone from merged list. Note bug only
  triggers with FDR:protein > 0.
- Sharpen item 3 mechanism: wrapper zeros FDR:protein but not FDR:PSM;
  ProSEAlgorithm's removeDecoyHits is conditional on fdr_protein_ == 0.0
  and triggers because the wrapper zeroed it.
- Add edge case: has_decoys_for_percolator == false + FDR:PSM > 0 →
  deferred FDR never applied. Add warning at decoy-check site.
- Add edge case: -out_pin only + Percolator fails.
- Reframe "some Percolator runs fail" as direct consequence of design,
  not pre-existing concern. Cross-reference #9198 for the long-term
  internal-PEP/FDR fallback.
- Note that ProSE.cpp:NNN references are to pre-patch state.
Six tasks: extend FDR:PSM deferral (task 1), add removeDanglingProteinReferences
(task 2), wrap+move merged-write block (task 3), restructure per-file loop with
pin first + Percolator inlined + post-Percolator FDR re-apply (task 4),
verification (task 5), CHANGELOG (task 6).
Mirror the existing FDR:protein deferral so PSM-level FDR doesn't strip
decoys inside ProSEAlgorithm before Percolator can use them. The deferred
cutoff is re-applied per-file after Percolator returns success (next commit).
Fixes 'Invalid protein reference DECOY_...' crash when merged path runs
applyPickedProteinFDR (deletes decoy ProteinHits) and target+decoy PSMs
remain (kept by removeDecoyHits's exact-match check on target_decoy=='decoy').

Refs OpenMS#9197 item 1b.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…catch

Fixes data loss on merged-write failure: previously a merged-write exception
aborted main_ and discarded per-file outputs even when per-file PSMs were
already complete in memory. Per-file writes now complete first and the merged
write is wrapped in try/catch so its failure becomes a logged error rather
than a terminal exception.

Refs OpenMS#9197 item 1a.
Don't claim per-file outputs were 'written successfully' — input_failed
may be true for one or more files. Direct user to check per-file errors
above.
… re-apply

The standalone Percolator loop (previously between the Algorithm run and the
per-file output writes) is removed. Per-file loop body order is now:

  1. write -out_pin (raw HyperScore — matches 'external rescoring input' semantic)
  2. run PercolatorAdapter (mutates result in place)
  3. re-apply deferred FDR:PSM cutoff using Percolator q-values
  4. write -out_idxml / -out_qpx / -out_parquet (rescored, FDR-filtered)

The hoisted decoy check is preserved before the loop (whole-run decision).
Skipped/failed Percolator paths now log explicitly that the deferred
FDR:PSM cutoff was not applied.

BREAKING (minor): -out_pin now contains raw HyperScore even when
-percolator_executable is set. Use -out_idxml for Percolator-rescored output.

Refs OpenMS#9197 items 1a (data loss eliminated by sibling-isolation)
and 3 (FDR:PSM deferral implemented end-to-end).
If FileHandler::storeIdentifications threw before runExternalProcess_,
tmp_in was created but never removed. Wrap the Percolator block in
try/catch with unconditional File::remove cleanup outside the try.
Also add a comment noting Percolator failure is intentionally a soft
failure (raw HyperScore is acceptable fallback output).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Stage loadIdentifications/keepNBestHits into local temporaries; only
swap into result.protein_ids/peptide_ids on full success. Previously,
result was cleared before the reload, so a throwing loadIdentifications
left result empty — silently losing per-file PSMs and dropping that
file's contributions from the merged output.

Fixes data-loss path flagged in final review.
@coderabbitai

coderabbitai Bot commented Apr 22, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR addresses ProSE/TOPP output generation and FDR rescoring for issue #9197. Per-file outputs are now written before merged output with try/catch protection. FDR:PSM deferral during Percolator rescoring is implemented with per-file re-application. Dangling protein reference cleanup is added to merged output. MSGFPlusAdapter PIN variant support is designed.

Changes

Cohort / File(s) Summary
CHANGELOG and Documentation
CHANGELOG, docs/superpowers/plans/2026-04-21-prose-9197-fixes.md, docs/superpowers/specs/2026-04-21-prose-9197-fixes-design.md, docs/superpowers/specs/2026-04-21-msgfplus-pin-support-design.md
Added ProSE issue #9197 implementation plan and specification documents detailing per-file output sequencing, FDR:PSM deferral/re-application with Percolator, merged-output try/catch protection, and dangling-protein-reference cleanup. Added MSGFPlusAdapter PIN variant support design spec with runtime MS-GF+ detection and .pin file loading. Added CHANGELOG entry summarizing ProSE output and FDR rescoring fixes.
ProSE Implementation
src/topp/ProSE.cpp
Refactored Percolator rescoring control flow: deferred FDR:PSM when -percolator_executable is set; repositioned per-file idXML/pin writing to occur after rescoring with soft-failure exception handling; moved merged output logic after per-file processing with try/catch wrapper and added IDFilter::removeDanglingProteinReferences call to prevent invalid protein reference crashes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ProSE
    participant OutputWriter as Per-File Output
    participant Percolator
    participant IDFilter
    participant MergedWriter as Merged Output
    
    User->>ProSE: Run with -percolator_executable
    
    loop Per-file processing
        ProSE->>OutputWriter: Write raw .pin (HyperScore PSMs)<br/>before rescoring
        OutputWriter-->>ProSE: .pin written
        
        ProSE->>Percolator: Run rescoring (FDR:PSM deferred)
        alt Percolator succeeds
            Percolator-->>ProSE: q-values returned
            ProSE->>IDFilter: Re-apply FDR:PSM<br/>using Percolator q-values
            IDFilter-->>ProSE: Filtered results
        else Percolator fails
            Percolator--X ProSE: Exception caught
            ProSE-->>ProSE: Keep raw results,<br/>skip FDR:PSM re-application
        end
        
        ProSE->>OutputWriter: Write per-file idXML/qpx/parquet<br/>(with or without rescoring)
        OutputWriter-->>ProSE: Per-file outputs written
    end
    
    ProSE->>MergedWriter: Attempt merged idXML write<br/>(with try/catch protection)
    
    alt Merged write succeeds
        rect rgba(100, 200, 100, 0.5)
            MergedWriter->>IDFilter: Call removeDanglingProteinReferences
            IDFilter-->>MergedWriter: References cleaned
        end
        MergedWriter-->>ProSE: Merged idXML written
    else Merged write fails
        rect rgba(200, 100, 100, 0.5)
            MergedWriter--X ProSE: Exception caught & logged
        end
        ProSE-->>User: Per-file outputs preserved,<br/>merged output not produced
    end
    
    ProSE-->>User: Completed (per-file outputs guaranteed)
Loading

Possibly related issues

Possibly related PRs

Suggested reviewers

  • jcharkow

Poem

🐰 Per-file first, then merge with care,
A try/catch wraps the output pair,
FDR defers till Percolator's done,
Dangling proteins cleaned—no crashes, none!
ProSE hops safely through the lane,
Where outputs thrive and data's sane. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main changes: per-file output isolation, dangling decoy reference fixes, and FDR:PSM deferral, with the issue number.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/prose-9197-fixes
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch feat/prose-9197-fixes

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
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (1)
src/topp/ProSE.cpp (1)

288-292: ⚠️ Potential issue | 🔴 Critical

Guard empty protein identifications before indexing.

Line 291 indexes pf.protein_ids[0] after only checking exit_code. A successful empty/no-hit result can make the decoy prescreen crash before any per-file outputs are written.

Proposed fix
         for (const auto& pf : mfres.per_file)
         {
-          if (pf.exit_code != ProSEAlgorithm::ExitCodes::EXECUTION_OK) continue;
+          if (pf.exit_code != ProSEAlgorithm::ExitCodes::EXECUTION_OK || pf.protein_ids.empty())
+          {
+            continue;
+          }
           for (const auto& ph : pf.protein_ids[0].getHits())
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/topp/ProSE.cpp` around lines 288 - 292, The loop indexes
pf.protein_ids[0] without checking for empty protein identifications; update the
loop over mfres.per_file so after confirming pf.exit_code ==
ProSEAlgorithm::ExitCodes::EXECUTION_OK you also guard that pf.protein_ids is
non-empty and that pf.protein_ids[0] contains hits (e.g., check
!pf.protein_ids.empty() and !pf.protein_ids[0].getHits().empty()) before
iterating over pf.protein_ids[0].getHits(); place this check immediately before
the inner for (const auto& ph : pf.protein_ids[0].getHits()) to avoid crashes
when a successful result has no protein IDs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/topp/ProSE.cpp`:
- Around line 638-698: The catch block that handles failures writing out_merged
currently logs the error but doesn't update the merged_ok flag, allowing
EXECUTION_OK to be returned; modify the catch in ProSE.cpp (the catch(const
Exception::BaseException& e) after FileHandler().storeIdentifications for
out_merged) to set merged_ok = false (and optionally set any overall exit status
variable you use for merged outputs) immediately after logging, preserving the
existing comment about not propagating the exception so per-file outputs remain
written.
- Around line 477-485: After calling
IDFilter::filterHitsByScore(result.peptide_ids, user_psm_fdr) and
IDFilter::removeEmptyIdentifications(result.peptide_ids) you must also remove
proteins that are no longer referenced by any remaining PSMs: invoke
IDFilter::removeUnreferencedProteins(result.protein_ids, result.peptide_ids) (or
the equivalent method that prunes protein_ids based on peptide_ids) to drop
orphaned proteins/groups so subsequent writers (idXML/QPX/parquet) do not see
stale protein-level entries; place this call immediately after
removeEmptyIdentifications and keep the existing INFO log.

---

Outside diff comments:
In `@src/topp/ProSE.cpp`:
- Around line 288-292: The loop indexes pf.protein_ids[0] without checking for
empty protein identifications; update the loop over mfres.per_file so after
confirming pf.exit_code == ProSEAlgorithm::ExitCodes::EXECUTION_OK you also
guard that pf.protein_ids is non-empty and that pf.protein_ids[0] contains hits
(e.g., check !pf.protein_ids.empty() and !pf.protein_ids[0].getHits().empty())
before iterating over pf.protein_ids[0].getHits(); place this check immediately
before the inner for (const auto& ph : pf.protein_ids[0].getHits()) to avoid
crashes when a successful result has no protein IDs.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 33a2edfb-41a9-4b9d-a482-5f751a637939

📥 Commits

Reviewing files that changed from the base of the PR and between c162f2d and 93319f4.

📒 Files selected for processing (5)
  • CHANGELOG
  • docs/superpowers/plans/2026-04-21-prose-9197-fixes.md
  • docs/superpowers/specs/2026-04-21-msgfplus-pin-support-design.md
  • docs/superpowers/specs/2026-04-21-prose-9197-fixes-design.md
  • src/topp/ProSE.cpp

Comment thread src/topp/ProSE.cpp
Comment on lines +477 to +485
// -- Re-apply deferred PSM FDR using Percolator q-values (post-rescoring) --
if (percolator_succeeded && user_psm_fdr > 0.0)
{
IDFilter::filterHitsByScore(result.peptide_ids, user_psm_fdr);
IDFilter::removeEmptyIdentifications(result.peptide_ids);
OPENMS_LOG_INFO << "[ProSE] " << in_file
<< ": applied deferred FDR:PSM=" << user_psm_fdr
<< " using Percolator q-values." << endl;
}

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.

⚠️ Potential issue | 🟠 Major

Remove proteins orphaned by deferred PSM FDR.

After filterHitsByScore() and removeEmptyIdentifications(), result.protein_ids can still contain proteins/groups supported only by removed PSMs. The later idXML/QPX/parquet writers then see stale protein-level data for the per-file output.

Proposed fix
         if (percolator_succeeded && user_psm_fdr > 0.0)
         {
           IDFilter::filterHitsByScore(result.peptide_ids, user_psm_fdr);
           IDFilter::removeEmptyIdentifications(result.peptide_ids);
+          IDFilter::removeUnreferencedProteins(result.protein_ids, result.peptide_ids);
           OPENMS_LOG_INFO << "[ProSE] " << in_file
                           << ": applied deferred FDR:PSM=" << user_psm_fdr
                           << " using Percolator q-values." << endl;
         }
📝 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
// -- Re-apply deferred PSM FDR using Percolator q-values (post-rescoring) --
if (percolator_succeeded && user_psm_fdr > 0.0)
{
IDFilter::filterHitsByScore(result.peptide_ids, user_psm_fdr);
IDFilter::removeEmptyIdentifications(result.peptide_ids);
OPENMS_LOG_INFO << "[ProSE] " << in_file
<< ": applied deferred FDR:PSM=" << user_psm_fdr
<< " using Percolator q-values." << endl;
}
// -- Re-apply deferred PSM FDR using Percolator q-values (post-rescoring) --
if (percolator_succeeded && user_psm_fdr > 0.0)
{
IDFilter::filterHitsByScore(result.peptide_ids, user_psm_fdr);
IDFilter::removeEmptyIdentifications(result.peptide_ids);
IDFilter::removeUnreferencedProteins(result.protein_ids, result.peptide_ids);
OPENMS_LOG_INFO << "[ProSE] " << in_file
<< ": applied deferred FDR:PSM=" << user_psm_fdr
<< " using Percolator q-values." << endl;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/topp/ProSE.cpp` around lines 477 - 485, After calling
IDFilter::filterHitsByScore(result.peptide_ids, user_psm_fdr) and
IDFilter::removeEmptyIdentifications(result.peptide_ids) you must also remove
proteins that are no longer referenced by any remaining PSMs: invoke
IDFilter::removeUnreferencedProteins(result.protein_ids, result.peptide_ids) (or
the equivalent method that prunes protein_ids based on peptide_ids) to drop
orphaned proteins/groups so subsequent writers (idXML/QPX/parquet) do not see
stale protein-level entries; place this call immediately after
removeEmptyIdentifications and keep the existing INFO log.

Comment thread src/topp/ProSE.cpp
Comment on lines +638 to +698
if (!out_merged.empty() && in_list.size() > 1)
{
try
{
const String decoy_prefix = search_params.getValue("decoy_prefix").toString();

// Merge per-file results via IDMergerAlgorithm (accession dedup + identifier remap)
IDMergerAlgorithm merger;
for (const auto& pf : mfres.per_file)
{
if (pf.exit_code != ProSEAlgorithm::ExitCodes::EXECUTION_OK) continue;
merger.insertRuns(pf.protein_ids, pf.peptide_ids);
}
ProteinIdentification merged_proteins;
PeptideIdentificationList merged_peptides;
merger.returnResultsAndClear(merged_proteins, merged_peptides);

vector<ProteinIdentification> merged_protein_ids = {std::move(merged_proteins)};
merged_protein_ids[0].setPrimaryMSRunPath(in_list);

// Protein inference: aggregate best PSM score per peptide per protein
BasicProteinInferenceAlgorithm bpia;
bpia.run(merged_peptides, merged_protein_ids);

// Optional picked-protein FDR
if (user_protein_fdr > 0.0)
{
FalseDiscoveryRate fdr;
fdr.applyPickedProteinFDR(merged_protein_ids[0], decoy_prefix, true);
IDFilter::filterHitsByScore(merged_protein_ids, user_protein_fdr);

OPENMS_LOG_INFO << "[ProSE] Merged protein inference + FDR: "
<< merged_protein_ids[0].getHits().size() << " proteins at "
<< user_protein_fdr * 100 << "% FDR" << endl;
}

// Clean up decoys in merged output
IDFilter::removeDecoyHits(merged_peptides);
IDFilter::removeEmptyIdentifications(merged_peptides);
IDFilter::removeUnreferencedProteins(merged_protein_ids, merged_peptides);
// Strip PeptideEvidence entries pointing to proteins removed by decoy/FDR
// cleanup (target+decoy PSMs kept by removeDecoyHits would otherwise leave
// dangling refs that IdXMLFile::store rejects).
IDFilter::removeDanglingProteinReferences(merged_peptides, merged_protein_ids);

if (getFlag_("test") && !merged_protein_ids.empty())
{
StringList basenames;
for (const auto& f : in_list) basenames.push_back("file://" + File::basename(f));
merged_protein_ids[0].setPrimaryMSRunPath(basenames);
}

FileHandler().storeIdentifications(out_merged, merged_protein_ids, merged_peptides, {FileTypes::IDXML});
}
catch (const Exception::BaseException& e)
{
OPENMS_LOG_ERROR << "Failed to write merged idXML output -> " << out_merged
<< ": " << e.what()
<< ". Per-file outputs were written (check above for any per-file errors)." << endl;
// Do NOT propagate; per-file outputs are already on disk.
}

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.

⚠️ Potential issue | 🟠 Major

Report merged idXML write failure in the final exit status.

The catch logs an error but leaves merged_ok unchanged, so ProSE can return EXECUTION_OK even when the requested -out_merged file was not produced. Keep the per-file preservation behavior, but mark the merged output as failed.

Proposed fix
         catch (const Exception::BaseException& e)
         {
           OPENMS_LOG_ERROR << "Failed to write merged idXML output -> " << out_merged
                            << ": " << e.what()
                            << ". Per-file outputs were written (check above for any per-file errors)." << endl;
+          merged_ok = false;
           // Do NOT propagate; per-file outputs are already on disk.
         }
📝 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
if (!out_merged.empty() && in_list.size() > 1)
{
try
{
const String decoy_prefix = search_params.getValue("decoy_prefix").toString();
// Merge per-file results via IDMergerAlgorithm (accession dedup + identifier remap)
IDMergerAlgorithm merger;
for (const auto& pf : mfres.per_file)
{
if (pf.exit_code != ProSEAlgorithm::ExitCodes::EXECUTION_OK) continue;
merger.insertRuns(pf.protein_ids, pf.peptide_ids);
}
ProteinIdentification merged_proteins;
PeptideIdentificationList merged_peptides;
merger.returnResultsAndClear(merged_proteins, merged_peptides);
vector<ProteinIdentification> merged_protein_ids = {std::move(merged_proteins)};
merged_protein_ids[0].setPrimaryMSRunPath(in_list);
// Protein inference: aggregate best PSM score per peptide per protein
BasicProteinInferenceAlgorithm bpia;
bpia.run(merged_peptides, merged_protein_ids);
// Optional picked-protein FDR
if (user_protein_fdr > 0.0)
{
FalseDiscoveryRate fdr;
fdr.applyPickedProteinFDR(merged_protein_ids[0], decoy_prefix, true);
IDFilter::filterHitsByScore(merged_protein_ids, user_protein_fdr);
OPENMS_LOG_INFO << "[ProSE] Merged protein inference + FDR: "
<< merged_protein_ids[0].getHits().size() << " proteins at "
<< user_protein_fdr * 100 << "% FDR" << endl;
}
// Clean up decoys in merged output
IDFilter::removeDecoyHits(merged_peptides);
IDFilter::removeEmptyIdentifications(merged_peptides);
IDFilter::removeUnreferencedProteins(merged_protein_ids, merged_peptides);
// Strip PeptideEvidence entries pointing to proteins removed by decoy/FDR
// cleanup (target+decoy PSMs kept by removeDecoyHits would otherwise leave
// dangling refs that IdXMLFile::store rejects).
IDFilter::removeDanglingProteinReferences(merged_peptides, merged_protein_ids);
if (getFlag_("test") && !merged_protein_ids.empty())
{
StringList basenames;
for (const auto& f : in_list) basenames.push_back("file://" + File::basename(f));
merged_protein_ids[0].setPrimaryMSRunPath(basenames);
}
FileHandler().storeIdentifications(out_merged, merged_protein_ids, merged_peptides, {FileTypes::IDXML});
}
catch (const Exception::BaseException& e)
{
OPENMS_LOG_ERROR << "Failed to write merged idXML output -> " << out_merged
<< ": " << e.what()
<< ". Per-file outputs were written (check above for any per-file errors)." << endl;
// Do NOT propagate; per-file outputs are already on disk.
}
if (!out_merged.empty() && in_list.size() > 1)
{
try
{
const String decoy_prefix = search_params.getValue("decoy_prefix").toString();
// Merge per-file results via IDMergerAlgorithm (accession dedup + identifier remap)
IDMergerAlgorithm merger;
for (const auto& pf : mfres.per_file)
{
if (pf.exit_code != ProSEAlgorithm::ExitCodes::EXECUTION_OK) continue;
merger.insertRuns(pf.protein_ids, pf.peptide_ids);
}
ProteinIdentification merged_proteins;
PeptideIdentificationList merged_peptides;
merger.returnResultsAndClear(merged_proteins, merged_peptides);
vector<ProteinIdentification> merged_protein_ids = {std::move(merged_proteins)};
merged_protein_ids[0].setPrimaryMSRunPath(in_list);
// Protein inference: aggregate best PSM score per peptide per protein
BasicProteinInferenceAlgorithm bpia;
bpia.run(merged_peptides, merged_protein_ids);
// Optional picked-protein FDR
if (user_protein_fdr > 0.0)
{
FalseDiscoveryRate fdr;
fdr.applyPickedProteinFDR(merged_protein_ids[0], decoy_prefix, true);
IDFilter::filterHitsByScore(merged_protein_ids, user_protein_fdr);
OPENMS_LOG_INFO << "[ProSE] Merged protein inference + FDR: "
<< merged_protein_ids[0].getHits().size() << " proteins at "
<< user_protein_fdr * 100 << "% FDR" << endl;
}
// Clean up decoys in merged output
IDFilter::removeDecoyHits(merged_peptides);
IDFilter::removeEmptyIdentifications(merged_peptides);
IDFilter::removeUnreferencedProteins(merged_protein_ids, merged_peptides);
// Strip PeptideEvidence entries pointing to proteins removed by decoy/FDR
// cleanup (target+decoy PSMs kept by removeDecoyHits would otherwise leave
// dangling refs that IdXMLFile::store rejects).
IDFilter::removeDanglingProteinReferences(merged_peptides, merged_protein_ids);
if (getFlag_("test") && !merged_protein_ids.empty())
{
StringList basenames;
for (const auto& f : in_list) basenames.push_back("file://" + File::basename(f));
merged_protein_ids[0].setPrimaryMSRunPath(basenames);
}
FileHandler().storeIdentifications(out_merged, merged_protein_ids, merged_peptides, {FileTypes::IDXML});
}
catch (const Exception::BaseException& e)
{
OPENMS_LOG_ERROR << "Failed to write merged idXML output -> " << out_merged
<< ": " << e.what()
<< ". Per-file outputs were written (check above for any per-file errors)." << endl;
merged_ok = false;
// Do NOT propagate; per-file outputs are already on disk.
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/topp/ProSE.cpp` around lines 638 - 698, The catch block that handles
failures writing out_merged currently logs the error but doesn't update the
merged_ok flag, allowing EXECUTION_OK to be returned; modify the catch in
ProSE.cpp (the catch(const Exception::BaseException& e) after
FileHandler().storeIdentifications for out_merged) to set merged_ok = false (and
optionally set any overall exit status variable you use for merged outputs)
immediately after logging, preserving the existing comment about not propagating
the exception so per-file outputs remain written.

@timosachsenberg

Copy link
Copy Markdown
Contributor Author

Superseded by #9205. After #9195 merged with a different approach for FDR:PSM deferral and the .pin column-set fix (items 3 + 4 of #9197), the remaining novel work in this PR is just items 1a (write-order isolation) and 1b (dangling decoy PeptideEvidence cleanup). Reopened as a tight 4-commit branch in #9205.

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.

1 participant