Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
17 changes: 12 additions & 5 deletions inc/ramcore/RecordBlocks.h
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,15 @@ class FlaggedBlockReader {
/// \p records values. Runs on other threads.
using DecodeFn = void (*)(std::vector<char> &bytes, std::size_t records, std::vector<int> &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<char> &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
Expand Down Expand Up @@ -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<uint32_t> m_flagsView;
std::optional<ROOT::RNTupleView<std::vector<std::uint8_t>>> m_view;
std::vector<uint64_t> m_ends; ///< Last row of each block.
std::vector<uint64_t> m_ends; ///< Last row of each block.
std::vector<std::size_t> 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.
Expand Down Expand Up @@ -195,7 +201,8 @@ class NameBlockReader {
void Load(std::size_t block);

ROOT::RNTupleView<std::vector<std::uint8_t>> m_view;
std::vector<uint64_t> m_ends; ///< Last row of each block.
std::vector<uint64_t> m_ends; ///< Last row of each block.
std::vector<std::size_t> 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;
Expand Down
6 changes: 5 additions & 1 deletion inc/rntuple/RAMFile.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,13 @@ class RAMFile {
/// has another format version. \p options are for the reader of the records.
static std::unique_ptr<RAMFile> Open(const std::string &path, const ROOT::RNTupleReadOptions &options = {});

RAMFile(std::unique_ptr<ROOT::RNTupleReader> reader, RAMFileMetadata meta);
RAMFile(std::unique_ptr<ROOT::RNTupleReader> 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); }
Expand All @@ -47,6 +50,7 @@ class RAMFile {

std::unique_ptr<ROOT::RNTupleReader> m_reader;
RAMFileMetadata m_meta;
bool m_clusterCache;
RAMTagReader m_tags;
std::unordered_map<std::string, int32_t> m_rnameIds;
};
Expand Down
53 changes: 48 additions & 5 deletions src/ramcore/RecordBlocks.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include "rntuple/RAMNTupleRecord.h"

#include <ROOT/REntry.hxx>
#include <ROOT/RNTupleDescriptor.hxx>
#include <ROOT/RNTupleReader.hxx>
#include <ROOT/RNTupleTypes.hxx>
#include <htscodecs/fqzcomp_qual.h>
Expand Down Expand Up @@ -188,6 +189,12 @@ void DecodeQualityBlock(std::vector<char> &bytes, std::size_t records, std::vect
c = static_cast<char>(c + '!');
}

// A quality block of fqzcomp, which decodes 25 times slower than rANS.
bool IsFqzcompBlock(const std::vector<char> &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<char> &bytes, std::size_t records, std::vector<int> &lengths, std::string &seqs)
{
Expand Down Expand Up @@ -221,6 +228,22 @@ void CheckBlockEnds(const std::vector<uint64_t> &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<std::size_t> BlockClusters(const ROOT::RNTupleDescriptor &desc, const std::vector<uint64_t> &ends)
{
std::vector<uint64_t> firsts;
for (const auto &cluster : desc.GetClusterIterable())
firsts.push_back(cluster.GetFirstEntryIndex());
std::sort(firsts.begin(), firsts.end());
std::vector<std::size_t> clusters;
clusters.reserve(ends.size());
for (const uint64_t end : ends)
clusters.push_back(
static_cast<std::size_t>(std::upper_bound(firsts.begin(), firsts.end(), end) - firsts.begin()));
return clusters;
}

} // namespace

void BlockWriter::FreeDeflate::operator()(libdeflate_compressor *c) const
Expand Down Expand Up @@ -360,11 +383,12 @@ std::vector<uint64_t> 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<uint32_t>("record.compression_flags")),
m_ends(file.GetMetadata().block_ends),
Expand All @@ -374,6 +398,8 @@ FlaggedBlockReader::FlaggedBlockReader(RAMFile &file, const char *field, uint32_
if (reader.GetDescriptor().FindFieldId(field) != ROOT::kInvalidDescriptorId)
m_view.emplace(reader.GetView<std::vector<std::uint8_t>>(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)
Expand Down Expand Up @@ -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)
Expand All @@ -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)
{
}

Expand All @@ -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)
{
}

Expand All @@ -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)
Expand Down Expand Up @@ -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)));
}
Expand Down
7 changes: 4 additions & 3 deletions src/rntuple/RAMFile.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,12 @@ std::unique_ptr<RAMFile> RAMFile::Open(const std::string &path, const ROOT::RNTu
RAMFileMetadata meta;
if (!ReadMetadata(path, meta))
return nullptr;
return std::make_unique<RAMFile>(std::move(reader), std::move(meta));
return std::make_unique<RAMFile>(std::move(reader), std::move(meta),
options.GetClusterCache() != ROOT::RNTupleReadOptions::EClusterCache::kOff);
}

RAMFile::RAMFile(std::unique_ptr<ROOT::RNTupleReader> reader, RAMFileMetadata meta)
: m_reader(std::move(reader)), m_meta(std::move(meta)), m_tags(m_meta)
RAMFile::RAMFile(std::unique_ptr<ROOT::RNTupleReader> 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<int32_t>(i));
Expand Down
72 changes: 68 additions & 4 deletions test/record_blocks_test.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

#include <ROOT/REntry.hxx>
#include <ROOT/RNTupleDescriptor.hxx>
#include <ROOT/RNTupleMetrics.hxx>
#include <ROOT/RNTupleReadOptions.hxx>
#include <ROOT/RNTupleTypes.hxx>
#include <ROOT/RNTupleWriteOptions.hxx>
#include <ROOT/RNTupleWriter.hxx>
#include <TFile.h>

Expand Down Expand Up @@ -41,22 +44,34 @@ const uint8_t kDeflateCodec = 1;
using Damage = std::function<void(std::vector<std::uint8_t> &)>;

// 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<Read> &reads, std::size_t block, uint32_t policy, const std::vector<uint64_t> &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<TFile> 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<std::vector<std::uint8_t>>(field);
if (damage && !blob.empty())
damage(blob);
writer->Fill(e);
if (clusterRows > 0 && ++rows % clusterRows == 0)
writer->CommitCluster();
},
block);
for (const auto &read : reads) {
Expand Down Expand Up @@ -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<Read> reads;
reads.reserve(kReads);
for (std::size_t i = 0; i < kReads; i++)
reads.push_back({0, std::string(kLength, static_cast<char>('!' + (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<RAMNTupleRecord>("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<std::int64_t>(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)
Expand Down
Loading