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
3 changes: 3 additions & 0 deletions Framework/AODNative/include/AODNative/ByteSource.h
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,9 @@ class ByteSource
virtual std::string url() const = 0;
/// The label of the replica being read, for a source opened with openReplicas().
virtual std::string replicaLabel() const { return {}; }
/// Seconds spent so far on replicas which failed to open, retry delays and
/// reopens, for a source opened with openReplicas().
virtual double failoverSeconds() const { return 0; }
static std::unique_ptr<ByteSource> open(std::string url, const Options&);
/// Opens the first replica which opens, and on a read error retries it
/// (Options::readRetries times, reopened) and then moves on to the next
Expand Down
11 changes: 11 additions & 0 deletions Framework/AODNative/include/AODNative/Container.h
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,27 @@ class RootFile
KeyInfo parseKey(std::span<const uint8_t> buf, uint64_t fileOffset);
DirectoryInfo readDirectory(uint64_t offset);
std::vector<KeyInfo> readKeyList(DirectoryInfo const&);
/// The bytes at @a offset: from the head, the metadata read ahead, or the source.
std::vector<uint8_t> readMetadata(uint64_t offset, size_t len);
/// Reads the directory records and key lists of DF @a df and of the next
/// ones not listed yet, in two vector reads, into mAhead.
void listAhead(std::string const& df);
std::optional<KeyInfo> findTopKey(std::string const& name);
std::vector<uint8_t> readStored(const KeyInfo&);

std::shared_ptr<ByteSource> mSource;
std::string mUrl;
FileHeader mHeader;
// The first bytes of the file, read with the header: they also hold the
// directory records of the file and, usually, of its first DF.
std::vector<uint8_t> mHead;
std::optional<std::vector<KeyInfo>> mTopKeys;
// Stored bytes of the TTrees of the last DF listed, by key offset, until read.
std::map<uint64_t, std::vector<uint8_t>> mPrefetched;
std::map<std::string, std::vector<KeyInfo>> mKeysOf;
// Directory records and key lists of the next DFs, by offset (small and capped).
std::map<uint64_t, std::vector<uint8_t>> mAhead;
std::vector<std::string> mOrder; // dataFrames(), for the read-ahead
std::vector<std::string> mTreesToPrefetch;
std::map<std::string, std::map<std::string, std::string>> mStringMaps;
};
Expand Down
87 changes: 82 additions & 5 deletions Framework/AODNative/src/Container.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ namespace
// Big enough for the file header and for a TDirectory record (including its UUID).
constexpr size_t kHeaderReadSize = 128;
constexpr size_t kDirectoryReadSize = 64;
// Read at open: the header, the top directory record and, as ROOT writes them
// first, the key and directory record of the first DF, in one round trip.
constexpr size_t kHeadReadSize = 4096;
// Directory records and key lists of the next DFs read along with those of a
// DF: at most this many DFs and this many bytes of key lists.
constexpr size_t kListAheadDFs = 16;
constexpr uint64_t kListAheadBytes = 1024 * 1024;
// Largest gap between the TTrees of a DF still read together with them.
constexpr uint64_t kMetadataGap = 4 * 1024;
// Smallest possible key header: 32-bit seeks and three empty strings.
Expand All @@ -49,8 +56,8 @@ RootFile::RootFile(std::shared_ptr<ByteSource> source)
: mSource(std::move(source)),
mUrl(mSource->url())
{
auto buf = readRange(*mSource, 0, std::min<uint64_t>(kHeaderReadSize, mSource->size()));
Cursor c{buf, mUrl};
mHead = readRange(*mSource, 0, std::min<uint64_t>(kHeadReadSize, mSource->size()));
Cursor c{mHead, mUrl};
auto magic = c.bytes(4);
if (std::memcmp(magic.data(), "root", 4) != 0) {
throw FormatError(mUrl + " is not a ROOT file");
Expand Down Expand Up @@ -100,7 +107,7 @@ DirectoryInfo RootFile::readDirectory(uint64_t offset)
if (offset >= mSource->size()) {
throw CorruptData(mUrl, offset, "directory record past the end of the file");
}
auto buf = readRange(*mSource, offset, std::min<uint64_t>(kDirectoryReadSize, mSource->size() - offset));
auto buf = readMetadata(offset, std::min<uint64_t>(kDirectoryReadSize, mSource->size() - offset));
Cursor c{buf, mUrl, offset};
DirectoryInfo d;
d.version = c.i16();
Expand All @@ -120,7 +127,7 @@ std::vector<KeyInfo> RootFile::readKeyList(DirectoryInfo const& dir)
if (dir.seekKeys == 0 || dir.nbytesKeys <= 0) {
return {};
}
auto buf = readRange(*mSource, dir.seekKeys, dir.nbytesKeys);
auto buf = readMetadata(dir.seekKeys, dir.nbytesKeys);
auto header = parseKey(buf, dir.seekKeys);
Cursor c{buf, mUrl, dir.seekKeys};
c.seek(header.keylen);
Expand All @@ -140,6 +147,67 @@ std::vector<KeyInfo> RootFile::readKeyList(DirectoryInfo const& dir)
return keys;
}

std::vector<uint8_t> RootFile::readMetadata(uint64_t offset, size_t len)
{
if (offset + len <= mHead.size()) {
return {mHead.begin() + offset, mHead.begin() + offset + len};
}
if (auto it = mAhead.find(offset); it != mAhead.end() && it->second.size() == len) {
return it->second;
}
return readRange(*mSource, offset, len);
}

void RootFile::listAhead(std::string const& df)
{
mAhead.clear();
auto fetch = [this](std::vector<std::pair<uint64_t, size_t>> const& ranges) {
std::vector<ReadRequest> requests;
for (auto [offset, len] : ranges) {
auto& bytes = mAhead[offset];
bytes.resize(len);
requests.push_back({offset, len, bytes.data()});
}
if (!requests.empty()) {
mSource->readvInto(requests);
}
};
// The directory records of this DF and of the next ones, in read order.
std::vector<uint64_t> records;
std::vector<std::pair<uint64_t, size_t>> ranges;
if (mOrder.empty()) {
mOrder = dataFrames();
}
for (auto it = std::ranges::find(mOrder, df); it != mOrder.end() && records.size() < kListAheadDFs; ++it) {
auto key = findTopKey(*it);
auto offset = key ? key->seekKey + key->keylen : 0;
if (!key || (*it != df && mKeysOf.contains(*it)) || (key->className != "TDirectoryFile" && key->className != "TDirectory") || key->compressed() || offset + kDirectoryReadSize > mSource->size()) {
continue;
}
records.push_back(offset);
if (offset + kDirectoryReadSize > mHead.size()) {
ranges.emplace_back(offset, kDirectoryReadSize);
}
}
fetch(ranges);
// Then their key lists. Anything odd is left to the normal path, which reports it.
ranges.clear();
uint64_t bytes = 0;
for (auto offset : records) {
try {
auto dir = readDirectory(offset);
if (dir.seekKeys == 0 || dir.nbytesKeys <= 0 || dir.seekKeys > mSource->size() || (uint64_t)dir.nbytesKeys > mSource->size() - dir.seekKeys ||
(!ranges.empty() && bytes + dir.nbytesKeys > kListAheadBytes)) {
continue;
}
bytes += dir.nbytesKeys;
ranges.emplace_back(dir.seekKeys, dir.nbytesKeys);
} catch (FormatError const&) {
}
}
fetch(ranges);
}

const std::vector<KeyInfo>& RootFile::topKeys()
{
if (!mTopKeys) {
Expand Down Expand Up @@ -231,7 +299,16 @@ std::vector<KeyInfo> RootFile::keysOf(const std::string& df)
if (key->compressed()) {
throw UnsupportedLayout("compressed directory record for " + df + " in " + mUrl);
}
auto dir = readDirectory(key->seekKey + key->keylen);
// The records of the next DFs are read ahead with those of this one; the
// first DF's directory record comes with the head, its key list does not.
auto offset = key->seekKey + key->keylen;
if (!mSource->canMap() && offset + kDirectoryReadSize > mHead.size() && !mAhead.contains(offset)) {
listAhead(df);
}
auto dir = readDirectory(offset);
if (!mSource->canMap() && !mAhead.contains(dir.seekKeys)) {
listAhead(df);
}
auto keys = highestCycles(readKeyList(dir));

// The TTrees of a DF are written next to each other: ranges less than
Expand Down
17 changes: 17 additions & 0 deletions Framework/AODNative/src/FailoverByteSource.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ namespace o2::aod::native

namespace
{
/// Adds the time until it goes out of scope to @a total, unless cancelled.
struct FailoverTimer {
std::atomic<uint64_t>& total;
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
bool counting = true;
void cancel() { counting = false; }
~FailoverTimer()
{
if (counting) {
total.fetch_add(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - start).count(), std::memory_order_relaxed);
}
}
};

std::string labelOf(Replica const& r)
{
return r.label.empty() ? r.url.substr(0, r.url.find('?')) : r.label;
Expand All @@ -33,10 +47,12 @@ FailoverByteSource::FailoverByteSource(std::vector<Replica> replicas, Options co
throw IoError("(no replica)", "no replica to open");
}
for (mIndex = 0; mIndex < mReplicas.size(); ++mIndex) {
FailoverTimer timer{mFailoverNs};
try {
mSource = openReplica(mIndex);
mSize = mSource->size();
mRemote = mSource->isRemote();
timer.cancel();
return;
} catch (IoError const& e) {
report("Could not open replica on " + labelOf(mReplicas[mIndex]) + ": " + e.what());
Expand Down Expand Up @@ -109,6 +125,7 @@ void FailoverByteSource::withFailover(std::function<void(ByteSource&)> const& re
return;
} catch (IoError const& e) {
std::lock_guard lock{mMutex};
FailoverTimer timer{mFailoverNs};
if (generation != mGeneration) {
continue; // another read already replaced the replica: try the new one
}
Expand Down
2 changes: 2 additions & 0 deletions Framework/AODNative/src/FailoverByteSource.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class FailoverByteSource : public ByteSource
uint64_t readCalls() const override;
std::string url() const override { return current()->url(); }
std::string replicaLabel() const override;
double failoverSeconds() const override { return mFailoverNs.load(std::memory_order_relaxed) / 1e9; }

private:
std::shared_ptr<ByteSource> current() const;
Expand All @@ -71,6 +72,7 @@ class FailoverByteSource : public ByteSource
bool mRemote = false;
std::atomic<uint64_t> mRetiredBytes = 0;
std::atomic<uint64_t> mRetiredCalls = 0;
std::atomic<uint64_t> mFailoverNs = 0;
};

} // namespace o2::aod::native
Expand Down
4 changes: 3 additions & 1 deletion Framework/AnalysisSupport/src/AODInputFile.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ std::shared_ptr<AODInputFile> openNativeAOD(std::string const& filename, RootObj
}
auto start = std::chrono::steady_clock::now();
auto replicas = gridReplicas(filename);
auto accessed = std::chrono::steady_clock::now();
if (replicas.empty()) {
throw o2::aod::native::IoError(filename, "no replica the native reader can read");
}
Expand All @@ -161,9 +162,10 @@ std::shared_ptr<AODInputFile> openNativeAOD(std::string const& filename, RootObj
auto source = o2::aod::native::ByteSource::openReplicas(std::move(list), options, [filename](std::string const& message) {
LOGP(info, "\"{}\": {}", filename, message);
});
auto replicaOpen = std::chrono::duration<double>(std::chrono::steady_clock::now() - accessed).count() - source->failoverSeconds();
auto se = source->replicaLabel();
auto file = NativeAODInputFile::open(std::move(source), factory, options, filename);
file->setGridInfo(se, std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count());
file->setGridInfo(se, std::chrono::duration<double>(accessed - start).count(), replicaOpen);
return file;
}

Expand Down
32 changes: 23 additions & 9 deletions Framework/AnalysisSupport/src/NativeAOD.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include "AODNative/Errors.h"
#include "Framework/RuntimeError.h"
#include <algorithm>
#include <chrono>
#include <cstdio>

namespace o2::framework
Expand Down Expand Up @@ -97,9 +98,6 @@ std::shared_ptr<ReadPlan> NativeAODFileSystem::planFor(std::string const& path)
if (std::ranges::find(trees, treeName) == trees.end()) {
trees.push_back(treeName);
}
if (!previous.empty()) {
mFile->setTreesToPrefetch(trees);
}
for (auto& name : previous) {
addToPlan(name);
}
Expand Down Expand Up @@ -255,6 +253,8 @@ void NativeAODFileSystem::addToPlan(std::string const& treeName)
mPlanBytes += bytes;
mPlanOf[treeName] = mPlan;
mPlanTrees.push_back(treeName);
// The next DF's keys can be listed before its plan is made (by getTreeHandle).
mFile->setTreesToPrefetch(mPlanTrees);
}
}

Expand Down Expand Up @@ -334,11 +334,19 @@ std::shared_ptr<NativeAODInputFile> NativeAODInputFile::open(std::unique_ptr<Byt
{
auto result = std::shared_ptr<NativeAODInputFile>(new NativeAODInputFile);
result->mName = name;
auto start = std::chrono::steady_clock::now();
double failover = source->failoverSeconds();
result->mFile = std::make_shared<RootFile>(std::move(source));
// What TFile::Init reads (header and keys) counts as opening, as for ROOT;
// the rest is the preparation of the first DF.
result->mFile->topKeys();
auto opened = std::chrono::steady_clock::now();
auto& file = result->mFile->source();
result->mOpenTime = std::chrono::duration<double>(opened - start).count() - (file.failoverSeconds() - failover);
failover = file.failoverSeconds();
result->mFilesystem = std::make_shared<NativeAODFileSystem>(result->mFile, options, factory);
result->mFilesystem->setName(result->mName);
result->mParentFiles = result->mFile->readStringMap("parentFiles");
result->mMetaData = result->mFile->readStringMap("metaData");
// Parse the trees of the first DF now: a layout or version we do not support
// is then found while the file can still be read with ROOT instead.
auto dfs = result->mFile->dataFrames();
Expand All @@ -349,23 +357,29 @@ std::shared_ptr<NativeAODInputFile> NativeAODInputFile::open(std::unique_ptr<Byt
}
}
}
result->mPrepareTime = std::chrono::duration<double>(std::chrono::steady_clock::now() - opened).count() - (file.failoverSeconds() - failover);
return result;
}

void NativeAODInputFile::setGridInfo(std::string se, double openTime)
void NativeAODInputFile::setGridInfo(std::string se, double accessTime, double replicaOpenTime)
{
mSE = std::move(se);
mOpenTime = openTime;
mAccessTime = accessTime;
mOpenTime += replicaOpenTime;
}

std::string NativeAODInputFile::monitoringDetails() const
{
if (mSE.empty()) {
return "";
}
char openTime[32];
std::snprintf(openTime, sizeof(openTime), "%.1f", mOpenTime);
return ",se=" + mSE + ",open_time=" + openTime;
// open_time covers what TJAlienFile::GetElapsed() does for ROOT: opening the
// replica which is read and TFile::Init. The other times come before it, so
// that open_time stays last in the open line, as for ROOT.
char times[256];
std::snprintf(times, sizeof(times), ",access_time=%.3f,failover_time=%.3f,prepare_time=%.3f,se=%s,open_time=%.1f",
mAccessTime, mFile->source().failoverSeconds(), mPrepareTime, mSE.c_str(), mOpenTime);
return times;
}

uint64_t NativeAODInputFile::size() const { return mFile->source().size(); }
Expand Down
15 changes: 9 additions & 6 deletions Framework/AnalysisSupport/src/NativeAOD.h
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,16 @@ class NativeAODFileSystem : public VirtualRootFileSystemBase
class NativeAODInputFile : public AODInputFile
{
public:
/// Opens @a url and parses its header, keys, maps and the trees of its first
/// Opens @a url and parses its header, keys, parent files and the trees of its first
/// DF, so that layouts and versions we cannot read are found here, when the
/// file can still go to ROOT. Throws o2::aod::native::FormatError.
/// @a name is what the file is called (an LFN for a grid file); @a url by default.
static std::shared_ptr<NativeAODInputFile> open(std::string const& url, RootObjectReadingFactory& factory, o2::aod::native::Options const& options, std::string const& name = {});
/// The same, reading from @a source (e.g. the replicas of a grid file).
static std::shared_ptr<NativeAODInputFile> open(std::unique_ptr<o2::aod::native::ByteSource> source, RootObjectReadingFactory& factory, o2::aod::native::Options const& options, std::string const& name);
/// The storage element and the seconds the grid lookup and open took, for monitoring.
void setGridInfo(std::string se, double openTime);
/// For monitoring: the storage element, the seconds the catalogue lookup took,
/// and those the opening of the replica read took (failed replicas excluded).
void setGridInfo(std::string se, double accessTime, double replicaOpenTime);
std::string monitoringDetails() const override;

std::string name() const override { return mName; }
Expand All @@ -144,19 +145,21 @@ class NativeAODInputFile : public AODInputFile
std::vector<Key> topLevelKeys() override;
std::vector<std::string> keysIn(std::string const& dir) override;
std::map<std::string, std::string> parentFiles() override { return mParentFiles; }
std::map<std::string, std::string> metaData() override { return mMetaData; }
/// Read when asked for: the reader does not need it, and it costs a round trip at open.
std::map<std::string, std::string> metaData() override { return mFile->readStringMap("metaData"); }
std::shared_ptr<VirtualRootFileSystemBase> filesystem() override { return mFilesystem; }
void setReadOrder(std::vector<std::string> const& dfs) override { mFilesystem->setReadOrder(dfs); }

private:
NativeAODInputFile() = default;
std::string mName;
std::string mSE;
double mOpenTime = 0;
double mAccessTime = 0;
double mOpenTime = 0; // replica open and the reads of TFile::Init, as TJAlienFile
double mPrepareTime = 0; // parentFiles and the first DF's directory, keys and trees
std::shared_ptr<o2::aod::native::RootFile> mFile;
std::shared_ptr<NativeAODFileSystem> mFilesystem;
std::map<std::string, std::string> mParentFiles;
std::map<std::string, std::string> mMetaData;
};

} // namespace o2::framework
Expand Down