diff --git a/Framework/AODNative/include/AODNative/ByteSource.h b/Framework/AODNative/include/AODNative/ByteSource.h index 9ba49c284faa2..46c6cd98ab60b 100644 --- a/Framework/AODNative/include/AODNative/ByteSource.h +++ b/Framework/AODNative/include/AODNative/ByteSource.h @@ -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 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 diff --git a/Framework/AODNative/include/AODNative/Container.h b/Framework/AODNative/include/AODNative/Container.h index 567927542a8fc..b14b5d0793384 100644 --- a/Framework/AODNative/include/AODNative/Container.h +++ b/Framework/AODNative/include/AODNative/Container.h @@ -81,16 +81,27 @@ class RootFile KeyInfo parseKey(std::span buf, uint64_t fileOffset); DirectoryInfo readDirectory(uint64_t offset); std::vector readKeyList(DirectoryInfo const&); + /// The bytes at @a offset: from the head, the metadata read ahead, or the source. + std::vector 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 findTopKey(std::string const& name); std::vector readStored(const KeyInfo&); std::shared_ptr 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 mHead; std::optional> mTopKeys; // Stored bytes of the TTrees of the last DF listed, by key offset, until read. std::map> mPrefetched; std::map> mKeysOf; + // Directory records and key lists of the next DFs, by offset (small and capped). + std::map> mAhead; + std::vector mOrder; // dataFrames(), for the read-ahead std::vector mTreesToPrefetch; std::map> mStringMaps; }; diff --git a/Framework/AODNative/src/Container.cxx b/Framework/AODNative/src/Container.cxx index 5136c8557afcb..7578fecf0e0e0 100644 --- a/Framework/AODNative/src/Container.cxx +++ b/Framework/AODNative/src/Container.cxx @@ -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. @@ -49,8 +56,8 @@ RootFile::RootFile(std::shared_ptr source) : mSource(std::move(source)), mUrl(mSource->url()) { - auto buf = readRange(*mSource, 0, std::min(kHeaderReadSize, mSource->size())); - Cursor c{buf, mUrl}; + mHead = readRange(*mSource, 0, std::min(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"); @@ -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(kDirectoryReadSize, mSource->size() - offset)); + auto buf = readMetadata(offset, std::min(kDirectoryReadSize, mSource->size() - offset)); Cursor c{buf, mUrl, offset}; DirectoryInfo d; d.version = c.i16(); @@ -120,7 +127,7 @@ std::vector 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); @@ -140,6 +147,67 @@ std::vector RootFile::readKeyList(DirectoryInfo const& dir) return keys; } +std::vector 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> const& ranges) { + std::vector 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 records; + std::vector> 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& RootFile::topKeys() { if (!mTopKeys) { @@ -231,7 +299,16 @@ std::vector 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 diff --git a/Framework/AODNative/src/FailoverByteSource.cxx b/Framework/AODNative/src/FailoverByteSource.cxx index c44c1640fe80d..f421d15f01848 100644 --- a/Framework/AODNative/src/FailoverByteSource.cxx +++ b/Framework/AODNative/src/FailoverByteSource.cxx @@ -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& 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::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; @@ -33,10 +47,12 @@ FailoverByteSource::FailoverByteSource(std::vector 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()); @@ -109,6 +125,7 @@ void FailoverByteSource::withFailover(std::function 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 } diff --git a/Framework/AODNative/src/FailoverByteSource.h b/Framework/AODNative/src/FailoverByteSource.h index 15e0aee055f75..a4564c86a95e5 100644 --- a/Framework/AODNative/src/FailoverByteSource.h +++ b/Framework/AODNative/src/FailoverByteSource.h @@ -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 current() const; @@ -71,6 +72,7 @@ class FailoverByteSource : public ByteSource bool mRemote = false; std::atomic mRetiredBytes = 0; std::atomic mRetiredCalls = 0; + std::atomic mFailoverNs = 0; }; } // namespace o2::aod::native diff --git a/Framework/AnalysisSupport/src/AODInputFile.cxx b/Framework/AnalysisSupport/src/AODInputFile.cxx index d73df2924587a..0e369e8d6824a 100644 --- a/Framework/AnalysisSupport/src/AODInputFile.cxx +++ b/Framework/AnalysisSupport/src/AODInputFile.cxx @@ -149,6 +149,7 @@ std::shared_ptr 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"); } @@ -161,9 +162,10 @@ std::shared_ptr 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(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(std::chrono::steady_clock::now() - start).count()); + file->setGridInfo(se, std::chrono::duration(accessed - start).count(), replicaOpen); return file; } diff --git a/Framework/AnalysisSupport/src/NativeAOD.cxx b/Framework/AnalysisSupport/src/NativeAOD.cxx index 4c4fb6ef31cb8..6ac52b2085280 100644 --- a/Framework/AnalysisSupport/src/NativeAOD.cxx +++ b/Framework/AnalysisSupport/src/NativeAOD.cxx @@ -13,6 +13,7 @@ #include "AODNative/Errors.h" #include "Framework/RuntimeError.h" #include +#include #include namespace o2::framework @@ -97,9 +98,6 @@ std::shared_ptr 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); } @@ -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); } } @@ -334,11 +334,19 @@ std::shared_ptr NativeAODInputFile::open(std::unique_ptr(new NativeAODInputFile); result->mName = name; + auto start = std::chrono::steady_clock::now(); + double failover = source->failoverSeconds(); result->mFile = std::make_shared(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(opened - start).count() - (file.failoverSeconds() - failover); + failover = file.failoverSeconds(); result->mFilesystem = std::make_shared(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(); @@ -349,13 +357,15 @@ std::shared_ptr NativeAODInputFile::open(std::unique_ptrmPrepareTime = std::chrono::duration(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 @@ -363,9 +373,13 @@ 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(); } diff --git a/Framework/AnalysisSupport/src/NativeAOD.h b/Framework/AnalysisSupport/src/NativeAOD.h index 70e1b515ff547..d60148515e292 100644 --- a/Framework/AnalysisSupport/src/NativeAOD.h +++ b/Framework/AnalysisSupport/src/NativeAOD.h @@ -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 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 open(std::unique_ptr 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; } @@ -144,7 +145,8 @@ class NativeAODInputFile : public AODInputFile std::vector topLevelKeys() override; std::vector keysIn(std::string const& dir) override; std::map parentFiles() override { return mParentFiles; } - std::map metaData() override { return mMetaData; } + /// Read when asked for: the reader does not need it, and it costs a round trip at open. + std::map metaData() override { return mFile->readStringMap("metaData"); } std::shared_ptr filesystem() override { return mFilesystem; } void setReadOrder(std::vector const& dfs) override { mFilesystem->setReadOrder(dfs); } @@ -152,11 +154,12 @@ class NativeAODInputFile : public AODInputFile 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 mFile; std::shared_ptr mFilesystem; std::map mParentFiles; - std::map mMetaData; }; } // namespace o2::framework