Skip to content

[FEATURE] ThermoRawFile: read-ahead workers also read peaks for an MS-level-only selection - #10925

Merged
timosachsenberg merged 2 commits into
OpenMS:developfrom
singjc:feature/thermo-raw-level-readahead
Nov 17, 2026
Merged

timosachsenberg merged 2 commits into
OpenMS:developfrom
singjc:feature/thermo-raw-level-readahead

Conversation

@singjc

@singjc singjc commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Description

Problem

ThermoRawFile::transform with a scan selection by MS level only (Options::ms_levels, no RT or precursor m/z filter) switched peak prefetch off in ThermoRawScanReader::readAhead. The read-ahead workers then only read headers, and the consumer thread decoded the peaks of every selected scan itself.

Change

  • readAhead() takes the MS levels whose peaks should be prefetched. A worker reads the header first. For a scan at a selected level it then reads the peaks without trailer text (peakReadOptions(), the same read convert() does) and swaps them into the scan.
  • Every scan carries its own has_peaks flag. convert() reads the peaks itself whenever the workers did not, so output does not depend on the workers' choice.
  • The worker clamps the MS order like header() does: levels of 0 or below map to 0.
  • Only transform() uses this. load() and level filters combined with an RT or precursor range keep the previous header-only read-ahead.

Output spectra are unchanged.

Measured effect

ThermoRawFile::transform() into a consumer that only counts. The test file is a 3.1 GB Astral DIA .raw (292,883 MS2 and 2,928 MS1 scans), in the page cache. Laptop with 20 cores, while other jobs were running. Each version was run 3 times, alternating; the table shows the median, with the range in brackets.

selection threads develop first commit this PR
MS2 4 25.4 s (23.7-28.3) 19.0 s (17.6-20.3) 16.7 s (16.6-21.6)
MS1 4 9.1 s (8.2-9.7) 8.5 s (8.4-9.4) 9.0 s (8.4-9.3)
MS2 1 (no read-ahead) 29.8 s (27.6-35.8) 27.3 s (25.2-29.7) 27.2 s (24.2-29.8)
  • Spectrum count, peak count and a checksum over all m/z and intensity values are identical across all three versions.
  • The reviewer's measurement on an Orbitrap Velos file (PXD000001) shows the same pattern: MS2 −26 %, MS1 −16 %, MS1 profile −29 %.
  • In a downstream DIA workflow that streams MS2 only from the same Astral file, the wall time went from 8:06 to 7:18, with byte-identical results.

Tests

ThermoRawFile_test compares transform() with load() (which keeps the consumer-thread read) for:

  • ms_levels {1} and {2}, centroided and profile, at 1 and 4 OpenMP threads;
  • at 4 threads, a level selection combined with a scan range (first_scan 51, last_scan 451), with charge and noise arrays, and with an RT range (the header-only fallback);
  • ms_levels {1, 2}, and {3}, a level that does not occur in the file.

A guard restores the OpenMP thread count even if a check throws.

Mutation check: with the workers' peak read removed (flag still set), ThermoRawFile_test fails.

ctest -R Thermo (ThermoRawFile_test, OnDiscThermoRawExperiment_test, ThermoRawFileMetadata_test) passes locally (Linux, GCC 13, Release, ENABLE_THERMO_RAW_TESTS=ON). The CI presets set ENABLE_THERMO_RAW_TESTS=OFF, so CI compiles these checks but does not run them.

Not in this PR (possible follow-ups from review)

  • One read per selected scan, and prefetch for any header filter (RT, precursor m/z): pass the select.selected(info) result from the scanHeaders() pass to readAhead() as a per-scan mask.
  • The same prefetch for load(). The tests here then need a single-threaded reference instead of load().
  • For MS2-only selections on DDA data, prefetch the parent MS1 scans used for the precursor intensity estimate.

Checklist

  • New and existing unit tests pass locally with my changes

AI use (see the OpenMS AI Policy)

  • I have read the OpenMS AI Policy, and I understand, have reviewed and tested every change in this PR and can explain it in my own words
  • Substantial AI use in PR (e.g. agentic tools wrote significant parts); commits carry a Co-authored-by: trailer, and the description above explains the design intent and rationale

An AI coding agent (Claude) wrote the change, the tests and the measurements. It came out of profiling a DIA workflow in which MS2-only streaming of Thermo files was a bottleneck. The design keeps a per-scan peak flag, and convert() falls back to reading the peaks itself, so the workers' choice cannot change the output.

Summary by CodeRabbit

  • Performance
    • Improved read-ahead for MS-level-filtered processing by loading peak data only for scans at the selected MS levels, while preserving peak loading for all scans when no levels are specified.
  • Bug Fixes
    • Ensured scan headers accurately reflect whether peak data is available.
  • Tests
    • Added checks that MS1 and MS2 selections produce consistent results across single-threaded and multithreaded processing, with centroiding enabled or disabled.

@singjc
singjc marked this pull request as ready for review November 17, 2026 10:49
@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

ThermoRawScanReader can load peaks during read-ahead only for selected MS levels. ThermoRawFile passes those levels for MS-level-only filtering. Tests compare streamed output with load() across MS-level selections, thread counts, centroiding modes, and scan and retention-time ranges.

Changes: MS-Level Peak Read-Ahead

Layer / File(s) Summary
Read-ahead selection contract
src/openms/include/OpenMS/FORMAT/HANDLERS/ThermoRawScanReader.h, src/openms/source/FORMAT/HANDLERS/ThermoRawScanReader.cpp
readAhead accepts optional MS levels and tracks peak availability per scan. ThermoRawScanSelection adds rtFiltered() and uses it in headerFiltered() without changing the retention-time filter conditions.
Selective loading and availability
src/openms/source/FORMAT/HANDLERS/ThermoRawScanReader.cpp
When MS levels are specified, workers read headers first and load peaks and auxiliary arrays only for matching scans at or after peaks_from. header() uses the recorded peak-availability flag, and chunk errors are rethrown by take().
Transform integration and validation
src/openms/source/FORMAT/ThermoRawFile.cpp, src/tests/class_tests/openms/source/ThermoRawFile_test.cpp
For MS-level-only filtering, transform passes the selected levels to readAhead. Tests compare transform() output with load() across MS-level selections, thread counts, centroiding modes, and filter ranges.

Sequence Diagram(s)

sequenceDiagram
  participant ThermoRawFile
  participant ThermoRawScanReader
  participant ReadAheadWorkers
  ThermoRawFile->>ThermoRawScanReader: readAhead with selected MS levels
  ThermoRawScanReader->>ReadAheadWorkers: dispatch scans
  ReadAheadWorkers->>ReadAheadWorkers: read headers and check MS levels
  ReadAheadWorkers->>ReadAheadWorkers: read peaks and auxiliary arrays for selected scans
  ReadAheadWorkers-->>ThermoRawScanReader: return scans, peak flags, or errors
Loading

Suggested reviewers: jpfeuffer, timosachsenberg

Change: Refactor

Merge Risk: Minimal · up to abc2e

This change lets read-ahead workers also read peaks for scans in an MS-level-only selection, and output is meant to be unchanged. No concrete defect was found, and the added tests compare streamed output with load() across levels, thread counts and centroiding modes. Merge risk is minimal.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: read-ahead workers in ThermoRawFile now also read peaks when the selection uses only MS levels. The raw summary confirms this: transform() enables peak prefetch for MS…
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.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title names the main change: read-ahead workers in ThermoRawFile now also read peaks when the selection uses only MS levels. The raw summary confirms this: transform() enables peak prefetch for MS-level-only selections, readAhead accepts a peak_levels filter, and take() returns a per-scan peak-presence flag. The title is specific and matches the changeset and the PR objectives. It is concise and free of file lists, emojis, or vague terms.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks the scans in flight,
And picks the levels for peaks to write.
Headers come first; the flags are clear,
The matching peaks and arrays appear.
Tests hop through threads, then settle right.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5d8a2a6d-d24d-43ed-9fba-c0990ab604d8
Commits

Reviewing files that changed from the base of the PR and between 7bebaff and abc2eb2.

Files selected for processing: 4

  • src/openms/include/OpenMS/FORMAT/HANDLERS/ThermoRawScanReader.h
  • src/openms/source/FORMAT/HANDLERS/ThermoRawScanReader.cpp
  • src/openms/source/FORMAT/ThermoRawFile.cpp
  • src/tests/class_tests/openms/source/ThermoRawFile_test.cpp

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@timosachsenberg timosachsenberg 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.

Independently reviewed the four-file diff at 7bebaff, the transform() selection/call path, ThermoRawScanReader::header() / convert() fallback and the bridge's RawFile::read_scan() / SpectrumSink reuse semantics. The per-scan has_peaks handling is consistent with the selection, including scan-range and chunk boundaries; the bridge resets reused output on the second read.

Own execution: compiled and ran an isolated C++20, multithreaded mock of the changed ReadAhead::run()/take() logic (g++, -std=c++20 -O2 -pthread). PASS: 2,866 ordered scan checks across five scenarios (MS1/MS2 selection, prefetch threshold, unfiltered behavior, multiple chunks and non-1 first scan), plus an injected bridge exception propagated at the expected chunk. This validates the isolated scheduling/selection logic only, not the real OpenMS/Thermo bridge integration. I could not run ThermoRawFile_test here: no OpenMS checkout, vendor RAW test fixture or bridge/runtime installed, and GitHub DNS/network access is unavailable in the execution environment.

No substantiated regression found in the changed path.

@timosachsenberg timosachsenberg 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.

AI-generated initial review

This is an automated, AI-generated first review. It looks only for high- and medium-priority issues (no nits) and checks whether the PR has tests and measurements. Please double-check anything before acting on it; a maintainer will follow up. I reviewed 7bebaff0 against develop (601776c8).

CodeRabbit left only its summary. The earlier independent review tested the scheduling logic in an isolated mock. I built OpenMS with the Thermo bridge and ran the real code.

What I ran:

  • Build: this PR merged into current develop (d3221c79), from source. Release, Linux, GCC 13.3, 4 cores, OPENMS_USE_VCPKG=OFF with system packages (Arrow 24.0.0 and libxml2 2.15.4 built from source). Thermo RAW was on (openms-thermo-bridge v1.0.0, .NET 8 SDK) with ENABLE_THERMO_RAW_TESTS=ON. #10926 and #10927 were in the same tree for their own reviews; they touch other code.
  • Tests: ThermoRawFile_test, OnDiscThermoRawExperiment_test and ThermoRawFileMetadata_test pass, including the extra cases listed under "Tests".
  • Mutation check: I dropped the workers' peak read for the selected levels (ThermoRawScanReader.cpp:683), keeping the has_peaks flag set. ThermoRawFile_test then fails. So the new checks really go through the new path, and not only through the consumer's fallback read.
  • Timing on real data: see "Measurements". Output was identical between develop and the PR, and between 1 and 4 threads.

Verdict:

  • High priority: none.
  • Medium priority: none.

Checked and fine

  • Correctness doesn't depend on the workers' selection: every scan carries its own has_peaks flag from the worker to header(), and convert() reads the peaks itself when the flag is false.
    • If the workers judge a scan differently from ThermoRawScanSelection::selected(), the only cost is a missed prefetch. One example: a scan whose ms_level() is ≤ 0, which header() maps to 0.
    • Scans the workers read with peaks but that aren't selected only cost extra work.
  • level_only: it excludes RT and precursor filters and metadata_only. first_scan and last_scan are covered by peaks_from and the read-ahead's last.
  • load() is unchanged: so the test compares the new transform() path with the old one.
  • Memory: with profile data, the workers now keep decoded peaks in the read-ahead buffer for level-filtered transforms too. On the file below, peak RSS for an MS1-profile transform rose from 510–565 MB to 714–888 MB. That is within what an unfiltered profile transform already uses with the same buffer (733–834 MB on the same file, unchanged code). So the existing bound holds; it's just reached now with a level filter too.

For information (not a defect of this PR)

  • CI doesn't run these tests:
    • The new checks are in ThermoRawFile_test inside #ifdef THERMO_RAW_TEST_DATA, and the CI presets set ENABLE_THERMO_RAW_TESTS=OFF (CMakePresets.json:110).
    • So the green build-and-test jobs compile this part of the test but don't run it. Your local run and mine are the only runs so far.
    • Turning the test data on in one Linux job would cover this file and the other Thermo tests in CI. It's a 9.7 MB download from archive.openms.de.
  • Possible follow-up (one read instead of two, and RT/precursor filters too):
    • transform() already visits every header in scanHeaders() (to count the selected scans) before it calls readAhead().
    • Recording select.selected(info) there, e.g. as a std::vector<char> over the scan range, and handing that to readAhead() would let the workers read each selected scan in one call, without the header-only read first.
    • It would also work for any header-based filter, not only MS levels.

Tests

  • You added: transform() equals load() for MS1 and MS2 selections, with 1 and 4 OpenMP threads, centroided and profile.

  • Added locally, all pass; you may want to take them over. At 4 threads, inside your loop over {ms2, ms1}, I added:

    • a level selection with a scan range (first_scan 51, last_scan 451): peaks_from is then above the first scan, and the read-ahead ends before the last scan;
    • a level selection with charge_data and noise_data.

    After the loop I added ms_levels {1, 2}, and {3}, a level that doesn't occur in the file.

    Code for ThermoRawFile_test.cpp: inserted after l. 656 (testTransform(profile);); the first } is the existing end of your loop
          // level selection combined with a scan range (peaks_from = first_scan > first scan of the file,
          // read-ahead ends before the last scan) and with the charge and noise arrays
          ThermoRawFile::Options range = levels;
          range.first_scan = 51;
          range.last_scan = 451;
          testTransform(range);
          ThermoRawFile::Options arrays = levels;
          arrays.charge_data = true;
          arrays.noise_data = true;
          testTransform(arrays);
        }
        // several levels at once, and a level that does not occur
        {
          ThermoRawFile::Options both = ms1;
          both.ms_levels = {1, 2};
          testTransform(both);
          ThermoRawFile::Options absent = ms1;
          absent.ms_levels = {3};
          testTransform(absent);
        }

Measurements

  • You provided: a downstream workflow on a 3.1 GB Astral file (MS2 only, 8 threads): 8:06 → 7:18 wall time, byte-identical outputs. That's real data, good.

  • Added here: ThermoRawFile::transform() into a consumer that only counts. That isolates the reader from the rest of a workflow.

    • File: PXD000001 TMT_Erwinia_1uLSike_Top10HCD_isol2_45stepped_60min_01.raw (LTQ Orbitrap Velos, 210 MB, 7,534 scans: 1,431 MS1 and 6,103 MS2).
    • Method: same build with develop's and the PR's Thermo sources swapped, 3 interleaved runs each, file in the page cache. The table shows the median, with the range in brackets. Times include opening the file and the header pass.
    selection threads develop PR change
    MS2, centroided 4 1.15 s (1.10–1.20) 0.85 s (0.84–1.07) −26 %
    MS1, centroided 4 0.89 s (0.89–0.95) 0.75 s (0.70–0.88) −16 %
    MS1, profile 4 2.57 s (2.51–2.74) 1.82 s (1.71–2.14) −29 %
    all levels, centroided (path unchanged) 4 0.87 s (0.83–0.95) 0.86 s (0.86–0.86) –
    MS2, centroided (no read-ahead) 1 1.23 s (1.23–1.34) 1.20 s (1.16–1.31) –
    • Same output: spectrum and peak counts, and a checksum over all m/z and intensity values, are identical between develop and the PR, and between 1 and 4 threads.
    • Consistent with your number: this confirms the gain on a second instrument type and also for MS1-only and profile selections.

Description

  • The PR has no AI-use section. The repository's PR template asks for one (and for the AI-policy confirmation), so please add it, even if the answer is "None".

Generated by Claude Code

@timosachsenberg timosachsenberg 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.

AI-generated review: lower-priority findings

This is an automated, AI-generated second pass, at a lower threshold than the earlier review on this PR: it lists optional improvements and nits as well. Nothing here changes the spectra and nothing blocks the merge. It is a static read of 7bebaff0 and of openms-thermo-bridge v1.0.0; nothing was built or run for it. Please double-check before acting on it.

Some points extend what the earlier review already noted (missed prefetch for an MS order of 0 or below, load() unchanged, one read instead of two, more test cases); the inline comments say where.

One point is not on a changed line:

  • MS2-only selections still decode the parent MS1 scans on the consumer thread. The precursor intensity estimate goes through parentSpectrum() -> raw->spectrum_data() (ThermoRawScanReader.cpp:755), because level 1 is not read ahead and unselected scans never enter the ParentCache of transform(). This is not introduced by the PR, but it limits the gain for ms_levels = {2} on DDA data. A possible follow-up: the workers also read the peaks of parent-level scans and hand them to the parent lookup.

Generated by Claude Code

Comment on lines +680 to +683
accessor.read_scan(scan, out, header_options);
if (wantsPeaks(scan, out.header.ms_level()))
{
accessor.read_scan(scan, out, full_options);

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.

Selected scans are read twice, both times with the trailer text (efficiency)

header_options and full_options both carry trailer_text = true, which the bridge documents as slow. On this path every selected scan therefore costs scan stats, scan event, filter string and GetTrailerExtraInformation twice. Before the PR the second read was the peakReadOptions() read of convert(), which has no trailer text, so the vendor work per selected scan goes up while it moves to the workers.

A small fix: read the peaks with peakReadOptions() into a per-worker scratch tb::Spectrum and swap its arrays into out. convertScan() only uses the arrays of data, and the consumer then gets exactly what convert() read before the PR. The selection bitmap from scanHeaders() that the earlier review suggested gets it down to one read, but only for transform().

Asking accessor.ms_level(scan) before the read is not an option: RawFile::ms_level() returns the raw MS order, and check_int_result() takes -1/-2/-3 for error codes, so it throws for precursor-ion, neutral-loss and neutral-gain scans.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in abc2eb2. The worker reads the peaks of a selected scan with peakReadOptions() (no trailer text, the same read convert() did before) into a scratch tb::Spectrum and swaps the six arrays in. The header read keeps the trailer text, which header() needs. On the 3.1 GB Astral file (MS2, 4 threads) this took the median from 19.0 s to 16.7 s (develop 25.4 s); the table is in the description. The one-read version via a mask from scanHeaders() is listed as a follow-up.

}
// Level-selected peaks: the header decides; the peaks of a selected scan are read in a second call.
accessor.read_scan(scan, out, header_options);
if (wantsPeaks(scan, out.header.ms_level()))

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.

wantsPeaks() gets the raw MS order, the selection uses the clamped level (low)

header.ms_level() is -1/-2/-3 for precursor-ion, neutral-loss and neutral-gain scans, and header() maps every value of 0 or below to ScanInfo::ms_level == 0. With ms_levels = {0} on a triple-quad file those scans are selected, but the workers never read their peaks. As the earlier review says, this only costs a missed prefetch and the output is correct. A negative entry in ms_levels has the opposite effect: peaks are decoded and never used.

Suggested change
if (wantsPeaks(scan, out.header.ms_level()))
if (wantsPeaks(scan, std::max(out.header.ms_level(), 0)))

Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: the worker now uses std::max(spectrum.header.ms_level(), 0), the same clamp as header().

bool complete = last == reader.lastScan(); // all headers read, so the TIC can be built from them
const bool prefetch_peaks = ! header_filtered && ! options_.metadata_only;
reader.readAhead(last, prefetch_peaks ? options_.first_scan : std::numeric_limits<int>::max());
// Selected by MS level only: the read-ahead workers also read the peaks of scans at those levels.

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.

load() keeps the old behaviour (scope)

Only transform() gets the level prefetch. load() (lines 89-91), and with it FileHandler::loadExperiment() with an MS-level filter, still passes INT_MAX for any header filter, so its calling thread decodes every selected scan as before.

If that is intended for now, fine. Otherwise the decision could live in one helper on ThermoRawScanSelection that both loops use. The new test relies on load() taking the old path (it compares transform() with load()), so it would then need a single-threaded reference instead.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Intended for this PR: load() keeps the consumer-thread read, and the tests use it as the reference for transform(). I listed the shared helper for load() (with a single-threaded reference in the tests) as a follow-up in the description.

Comment on lines +228 to +230
const bool level_only = header_filtered && ! options_.ms_levels.empty() && ! select.precursorFiltered()
&& options_.rt_min == -std::numeric_limits<double>::infinity()
&& options_.rt_max == std::numeric_limits<double>::infinity() && ! options_.metadata_only;

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.

A level filter with an RT range falls back to the old path (scope)

level_only is false as soon as rt_min or rt_max is set, although the worker has the retention time in the same header as the MS level. ms_levels = {2} with an RT window is a common setup and gets no prefetch.

Passing the selection instead of a level list, and checking select.level() and select.rt() in the worker, would cover it. The bitmap follow-up from the earlier review would cover precursor m/z filters too.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed this is the common case. I kept it out of this PR so the change stays small; the fallback is now covered by a test (level selection with an RT range at 4 threads). The per-scan selection mask from scanHeaders(), which covers RT and precursor filters and gives one read per scan, is listed as a follow-up.

// which must give the single-threaded result (where the consumer thread reads every scan itself)
{
const int threads = omp_get_max_threads();
for (const ThermoRawFile::Options& levels : {ms2, ms1})

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.

Test coverage

  • Not exercised: a level filter together with first_scan/last_scan (the scan < peaks_from branch with a non-empty level list), charge_data/noise_data through the two-step read, a list of several levels, and a level filter with an RT range (the fallback). The earlier review has code for the first three.
  • Profile mode runs with 4 threads only.
  • The mutation check in the earlier review shows that these checks go through the peaks the workers read. The opposite regression is not caught: if level_only were never true, or wantsPeaks() always false, every check still passes, because the fallback gives the same spectra. I see no way to test that through the public API; noting it only.

Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added in abc2eb2: level selection with first_scan 51 / last_scan 451, with charge_data and noise_data, with an RT range (fallback), ms_levels {1, 2} and {3}; profile now runs at 1 and 4 threads. I repeated your mutation check: without the worker peak read (flag still set) ThermoRawFile_test fails. Agreed that the opposite regression (prefetch never used) is not visible through the public API; the timing in the description covers it for now.

Comment on lines +231 to +232
if (level_only) { reader.readAhead(last, options_.first_scan, options_.ms_levels); }
else { reader.readAhead(last, prefetch_peaks ? options_.first_scan : std::numeric_limits<int>::max()); }

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.

The two readAhead() calls are one call (simplification)

readAhead(last, first_scan, {}) is the unfiltered call, and ms_levels is empty whenever prefetch_peaks is true, so one call does the same:

Suggested change
if (level_only) { reader.readAhead(last, options_.first_scan, options_.ms_levels); }
else { reader.readAhead(last, prefetch_peaks ? options_.first_scan : std::numeric_limits<int>::max()); }
reader.readAhead(last, (prefetch_peaks || level_only) ? options_.first_scan : std::numeric_limits<int>::max(), options_.ms_levels);

Two smaller things in level_only above: header_filtered && is implied by ! options_.ms_levels.empty(), and the RT part repeats headerFiltered() with a different comparison (== instead of > / <). An rtFiltered() helper on ThermoRawScanSelection, used by headerFiltered() as well, would keep the two from drifting apart.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: one readAhead() call, level_only no longer repeats header_filtered, and a new ThermoRawScanSelection::rtFiltered() is used by both headerFiltered() and transform().

Comment on lines +673 to +678
if (peak_levels.empty() || scan < peaks_from)
{
with_peaks[scan - begin] = scan >= peaks_from;
accessor.read_scan(scan, out, with_peaks[scan - begin] ? full_options : header_options);
continue;
}

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.

Two read paths for one decision (nit)

The loop sets with_peaks in two places and has three read_scan() call sites, and wantsPeaks() tests scan >= peaks_from and peak_levels.empty() again, which the calling branch has already decided.

One flow reads easier: bool peaks = scan >= peaks_from;, then, for a non-empty level list, read the header and set peaks from the level, and store the flag in one place.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: one flow. with_peaks starts as scan >= peaks_from, a level list may turn it off after the header read, and the flag is stored in one place. wantsPeaks() is gone.

profile.centroid = false;
testTransform(profile);
}
omp_set_num_threads(threads);

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.

Thread count is not restored if a check throws; the comment promises more than the code does (nit)

  • If transform() or load() throws, START_SECTION catches it and the rest of the test runs with 4 (or 1) threads. A small RAII guard avoids that. The existing read-ahead section has the same pattern.
  • Each testTransform() compares transform() with load() at the same thread count. The 4-thread result is never compared with a single-threaded reference, as the comment says. That works as long as load() takes the old path (see the comment on load()).

Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: a small RAII guard restores the OpenMP thread count, and the comment now says that each transform() is compared with load(), which keeps the consumer-thread read.

Comment on lines +170 to +171
@param[in] peak_levels If not empty, only scans of these MS levels (from @p peaks_from on) are read with peaks;
the header is read first to learn the level. header() reports which scans carry peaks.

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.

header() does not report this (doc)

header() returns a ScanInfo without such a field. The flag is internal and only convert() uses it.

Suggested change
@param[in] peak_levels If not empty, only scans of these MS levels (from @p peaks_from on) are read with peaks;
the header is read first to learn the level. header() reports which scans carry peaks.
@param[in] peak_levels If not empty, only scans of these MS levels (from @p peaks_from on) are read with peaks;
the header is read first to learn the level. convert() reads the peaks of the other scans itself.

Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Applied, thanks.

std::mutex mutex;
std::condition_variable produced, consumed;
std::map<int, std::pair<std::vector<tb::Spectrum>, std::exception_ptr>> ready; ///< chunk -> scans
std::map<int, std::tuple<std::vector<tb::Spectrum>, std::vector<char>, std::exception_ptr>> ready; ///< chunk -> scans, peaks read

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.

<tuple> is not included (nit)

std::tuple, std::make_tuple and std::get<N> now only come in through <map>, <mutex> and <functional>. #include <tuple> is enough. A small struct with named members (scans, peaks, error) would also read better than std::get<0..2>.


Generated by Claude Code

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Replaced the tuple with a named Chunk struct (scans, has_peaks, error), so <tuple> is no longer needed.

singjc and others added 2 commits November 17, 2026 16:31
…-level-only selection

Before, any header filter (also ms_levels alone) turned peak prefetch off in
ThermoRawScanReader::readAhead, so the consumer thread of transform() decoded
every selected scan itself. readAhead() now takes the levels whose peaks the
workers read after the header, and take() reports per scan whether peaks came
along. Spectra are unchanged.

Test: ThermoRawFile_test checks transform() == load() for ms_levels {1} and {2}
with 1 and 4 OpenMP threads, centroided and profile.

Co-authored-by: Claude <[email protected]>
- Workers read the peaks of a level-selected scan without the trailer text (peakReadOptions, as convert()
  reads them) into a scratch spectrum and swap the arrays in; previously the second read repeated the slow
  trailer text.
- The worker clamps the MS order like header() (levels <= 0 map to 0), so ms_levels {0} prefetches too.
- One readAhead() call in transform(); rtFiltered() helper shared with headerFiltered(); named Chunk struct
  instead of a tuple; readAhead() doc says convert() reads the other peaks.
- Tests: level selection with a scan range, with charge/noise arrays, with an RT range (fallback), levels
  {1,2} and an absent level {3}; profile at 1 and 4 threads; OpenMP thread count restored by a guard.
  Mutation check: dropping the worker peak read makes ThermoRawFile_test fail.

Co-authored-by: Claude <[email protected]>
@singjc
singjc force-pushed the feature/thermo-raw-level-readahead branch from 7bebaff to abc2eb2 Compare November 17, 2026 16:33
@singjc

singjc commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough reviews and the measurements. I pushed abc2eb2 (branch rebased onto current develop; the first commit only gains its Co-authored-by trailer):

  • The worker's peak read no longer repeats the trailer text. Level clamp as in header(). One readAhead() call, rtFiltered() helper, a named Chunk struct, and the doc fix.
  • Your suggested tests (scan range, charge/noise, {1, 2}, absent level), plus a level selection with an RT range (fallback) and profile at 1 and 4 threads. RAII thread guard. The mutation check fails as expected.
  • The AI-use section and new timings are in the description. On a 3.1 GB Astral DIA file (MS2, 4 threads) the median goes from 25.4 s (develop) to 16.7 s, with identical checksums.

Kept out as follow-ups (listed in the description): the selection mask from scanHeaders() (one read, RT and precursor filters), the same prefetch for load(), and parent-MS1 prefetch for DDA. Happy to do the mask in this PR instead if you prefer.

Copy link
Copy Markdown
Contributor

Patch for the follow-up: prefetch in load() and with an RT range

This is an AI-generated patch that has not been run against a RAW file. It is input for the follow-up you listed, not a request for this PR: keeping load() and the RT range out of this PR is fine.

The patch applies on top of abc2eb24:

  • Selection instead of a level list: readAhead() takes the ThermoRawScanSelection. After the header read the worker checks select.level() and select.rt(), so a selection with an RT range (alone or with MS levels) gets its peaks read ahead too. A precursor m/z range and metadata_only still read headers only.
  • load() as well: load() and transform() both call a new ThermoRawScanSelection::peaksReadAheadFrom().
  • Test: load() then no longer keeps the consumer-thread read, so load() and transform() at 4 threads are compared with the single-threaded load(). An RT range alone is added.

How it relates to the mask you plan: the mask from scanHeaders() gives one vendor read per scan and also covers precursor filters, but only transform() has that header pass. load() has none, so there the check has to happen in the worker, as in this patch, with two reads per selected scan. The follow-up may want both.

What was checked: a compiler syntax check of the four changed sources (g++ 13, C++20, OpenMP), and the read-ahead code run against a fake vendor accessor in 16 selection scenarios with 1 and 3 workers, also under ThreadSanitizer. Nothing was built, and ThermoRawFile_test has not been executed with these changes. Please run it before taking anything over.

Patch on top of abc2eb24 (4 files, +48 / -33)
diff --git a/src/openms/include/OpenMS/FORMAT/HANDLERS/ThermoRawScanReader.h b/src/openms/include/OpenMS/FORMAT/HANDLERS/ThermoRawScanReader.h
index 97559d8c..d92a13b3 100644
--- a/src/openms/include/OpenMS/FORMAT/HANDLERS/ThermoRawScanReader.h
+++ b/src/openms/include/OpenMS/FORMAT/HANDLERS/ThermoRawScanReader.h
@@ -28,6 +28,8 @@ namespace OpenMS
 
 namespace Internal
 {
+  struct ThermoRawScanSelection;
+
   /**
     @brief Scan-by-scan conversion of a Thermo RAW file into OpenMS spectra (private).
 
@@ -167,10 +169,11 @@ namespace Internal
 
       @param[in] last_scan Last scan to read ahead
       @param[in] peaks_from Scans from this number on are read with peaks (as header(scan, true))
-      @param[in] peak_levels If not empty, only scans of these MS levels (from @p peaks_from on) are read with peaks;
-                 the header is read first to learn the level. convert() reads the peaks of the other scans itself.
+      @param[in] select If it selects scans by MS level or retention time, only the scans (from @p peaks_from on) that
+                 these two select are read with peaks; the header is read first to learn them. convert() reads the
+                 peaks of the other scans itself. The options of @p select are copied.
     */
-    void readAhead(int last_scan, int peaks_from, std::vector<int> peak_levels = {});
+    void readAhead(int last_scan, int peaks_from, const ThermoRawScanSelection* select = nullptr);
 
     /**
       @brief Visit the headers of scans @p first to @p last ahead of header(), without peaks.
@@ -254,6 +257,12 @@ namespace Internal
     {
       return ! options.ms_levels.empty() || precursorFiltered() || rtFiltered();
     }
+    /// First scan whose peaks ThermoRawScanReader::readAhead() may read with this selection. None (the largest int) if
+    /// no peaks are converted, or with a precursor m/z range, which the header of a single scan does not tell.
+    int peaksReadAheadFrom() const
+    {
+      return options.metadata_only || precursorFiltered() ? std::numeric_limits<int>::max() : options.first_scan;
+    }
     /// Last scan to read: scans of one controller are in acquisition order, so no later scan can be selected.
     int lastScan(int last) const { return options.last_scan > 0 ? std::min(last, options.last_scan) : last; }
     /// True if no scan from @p info on can be selected (checked after reading its header).
diff --git a/src/openms/source/FORMAT/HANDLERS/ThermoRawScanReader.cpp b/src/openms/source/FORMAT/HANDLERS/ThermoRawScanReader.cpp
index 797a3f24..bab9010e 100644
--- a/src/openms/source/FORMAT/HANDLERS/ThermoRawScanReader.cpp
+++ b/src/openms/source/FORMAT/HANDLERS/ThermoRawScanReader.cpp
@@ -632,7 +632,7 @@ struct ThermoRawScanReader::Impl
   {
     static constexpr int chunk = 128;
     int first = 0, last = 0, peaks_from = 0;
-    std::vector<int> peak_levels; ///< If not empty, peaks are only read ahead for scans of these MS levels.
+    std::optional<Options> select; ///< If set, peaks are only read ahead for scans whose MS level and RT these select.
     tb::ReadOptions header_options, full_options;
     tb::ReadOptions peak_options; ///< Peaks of a scan whose header was already read (no trailers, as convert() reads them).
     std::vector<std::thread> workers;
@@ -674,13 +674,13 @@ struct ThermoRawScanReader::Impl
           {
             tb::Spectrum& spectrum = out.scans[scan - begin];
             bool with_peaks = scan >= peaks_from;
-            if (with_peaks && ! peak_levels.empty())
+            if (with_peaks && select)
             {
-              // The header decides; the peaks of a selected scan follow in a second read without trailers. The level
-              // is clamped as in header(), which maps every MS order of 0 or below to level 0.
+              // The header decides; the peaks of a selected scan follow in a second read without trailers. Level and
+              // RT are taken as in header(), which maps every MS order of 0 or below to level 0.
               accessor.read_scan(scan, spectrum, header_options);
-              const int level = std::max(spectrum.header.ms_level(), 0);
-              with_peaks = std::find(peak_levels.begin(), peak_levels.end(), level) != peak_levels.end();
+              const ThermoRawScanSelection selection{*select};
+              with_peaks = selection.level(std::max(spectrum.header.ms_level(), 0)) && selection.rt(spectrum.header.retention_time * 60.0);
               if (with_peaks)
               {
                 accessor.read_scan(scan, peaks, peak_options);
@@ -894,7 +894,7 @@ void ThermoRawScanReader::fillSettings(ExperimentalSettings& settings) const
   settings.setInstrument(d.instrument);
 }
 
-void ThermoRawScanReader::readAhead(int last_scan, int peaks_from, std::vector<int> peak_levels)
+void ThermoRawScanReader::readAhead(int last_scan, int peaks_from, const ThermoRawScanSelection* select)
 {
   Impl& d = *impl_;
   if (d.read_ahead) { d.read_ahead->shutdown(); d.read_ahead.reset(); }
@@ -911,7 +911,7 @@ void ThermoRawScanReader::readAhead(int last_scan, int peaks_from, std::vector<i
   ahead->first = first;
   ahead->last = last_scan;
   ahead->peaks_from = peaks_from;
-  ahead->peak_levels = std::move(peak_levels);
+  if (select != nullptr && (! select->options.ms_levels.empty() || select->rtFiltered())) { ahead->select = select->options; }
   ahead->window = 4 * workers;
   ahead->full_options = d.peakReadOptions();
   ahead->full_options.trailer_text = true;
diff --git a/src/openms/source/FORMAT/ThermoRawFile.cpp b/src/openms/source/FORMAT/ThermoRawFile.cpp
index 0b8685f3..d8edb6fa 100644
--- a/src/openms/source/FORMAT/ThermoRawFile.cpp
+++ b/src/openms/source/FORMAT/ThermoRawFile.cpp
@@ -87,8 +87,7 @@ void ThermoRawFile::load(const std::string& path, MSExperiment& exp)
       MSChromatogram tic;
       bool complete = true; // all headers read, so the TIC can be built from them
       const bool prefetch_peaks = ! header_filtered && ! options_.metadata_only;
-      reader.readAhead(select.lastScan(last),
-                       prefetch_peaks ? options_.first_scan : std::numeric_limits<int>::max());
+      reader.readAhead(select.lastScan(last), select.peaksReadAheadFrom(), &select);
       startProgress(first, last, "Loading Thermo RAW file");
       for (int scan = first; scan <= last; ++scan)
       {
@@ -224,10 +223,9 @@ void ThermoRawFile::transform(const std::string& path, Interfaces::IMSDataConsum
       MSChromatogram tic;
       bool complete = last == reader.lastScan(); // all headers read, so the TIC can be built from them
       const bool prefetch_peaks = ! header_filtered && ! options_.metadata_only;
-      // Selected by MS level only: the read-ahead workers also read the peaks of scans at those levels (an empty level
-      // list, the unfiltered case, reads all peaks). Other header filters keep the header-only read-ahead.
-      const bool level_only = ! options_.ms_levels.empty() && ! select.precursorFiltered() && ! select.rtFiltered() && ! options_.metadata_only;
-      reader.readAhead(last, (prefetch_peaks || level_only) ? options_.first_scan : std::numeric_limits<int>::max(), options_.ms_levels);
+      // The read-ahead workers also read the peaks of the scans that the MS levels and the RT range select (all scans
+      // without these two filters). A precursor m/z range keeps the header-only read-ahead.
+      reader.readAhead(last, select.peaksReadAheadFrom(), &select);
       startProgress(first, last, "Streaming Thermo RAW file");
       for (int scan = first; scan <= last; ++scan)
       {
diff --git a/src/tests/class_tests/openms/source/ThermoRawFile_test.cpp b/src/tests/class_tests/openms/source/ThermoRawFile_test.cpp
index e0a0a7fa..2f0712f7 100644
--- a/src/tests/class_tests/openms/source/ThermoRawFile_test.cpp
+++ b/src/tests/class_tests/openms/source/ThermoRawFile_test.cpp
@@ -641,48 +641,56 @@ START_SECTION(void transform(const std::string& path, Interfaces::IMSDataConsume
   ms1.ms_levels = {1};
   testTransform(ms1);
 #ifdef _OPENMP
-  // MS-level-only selection: the read-ahead workers also read the peaks of the selected levels. load() keeps the
-  // consumer-thread read for any header filter, so each transform() below is compared with that path.
+  // Selection by MS level and/or RT: the read-ahead workers of load() and transform() also read the peaks of the
+  // selected scans. Both are compared with the single-threaded load(), where no scan is read ahead.
   {
     struct ThreadGuard // restores the OpenMP thread count also when a check throws
     {
       int threads = omp_get_max_threads();
       ~ThreadGuard() { omp_set_num_threads(threads); }
     } guard;
+    auto testReadAhead = [&](const ThermoRawFile::Options& options) {
+      omp_set_num_threads(1);
+      const MSExperiment single = load(options);
+      testTransform(options);
+      omp_set_num_threads(4);
+      TEST_TRUE(load(options) == single)
+      testTransform(options);
+    };
+    const MSExperiment all = load(base);
     for (const ThermoRawFile::Options& levels : {ms2, ms1})
     {
-      omp_set_num_threads(1);
-      testTransform(levels);
+      testReadAhead(levels);
       ThermoRawFile::Options profile = levels;
       profile.centroid = false;
-      testTransform(profile);
-      omp_set_num_threads(4);
-      testTransform(levels);
-      testTransform(profile);
+      testReadAhead(profile);
       // level selection combined with a scan range (peaks_from = first_scan > first scan of the file,
       // read-ahead ends before the last scan) and with the charge and noise arrays
       ThermoRawFile::Options range = levels;
       range.first_scan = 51;
       range.last_scan = 451;
-      testTransform(range);
+      testReadAhead(range);
       ThermoRawFile::Options arrays = levels;
       arrays.charge_data = true;
       arrays.noise_data = true;
-      testTransform(arrays);
-      // with an RT range the header-only read-ahead is kept
+      testReadAhead(arrays);
+      // with an RT range
       ThermoRawFile::Options rt_range = levels;
-      const MSExperiment all = load(base);
       rt_range.rt_min = all[100].getRT();
       rt_range.rt_max = all[200].getRT();
-      testTransform(rt_range);
+      testReadAhead(rt_range);
     }
-    // several levels at once, and a level that does not occur
+    // several levels at once, a level that does not occur, and an RT range alone
     ThermoRawFile::Options both = ms1;
     both.ms_levels = {1, 2};
-    testTransform(both);
+    testReadAhead(both);
     ThermoRawFile::Options absent = ms1;
     absent.ms_levels = {3};
-    testTransform(absent);
+    testReadAhead(absent);
+    ThermoRawFile::Options rt_only = base;
+    rt_only.rt_min = all[100].getRT();
+    rt_only.rt_max = all[200].getRT();
+    testReadAhead(rt_only);
   }
 #endif
   const MSExperiment full = load(base);

Generated by Claude Code

@timosachsenberg timosachsenberg 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.

Approving abc2eb24. This approval is AI-generated and posted at the maintainer's request, on the condition that CI passes.

  • First commit: the rebased e8e64d74 has the same patch as 7bebaff0, which was reviewed before.
  • Second commit: I read its diff in full. It resolves the review comments: the peak read without trailer text, the level clamp as in header(), one readAhead() call with rtFiltered(), the named Chunk struct, the doc sentence, the thread-count guard and the added test cases. I found no new issue in it.
  • CI: all build-and-test, wheel and header-set jobs pass on abc2eb24.
  • Thermo tests: CI does not run them (ENABLE_THERMO_RAW_TESTS=OFF), so ThermoRawFile_test rests on your local run and the mutation check you report. Nothing was built or run for this approval.
  • Follow-ups: prefetch in load(), the selection mask (RT and precursor filters) and parent-MS1 prefetch stay out of this PR, as listed in the description. A patch for the first two is in the comment above.

Generated by Claude Code

@timosachsenberg
timosachsenberg merged commit 6610795 into OpenMS:develop Nov 17, 2026
31 checks passed
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