diff --git a/CHANGELOG.md b/CHANGELOG.md index 9984a38..ba6c588 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,18 @@ the README for what that means before 1.0. a 10 Mb region 0.15 s instead of 0.56 s, for more peak memory: 640 MB instead of 580 MB, and 67 MB instead of 60 MB ([#131]). +### Changed + +- A full read reads each cluster of the file once. The readers of names, + qualities and bases read ahead only within the cluster the records are in: + ROOT keeps the cluster it is asked for and the next one, so a block read ahead + from the next cluster dropped the records' cluster, and they read it again. + NA12878's HiSeq chromosome 20 now reads 2.2 GB instead of 6.6 GB of its 2.2 GB + file, in 19.3 to 19.9 s instead of 23.8 to 24.4 s; chromosome 20 reads 0.42 GB + instead of 2.04 GB, in 14.5 to 15.2 s instead of 15.1 to 16.0 s. Blocks of + fqzcomp, slow to decode, still read ahead from the next cluster; regions, + which are read without the cluster cache, and `-@ N` are as before ([#132]). + ## [0.2.0] - 2026-11-07 The format of this release stores the typed SAM tags in columns of their own, the @@ -384,3 +396,4 @@ it stay readable by every later release. [#127]: https://github.com/compiler-research/ramtools/pull/127 [#128]: https://github.com/compiler-research/ramtools/pull/128 [#131]: https://github.com/compiler-research/ramtools/pull/131 +[#132]: https://github.com/compiler-research/ramtools/pull/132 diff --git a/inc/ramcore/RecordBlocks.h b/inc/ramcore/RecordBlocks.h index 8a68e74..c0333b1 100644 --- a/inc/ramcore/RecordBlocks.h +++ b/inc/ramcore/RecordBlocks.h @@ -104,11 +104,15 @@ class FlaggedBlockReader { /// \p records values. Runs on other threads. using DecodeFn = void (*)(std::vector &bytes, std::size_t records, std::vector &lengths, std::string &values); + /// Whether the block with these bytes decodes so slowly that the blocks + /// after it are worth reading ahead from the next cluster too. + using SlowFn = bool (*)(const std::vector &bytes); /// With \p everyRow, a block holds a value for every row, empty for those - /// without the bit, so finding a row's value needs no flags. - FlaggedBlockReader(RAMFile &file, const char *field, uint32_t bit, DecodeFn decode, std::size_t readAhead, - bool everyRow); + /// without the bit, so finding a row's value needs no flags. \p slow may be + /// null: no block is slow. + FlaggedBlockReader(RAMFile &file, const char *field, uint32_t bit, DecodeFn decode, SlowFn slow, + std::size_t readAhead, bool everyRow); /// The value of \p row, whose record has the bit. Valid until the next call. /// A view into the decoded block, not a copy: copying every quality out cost @@ -138,10 +142,12 @@ class FlaggedBlockReader { std::string m_field; uint32_t m_bit; DecodeFn m_decode; + SlowFn m_slow; bool m_everyRow; ROOT::RNTupleView m_flagsView; std::optional>> m_view; - std::vector m_ends; ///< Last row of each block. + std::vector m_ends; ///< Last row of each block. + std::vector m_clusters; ///< Per block, with the cluster cache: its cluster, by number. std::size_t m_readAhead; std::size_t m_block = kNoBlock; std::size_t m_run = 0; ///< Consecutive blocks read so far. @@ -195,7 +201,8 @@ class NameBlockReader { void Load(std::size_t block); ROOT::RNTupleView> m_view; - std::vector m_ends; ///< Last row of each block. + std::vector m_ends; ///< Last row of each block. + std::vector m_clusters; ///< Per block, with the cluster cache: its cluster, by number. std::size_t m_block = kNoBlock; std::size_t m_run = 0; ///< Consecutive blocks read so far. uint64_t m_firstRow = 0; diff --git a/inc/rntuple/RAMFile.h b/inc/rntuple/RAMFile.h index 7675c0c..d674b68 100644 --- a/inc/rntuple/RAMFile.h +++ b/inc/rntuple/RAMFile.h @@ -21,10 +21,13 @@ class RAMFile { /// has another format version. \p options are for the reader of the records. static std::unique_ptr Open(const std::string &path, const ROOT::RNTupleReadOptions &options = {}); - RAMFile(std::unique_ptr reader, RAMFileMetadata meta); + RAMFile(std::unique_ptr reader, RAMFileMetadata meta, bool clusterCache = true); ROOT::RNTupleReader &GetReader() { return *m_reader; } [[nodiscard]] const RAMFileMetadata &GetMetadata() const { return m_meta; } + /// Whether the reader of the records loads whole clusters, with ROOT's + /// cluster cache, as it does unless the options of Open() turn it off. + [[nodiscard]] bool UsesClusterCache() const { return m_clusterCache; } /// The name of reference \p refid; "*" for -1 or an id the file does not have. [[nodiscard]] const std::string &GetRname(int32_t refid) const { return Name(m_meta.rname_refs, refid); } @@ -47,6 +50,7 @@ class RAMFile { std::unique_ptr m_reader; RAMFileMetadata m_meta; + bool m_clusterCache; RAMTagReader m_tags; std::unordered_map m_rnameIds; }; diff --git a/src/ramcore/RecordBlocks.cxx b/src/ramcore/RecordBlocks.cxx index 44ec331..18a5915 100644 --- a/src/ramcore/RecordBlocks.cxx +++ b/src/ramcore/RecordBlocks.cxx @@ -3,6 +3,7 @@ #include "rntuple/RAMNTupleRecord.h" #include +#include #include #include #include @@ -188,6 +189,12 @@ void DecodeQualityBlock(std::vector &bytes, std::size_t records, std::vect c = static_cast(c + '!'); } +// A quality block of fqzcomp, which decodes 25 times slower than rANS. +bool IsFqzcompBlock(const std::vector &bytes) +{ + return !bytes.empty() && bytes.front() == kQualFqzcomp; +} + // Fills \p lengths and \p seqs from a block that holds \p records sequences. void DecodeSeqBlock(std::vector &bytes, std::size_t records, std::vector &lengths, std::string &seqs) { @@ -221,6 +228,22 @@ void CheckBlockEnds(const std::vector &ends, ROOT::NTupleSize_t rows) } } +// For each block, a number for the cluster that holds its last row, and so its +// bytes: equal numbers, the same cluster. +std::vector BlockClusters(const ROOT::RNTupleDescriptor &desc, const std::vector &ends) +{ + std::vector firsts; + for (const auto &cluster : desc.GetClusterIterable()) + firsts.push_back(cluster.GetFirstEntryIndex()); + std::sort(firsts.begin(), firsts.end()); + std::vector clusters; + clusters.reserve(ends.size()); + for (const uint64_t end : ends) + clusters.push_back( + static_cast(std::upper_bound(firsts.begin(), firsts.end(), end) - firsts.begin())); + return clusters; +} + } // namespace void BlockWriter::FreeDeflate::operator()(libdeflate_compressor *c) const @@ -360,11 +383,12 @@ std::vector BlockWriter::TakeBlockEnds() return std::exchange(m_blockEnds, {}); } -FlaggedBlockReader::FlaggedBlockReader(RAMFile &file, const char *field, uint32_t bit, DecodeFn decode, +FlaggedBlockReader::FlaggedBlockReader(RAMFile &file, const char *field, uint32_t bit, DecodeFn decode, SlowFn slow, std::size_t readAhead, bool everyRow) : m_field(field), m_bit(bit), m_decode(decode), + m_slow(slow), m_everyRow(everyRow), m_flagsView(file.GetReader().GetView("record.compression_flags")), m_ends(file.GetMetadata().block_ends), @@ -374,6 +398,8 @@ FlaggedBlockReader::FlaggedBlockReader(RAMFile &file, const char *field, uint32_ if (reader.GetDescriptor().FindFieldId(field) != ROOT::kInvalidDescriptorId) m_view.emplace(reader.GetView>(field)); CheckBlockEnds(m_ends, reader.GetNEntries()); + if (file.UsesClusterCache()) + m_clusters = BlockClusters(reader.GetDescriptor(), m_ends); } std::string_view FlaggedBlockReader::FromBlock(ROOT::NTupleSize_t row) @@ -464,8 +490,19 @@ void FlaggedBlockReader::Load(std::size_t block) m_block = block; m_firstRow = block == 0 ? 0 : m_ends[block - 1] + 1; + // With ROOT's cluster cache, only blocks of this block's cluster: the cache + // keeps the cluster it is asked for and the next one, so a block read ahead + // from the next cluster dropped the one the records were still in, and they + // read it again. A full read of NA12878's HiSeq chromosome 20 read 6.6 GB of + // its 2.2 GB file. Without the cache pages are read one by one, and waiting + // for the first block of each cluster only made a region slower. So did it + // for fqzcomp, whose blocks take about 60 ms each: 5.5 to 5.9 s instead of + // 4.4 to 4.5 s for 2 million records, so a slow block still reads ahead. + const bool anyCluster = m_clusters.empty() || (m_slow != nullptr && m_slow(m_current.bytes)); const std::size_t depth = std::min(m_run, m_readAhead); - for (std::size_t next = block + 1; next < m_ends.size() && next <= block + depth; next++) { + for (std::size_t next = block + 1; + next < m_ends.size() && next <= block + depth && (anyCluster || m_clusters[next] == m_clusters[block]); + next++) { // A thread for each block. Threads kept for the reader's life took more // CPU: 28.4 s instead of 25.7 s for a full read of chr20. if (m_ahead.count(next) == 0) @@ -475,7 +512,7 @@ void FlaggedBlockReader::Load(std::size_t block) QualityBlockReader::QualityBlockReader(RAMFile &file) : FlaggedBlockReader(file, RAMNTupleRecord::kQualBlockField, RAMNTupleRecord::kQualInBlock, DecodeQualityBlock, - kQualityReadAhead, /*everyRow=*/false) + IsFqzcompBlock, kQualityReadAhead, /*everyRow=*/false) { } @@ -490,7 +527,7 @@ std::string_view QualityBlockReader::Get(const RAMNTupleRecord &rec, ROOT::NTupl SeqBlockReader::SeqBlockReader(RAMFile &file) : FlaggedBlockReader(file, RAMNTupleRecord::kSeqBlockField, RAMNTupleRecord::kSeqInBlock, DecodeSeqBlock, - kSeqReadAhead, /*everyRow=*/true) + /*slow=*/nullptr, kSeqReadAhead, /*everyRow=*/true) { } @@ -506,6 +543,8 @@ NameBlockReader::NameBlockReader(RAMFile &file) m_ends(file.GetMetadata().block_ends) { CheckBlockEnds(m_ends, file.GetReader().GetNEntries()); + if (file.UsesClusterCache()) + m_clusters = BlockClusters(file.GetReader().GetDescriptor(), m_ends); } std::string_view NameBlockReader::Get(ROOT::NTupleSize_t row) @@ -566,8 +605,12 @@ void NameBlockReader::Load(std::size_t block) m_block = block; m_firstRow = block == 0 ? 0 : m_ends[block - 1] + 1; + // With ROOT's cluster cache, only blocks of this block's cluster, as + // FlaggedBlockReader::Load() says. const std::size_t depth = std::min(m_run, kNameReadAhead); - for (std::size_t next = block + 1; next < m_ends.size() && next <= block + depth; next++) { + for (std::size_t next = block + 1; + next < m_ends.size() && next <= block + depth && (m_clusters.empty() || m_clusters[next] == m_clusters[block]); + next++) { if (m_ahead.count(next) == 0) m_ahead.emplace(next, std::async(std::launch::async, Decode, Read(next), next, rows(next))); } diff --git a/src/rntuple/RAMFile.cxx b/src/rntuple/RAMFile.cxx index 019e23c..3db6b15 100644 --- a/src/rntuple/RAMFile.cxx +++ b/src/rntuple/RAMFile.cxx @@ -86,11 +86,12 @@ std::unique_ptr RAMFile::Open(const std::string &path, const ROOT::RNTu RAMFileMetadata meta; if (!ReadMetadata(path, meta)) return nullptr; - return std::make_unique(std::move(reader), std::move(meta)); + return std::make_unique(std::move(reader), std::move(meta), + options.GetClusterCache() != ROOT::RNTupleReadOptions::EClusterCache::kOff); } -RAMFile::RAMFile(std::unique_ptr reader, RAMFileMetadata meta) - : m_reader(std::move(reader)), m_meta(std::move(meta)), m_tags(m_meta) +RAMFile::RAMFile(std::unique_ptr reader, RAMFileMetadata meta, bool clusterCache) + : m_reader(std::move(reader)), m_meta(std::move(meta)), m_clusterCache(clusterCache), m_tags(m_meta) { for (std::size_t i = 0; i < m_meta.rname_refs.size(); i++) m_rnameIds.emplace(m_meta.rname_refs[i], static_cast(i)); diff --git a/test/record_blocks_test.cxx b/test/record_blocks_test.cxx index 1d02205..20952f3 100644 --- a/test/record_blocks_test.cxx +++ b/test/record_blocks_test.cxx @@ -4,7 +4,10 @@ #include #include +#include +#include #include +#include #include #include @@ -41,22 +44,34 @@ const uint8_t kDeflateCodec = 1; using Damage = std::function &)>; // Writes the reads; \p ends, when given, replaces the block ends, and \p damage -// changes every block of \p field, as in a damaged file. +// changes every block of \p field, as in a damaged file. With \p clusterRows, a +// cluster ends every so many rows, and pages hold 64 bytes at most, so that a +// column has several pages in a cluster. void Write(const std::vector &reads, std::size_t block, uint32_t policy, const std::vector &ends = {}, - const Damage &damage = nullptr, const char *field = RAMNTupleRecord::kQualBlockField) + const Damage &damage = nullptr, const char *field = RAMNTupleRecord::kQualBlockField, + std::size_t clusterRows = 0) { std::unique_ptr file(TFile::Open(kFile, "RECREATE")); RAMFileMetadata meta; meta.rname_refs = {"chr1"}; { - auto writer = ROOT::RNTupleWriter::Append(RAMNTupleRecord::MakeModel(), "RAM", *file); + ROOT::RNTupleWriteOptions options; + if (clusterRows > 0) { + constexpr std::size_t kPageBytes = 64; + options.SetInitialUnzippedPageSize(kPageBytes); + options.SetMaxUnzippedPageSize(kPageBytes); + } + auto writer = ROOT::RNTupleWriter::Append(RAMNTupleRecord::MakeModel(), "RAM", *file, options); + std::size_t rows = 0; BlockWriter out( writer->GetModel().CreateEntry(), writer->GetModel().CreateEntry(), - [&writer, &damage, field](ROOT::REntry &e) { + [&writer, &damage, field, clusterRows, &rows](ROOT::REntry &e) { auto &blob = *e.GetPtr>(field); if (damage && !blob.empty()) damage(blob); writer->Fill(e); + if (clusterRows > 0 && ++rows % clusterRows == 0) + writer->CommitCluster(); }, block); for (const auto &read : reads) { @@ -352,6 +367,55 @@ TEST_F(RecordBlocksTest, ADamagedBlockReadAheadIsReported) EXPECT_THROW(seqs.Get(view(5), 5), std::runtime_error); } +// Reading every record in order, as ramdump does, reads each cluster once: the +// blocks read ahead stay in the cluster the records are in. A block read ahead +// from the next cluster made ROOT drop the records' cluster and read it again. +TEST_F(RecordBlocksTest, AFullReadReadsEachClusterOnce) +{ + constexpr std::size_t kReads = 96; + constexpr std::size_t kBlock = 4; + constexpr std::size_t kClusterRows = 16; + constexpr std::size_t kLength = 30; + const std::string bases = "ACGT"; + std::vector reads; + reads.reserve(kReads); + for (std::size_t i = 0; i < kReads; i++) + reads.push_back({0, std::string(kLength, static_cast('!' + (i % 40))), "read" + std::to_string(i), + std::string(kLength, bases.at(i % bases.size()))}); + Write(reads, kBlock, kRansPolicy, /*ends=*/{}, /*damage=*/nullptr, RAMNTupleRecord::kQualBlockField, kClusterRows); + + ROOT::RNTupleReadOptions options; + options.SetEnableMetrics(true); + auto file = RAMFile::Open(kFile, options); + ASSERT_NE(file, nullptr); + ROOT::RNTupleReader &reader = file->GetReader(); + const auto &desc = reader.GetDescriptor(); + ASSERT_EQ(desc.GetNClusters(), kReads / kClusterRows); + std::uint64_t stored = 0; + for (const auto &cluster : desc.GetClusterIterable()) { + for (const auto &column : desc.GetColumnIterable()) { + if (!cluster.ContainsColumn(column.GetPhysicalId())) + continue; + for (const auto &page : cluster.GetPageRange(column.GetPhysicalId()).GetPageInfos()) + stored += page.GetLocator().GetNBytesOnStorage(); + } + } + + auto view = reader.GetView("record"); + NameBlockReader names(*file); + SeqBlockReader seqs(*file); + QualityBlockReader quals(*file); + for (std::size_t row = 0; row < kReads; row++) { + const RAMNTupleRecord &rec = view(row); + EXPECT_EQ(names.Get(row), reads[row].name) << "row " << row; + EXPECT_EQ(seqs.Get(rec, row), reads[row].seq) << "row " << row; + EXPECT_EQ(quals.Get(rec, row), reads[row].qual) << "row " << row; + } + const auto *payload = reader.GetMetrics().GetCounter("RNTupleReader.RPageSourceFile.szReadPayload"); + ASSERT_NE(payload, nullptr); + EXPECT_LE(payload->GetValueAsInt(), static_cast(stored)); +} + // Names go into blocks whatever the quality policy, and come back in any order: // a repeated name, "*", an empty one, the longest SAM allows. TEST_F(RecordBlocksTest, EveryNameComesBackInAnyOrder)