Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RPageStorageFile.cxx
Go to the documentation of this file.
1/// \file RPageStorageFile.cxx
2/// \author Jakob Blomer <jblomer@cern.ch>
3/// \date 2019-11-25
4
5/*************************************************************************
6 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
7 * All rights reserved. *
8 * *
9 * For the licensing terms see $ROOTSYS/LICENSE. *
10 * For the list of contributors see $ROOTSYS/README/CREDITS. *
11 *************************************************************************/
12
13#include <ROOT/RCluster.hxx>
14#include <ROOT/RLogger.hxx>
16#include <ROOT/RNTupleModel.hxx>
18#include <ROOT/RNTupleZip.hxx>
19#include <ROOT/RPage.hxx>
21#include <ROOT/RPagePool.hxx>
23#include <ROOT/RRawFile.hxx>
25#include <ROOT/RNTupleTypes.hxx>
26#include <ROOT/RNTupleUtils.hxx>
27#include <ROOT/RVersion.hxx>
28
29#include <TDirectory.h>
30#include <TError.h>
32
33#include <algorithm>
34#include <cstdio>
35#include <cstdlib>
36#include <cstring>
37#include <functional>
38#include <iterator>
39#include <limits>
40#include <mutex>
41#include <utility>
42
51
53 : RPagePersistentSink(ntupleName, options)
54{
55 EnableDefaultMetrics("RPageSinkFile");
57}
58
59ROOT::Internal::RPageSinkFile::RPageSinkFile(std::string_view ntupleName, std::string_view path,
60 const ROOT::RNTupleWriteOptions &options)
61 : RPageSinkFile(ntupleName, options)
62{
64}
65
66ROOT::Internal::RPageSinkFile::RPageSinkFile(std::string_view ntupleName, TDirectory &fileOrDirectory,
67 const ROOT::RNTupleWriteOptions &options)
68 : RPageSinkFile(ntupleName, options)
69{
70 fWriter = RNTupleFileWriter::Append(ntupleName, fileOrDirectory, options.GetMaxKeySize(), /*isHidden=*/false);
71}
72
73ROOT::Internal::RPageSinkFile::RPageSinkFile(std::string_view ntupleName, ROOT::RFile &file, std::string_view ntupleDir,
74 const ROOT::RNTupleWriteOptions &options)
75 : RPageSinkFile(ntupleName, options)
76{
77 fWriter = RNTupleFileWriter::Append(ntupleName, file, ntupleDir, options.GetMaxKeySize());
78}
79
80ROOT::Internal::RPageSinkFile::RPageSinkFile(std::unique_ptr<ROOT::Internal::RNTupleFileWriter> writer,
81 const ROOT::RNTupleWriteOptions &options)
82 : RPageSinkFile(writer->GetNTupleName(), options)
83{
84 fWriter = std::move(writer);
85}
86
88
89void ROOT::Internal::RPageSinkFile::InitImpl(unsigned char *serializedHeader, std::uint32_t length)
90{
91 auto zipBuffer = MakeUninitArray<unsigned char>(length);
92 auto szZipHeader =
93 RNTupleCompressor::Zip(serializedHeader, length, GetWriteOptions().GetCompression(), zipBuffer.get());
94 fWriter->WriteNTupleHeader(zipBuffer.get(), szZipHeader, length);
95}
96
98 ROOT::NTupleSize_t firstEntry)
99{
100 RPagePersistentSink::UpdateSchema(changeset, firstEntry);
101
102 auto fnAddStreamerInfo = [this](const ROOT::RFieldBase *field) {
103 const TClass *cl = nullptr;
104 if (auto classField = dynamic_cast<const RClassField *>(field)) {
105 cl = classField->GetClass();
106 } else if (auto streamerField = dynamic_cast<const RStreamerField *>(field)) {
107 cl = streamerField->GetClass();
108 } else if (auto soaField = dynamic_cast<const RSoAField *>(field)) {
109 cl = soaField->GetSoAClass();
110 }
111 if (!cl)
112 return;
113
114 auto streamerInfo = cl->GetStreamerInfo(field->GetTypeVersion());
115 if (!streamerInfo) {
116 throw RException(R__FAIL(std::string("cannot get streamerInfo for ") + cl->GetName() + " [" +
117 std::to_string(field->GetTypeVersion()) + "]"));
118 }
119 fInfosOfClassFields[streamerInfo->GetNumber()] = streamerInfo;
120 };
121
122 for (const auto field : changeset.fAddedFields) {
123 fnAddStreamerInfo(field);
124 for (const auto &subField : *field) {
125 fnAddStreamerInfo(&subField);
126 }
127 }
128}
129
132{
133 std::uint64_t offsetData;
134 {
135 RNTupleAtomicTimer timer(fCounters->fTimeWallWrite, fCounters->fTimeCpuWrite);
136 offsetData = fWriter->WriteBlob(sealedPage.GetBuffer(), sealedPage.GetBufferSize(), bytesPacked);
137 }
138
140 result.SetPosition(offsetData);
141 result.SetNBytesOnStorage(sealedPage.GetDataSize());
142 fCounters->fNPageCommitted.Inc();
143 fCounters->fSzWritePayload.Add(sealedPage.GetBufferSize());
144 fNBytesCurrentCluster += sealedPage.GetBufferSize();
145 return result;
146}
147
149 const RPageStorage::RSealedPage &sealedPage)
150{
151 const auto nBits = fDescriptorBuilder.GetDescriptor().GetColumnDescriptor(physicalColumnId).GetBitsOnStorage();
152 const auto bytesPacked = (nBits * sealedPage.GetNElements() + 7) / 8;
153 return WriteSealedPage(sealedPage, bytesPacked);
154}
155
156void ROOT::Internal::RPageSinkFile::CommitBatchOfPages(CommitBatch &batch, std::vector<RNTupleLocator> &locators)
157{
158 RNTupleAtomicTimer timer(fCounters->fTimeWallWrite, fCounters->fTimeCpuWrite);
159
160 std::uint64_t offset = fWriter->ReserveBlob(batch.fSize, batch.fBytesPacked);
161
162 locators.reserve(locators.size() + batch.fSealedPages.size());
163
164 for (const auto *pagePtr : batch.fSealedPages) {
165 fWriter->WriteIntoReservedBlob(pagePtr->GetBuffer(), pagePtr->GetBufferSize(), offset);
166 RNTupleLocator locator;
167 locator.SetPosition(offset);
168 locator.SetNBytesOnStorage(pagePtr->GetDataSize());
169 locators.push_back(locator);
170 offset += pagePtr->GetBufferSize();
171 }
172
173 fCounters->fNPageCommitted.Add(batch.fSealedPages.size());
174 fCounters->fSzWritePayload.Add(batch.fSize);
175 fNBytesCurrentCluster += batch.fSize;
176
177 batch.fSize = 0;
178 batch.fBytesPacked = 0;
179 batch.fSealedPages.clear();
180}
181
182std::vector<ROOT::RNTupleLocator>
183ROOT::Internal::RPageSinkFile::CommitSealedPageVImpl(std::span<RPageStorage::RSealedPageGroup> ranges,
184 const std::vector<bool> &mask)
185{
186 const std::uint64_t maxKeySize = fOptions->GetMaxKeySize();
187
188 CommitBatch batch{};
189 std::vector<RNTupleLocator> locators;
190
191 std::size_t iPage = 0;
192 for (auto rangeIt = ranges.begin(); rangeIt != ranges.end(); ++rangeIt) {
193 auto &range = *rangeIt;
194 if (range.fFirst == range.fLast) {
195 // Skip empty ranges, they might not have a physical column ID!
196 continue;
197 }
198
199 const auto bitsOnStorage =
200 fDescriptorBuilder.GetDescriptor().GetColumnDescriptor(range.fPhysicalColumnId).GetBitsOnStorage();
201
202 for (auto sealedPageIt = range.fFirst; sealedPageIt != range.fLast; ++sealedPageIt, ++iPage) {
203 if (!mask[iPage])
204 continue;
205
206 const auto bytesPacked = (bitsOnStorage * sealedPageIt->GetNElements() + 7) / 8;
207
208 if (batch.fSize > 0 && batch.fSize + sealedPageIt->GetBufferSize() > maxKeySize) {
209 /**
210 * Adding this page would exceed maxKeySize. Since we always want to write into a single key
211 * with vectorized writes, we commit the current set of pages before proceeding.
212 * NOTE: we do this *before* checking if sealedPageIt->GetBufferSize() > maxKeySize to guarantee that
213 * we always flush the current batch before doing an individual WriteBlob. This way we
214 * preserve the assumption that a CommitBatch always contain a sequential set of pages.
215 */
216 CommitBatchOfPages(batch, locators);
217 }
218
219 if (sealedPageIt->GetBufferSize() > maxKeySize) {
220 // This page alone is bigger than maxKeySize: save it by itself, since it will need to be
221 // split into multiple keys.
222
223 // Since this check implies the previous check on batchSize + newSize > maxSize, we should
224 // already have committed the current batch before writing this page.
225 assert(batch.fSize == 0);
226
227 std::uint64_t offset =
228 fWriter->WriteBlob(sealedPageIt->GetBuffer(), sealedPageIt->GetBufferSize(), bytesPacked);
229 RNTupleLocator locator;
230 locator.SetPosition(offset);
231 locator.SetNBytesOnStorage(sealedPageIt->GetDataSize());
232 locators.push_back(locator);
233
234 fCounters->fNPageCommitted.Inc();
235 fCounters->fSzWritePayload.Add(sealedPageIt->GetBufferSize());
236 fNBytesCurrentCluster += sealedPageIt->GetBufferSize();
237
238 } else {
239 batch.fSealedPages.emplace_back(&(*sealedPageIt));
240 batch.fSize += sealedPageIt->GetBufferSize();
241 batch.fBytesPacked += bytesPacked;
242 }
243 }
244 }
245
246 if (batch.fSize > 0) {
247 CommitBatchOfPages(batch, locators);
248 }
249
250 return locators;
251}
252
254{
255 auto result = fNBytesCurrentCluster;
256 fNBytesCurrentCluster = 0;
257 return result;
258}
259
261ROOT::Internal::RPageSinkFile::CommitClusterGroupImpl(unsigned char *serializedPageList, std::uint32_t length)
262{
263 auto bufPageListZip = MakeUninitArray<unsigned char>(length);
264 auto szPageListZip =
265 RNTupleCompressor::Zip(serializedPageList, length, GetWriteOptions().GetCompression(), bufPageListZip.get());
266
268 result.SetNBytesOnStorage(szPageListZip);
269 result.SetPosition(fWriter->WriteBlob(bufPageListZip.get(), szPageListZip, length));
270 return result;
271}
272
274ROOT::Internal::RPageSinkFile::CommitDatasetImpl(unsigned char *serializedFooter, std::uint32_t length)
275{
276 // Add the streamer info records from streamer fields: because of runtime polymorphism we may need to add additional
277 // types not covered by the type names of the class fields
278 for (const auto &extraTypeInfo : fDescriptorBuilder.GetDescriptor().GetExtraTypeInfoIterable()) {
279 if (extraTypeInfo.GetContentId() != EExtraTypeInfoIds::kStreamerInfo)
280 continue;
281 // Ideally, we would avoid deserializing the streamer info records of the streamer fields that we just serialized.
282 // However, this happens only once at the end of writing and only when streamer fields are used, so the
283 // preference here is for code simplicity.
284 fInfosOfClassFields.merge(RNTupleSerializer::DeserializeStreamerInfos(extraTypeInfo.GetContent()).Unwrap());
285 }
286 fWriter->UpdateStreamerInfos(fInfosOfClassFields);
287
288 auto bufFooterZip = MakeUninitArray<unsigned char>(length);
289 auto szFooterZip =
290 RNTupleCompressor::Zip(serializedFooter, length, GetWriteOptions().GetCompression(), bufFooterZip.get());
291 fWriter->WriteNTupleFooter(bufFooterZip.get(), szFooterZip, length);
292 return fWriter->Commit(GetWriteOptions().GetCompression());
293}
294
295std::unique_ptr<ROOT::Internal::RPageSink>
297{
298 auto writer = fWriter->CloneAsHidden(name);
299 auto cloned = std::unique_ptr<RPageSinkFile>(new RPageSinkFile(std::move(writer), opts));
300 return cloned;
301}
302
303////////////////////////////////////////////////////////////////////////////////
304
306{
307 return source.fAnchor ? &*source.fAnchor : nullptr;
308}
309
311 : RPageSource(ntupleName, opts)
312{
313 EnableDefaultMetrics("RPageSourceFile");
314 fFileCounters = std::make_unique<RFileCounters>(RFileCounters{
315 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("szSkip", "B",
316 "cumulative seek distance (excluding header/footer reads)"),
318 "szFile", "B", "total file size", fMetrics,
319 [this](const RNTupleMetrics &) -> std::pair<bool, double> {
320 if (fFileSize > 0)
321 return {true, static_cast<double>(fFileSize)};
322 return {false, -1.};
323 }),
325 "randomness", "",
326 "ratio of seek distance to bytes read (excluding file structure reads)", fMetrics,
327 [](const RNTupleMetrics &metrics) -> std::pair<bool, double> {
328 if (const auto szSkip = metrics.GetLocalCounter("szSkip")) {
329 if (const auto szReadPayload = metrics.GetLocalCounter("szReadPayload")) {
330 if (const auto szReadOverhead = metrics.GetLocalCounter("szReadOverhead")) {
331 auto totalRead = szReadPayload->GetValueAsInt() + szReadOverhead->GetValueAsInt();
332 if (totalRead > 0) {
333 return {true, (1. * szSkip->GetValueAsInt()) / totalRead};
334 }
335 }
336 }
337 }
338 return {false, -1.};
339 }),
341 "sparseness", "",
342 "ratio of bytes read to total file size (excluding file structure reads)", fMetrics,
343 [this](const RNTupleMetrics &metrics) -> std::pair<bool, double> {
344 if (fFileSize > 0) {
345 if (const auto szReadPayload = metrics.GetLocalCounter("szReadPayload")) {
346 if (const auto szReadOverhead = metrics.GetLocalCounter("szReadOverhead")) {
347 auto totalRead = szReadPayload->GetValueAsInt() + szReadOverhead->GetValueAsInt();
348 return {true, (1. * totalRead) / fFileSize};
349 }
350 }
351 }
352 return {false, -1.};
353 })});
354}
355
357 std::unique_ptr<ROOT::Internal::RRawFile> file,
358 const ROOT::RNTupleReadOptions &options)
359 : RPageSourceFile(ntupleName, options)
360{
361 fFile = std::move(file);
364}
365
366ROOT::Internal::RPageSourceFile::RPageSourceFile(std::string_view ntupleName, std::string_view path,
367 const ROOT::RNTupleReadOptions &options)
368 : RPageSourceFile(ntupleName, ROOT::Internal::RRawFile::Create(path), options)
369{
370}
371
372std::unique_ptr<ROOT::Internal::RPageSourceFile>
374{
375 if (!anchor.fFile)
376 throw RException(R__FAIL("This RNTuple object was not streamed from a ROOT file (TFile or descendant)"));
377
378 std::unique_ptr<ROOT::Internal::RRawFile> rawFile;
379 // For local TFiles, TDavixFile, TCurlFile, and TNetXNGFile, we want to open a new RRawFile to take advantage of the
380 // faster reading. We check the exact class name to avoid classes inheriting in ROOT (for example TMemFile) or in
381 // experiment frameworks.
382 const std::string className = anchor.fFile->IsA()->GetName();
383 const auto url = anchor.fFile->GetEndpointUrl();
384 if (className == "TFile") {
385 rawFile = ROOT::Internal::RRawFile::Create(url->GetFile());
386 } else if (className == "TDavixFile" || className == "TCurlFile" || className == "TNetXNGFile") {
387 rawFile = ROOT::Internal::RRawFile::Create(url->GetUrl());
388 } else {
389 rawFile.reset(new ROOT::Internal::RRawFileTFile(anchor.fFile));
390 }
391
392 auto pageSource = std::make_unique<RPageSourceFile>("", std::move(rawFile), options);
393 pageSource->fAnchor = anchor;
394 // NOTE: fNTupleName gets set only upon Attach().
395 return pageSource;
396}
397
399{
400 StopClusterPoolBackgroundThread();
401}
402
403std::unique_ptr<ROOT::Internal::RPageSource>
405 const ROOT::RNTupleReadOptions &options)
406{
407 assert(anchorLink.fLocator.GetType() == RNTupleLocator::kTypeFile);
408
409 const auto anchorPos = anchorLink.fLocator.GetPosition<std::uint64_t>();
410 auto anchor =
411 fReader.GetNTupleProperAtOffset(anchorPos, anchorLink.fLocator.GetNBytesOnStorage(), anchorLink.fLength).Unwrap();
412 auto pageSource = std::make_unique<RPageSourceFile>("", fFile->Clone(), options);
413 pageSource->fAnchor = anchor;
414 // NOTE: fNTupleName gets set only upon Attach().
415 return pageSource;
416}
417
419{
420 // If we constructed the page source with (ntuple name, path), we need to find the anchor first.
421 // Otherwise, the page source was created by OpenFromAnchor()
422 if (!fAnchor) {
423 fAnchor = fReader.GetNTuple(fNTupleName).Unwrap();
424 // We couple finding the RNTuple anchor to loading the streamer infos.
425 // If we already have the anchor, we must have opened the file before (either through TFile or by the source of
426 // OpenWithDifferentAnchor(), in which case we already loaded the streamer info) .
427 fReader.LoadStreamerInfo();
428 }
429 fReader.SetMaxKeySize(fAnchor->GetMaxKeySize());
430
431 fDescriptorBuilder.SetVersion(fAnchor->GetVersionEpoch(), fAnchor->GetVersionMajor(), fAnchor->GetVersionMinor(),
432 fAnchor->GetVersionPatch());
433 fDescriptorBuilder.SetOnDiskHeaderSize(fAnchor->GetNBytesHeader());
434 fDescriptorBuilder.AddToOnDiskFooterSize(fAnchor->GetNBytesFooter());
435
436 // Reserve enough space for the compressed and the uncompressed header/footer (see AttachImpl)
437 const auto bufSize = fAnchor->GetNBytesHeader() + fAnchor->GetNBytesFooter() +
438 std::max(fAnchor->GetLenHeader(), fAnchor->GetLenFooter());
439 fStructureBuffer.fBuffer = MakeUninitArray<unsigned char>(bufSize);
440 fStructureBuffer.fPtrHeader = fStructureBuffer.fBuffer.get();
441 fStructureBuffer.fPtrFooter = fStructureBuffer.fBuffer.get() + fAnchor->GetNBytesHeader();
442
443 auto readvLimits = fFile->GetReadVLimits();
444 // Never try to vectorize reads to a split key
445 readvLimits.fMaxSingleSize = std::min<size_t>(readvLimits.fMaxSingleSize, fAnchor->GetMaxKeySize());
446
447 if ((readvLimits.fMaxReqs < 2) ||
448 (std::max(fAnchor->GetNBytesHeader(), fAnchor->GetNBytesFooter()) > readvLimits.fMaxSingleSize) ||
449 (fAnchor->GetNBytesHeader() + fAnchor->GetNBytesFooter() > readvLimits.fMaxTotalSize)) {
450 RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
451 fReader.ReadBuffer(fStructureBuffer.fPtrHeader, fAnchor->GetNBytesHeader(), fAnchor->GetSeekHeader());
452 fReader.ReadBuffer(fStructureBuffer.fPtrFooter, fAnchor->GetNBytesFooter(), fAnchor->GetSeekFooter());
453 fCounters->fNRead.Add(2);
454 } else {
455 RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
456 R__ASSERT(fAnchor->GetNBytesHeader() < std::numeric_limits<std::size_t>::max());
457 R__ASSERT(fAnchor->GetNBytesFooter() < std::numeric_limits<std::size_t>::max());
458 ROOT::Internal::RRawFile::RIOVec readRequests[2] = {{fStructureBuffer.fPtrHeader, fAnchor->GetSeekHeader(),
459 static_cast<std::size_t>(fAnchor->GetNBytesHeader()), 0},
460 {fStructureBuffer.fPtrFooter, fAnchor->GetSeekFooter(),
461 static_cast<std::size_t>(fAnchor->GetNBytesFooter()), 0}};
462 fFile->ReadV(readRequests, 2);
463 fCounters->fNReadV.Inc();
464 }
465}
466
468{
469 auto unzipBuf = reinterpret_cast<unsigned char *>(fStructureBuffer.fPtrFooter) + fAnchor->GetNBytesFooter();
470
471 RNTupleDecompressor::Unzip(fStructureBuffer.fPtrHeader, fAnchor->GetNBytesHeader(), fAnchor->GetLenHeader(),
472 unzipBuf);
473 RNTupleSerializer::DeserializeHeader(unzipBuf, fAnchor->GetLenHeader(), fDescriptorBuilder);
474
475 RNTupleDecompressor::Unzip(fStructureBuffer.fPtrFooter, fAnchor->GetNBytesFooter(), fAnchor->GetLenFooter(),
476 unzipBuf);
477 RNTupleSerializer::DeserializeFooter(unzipBuf, fAnchor->GetLenFooter(), fDescriptorBuilder);
478
479 // fNTupleName is empty if and only if we created this source via CreateFromAnchor. If that's the case, this is the
480 // earliest we can set the name.
481 if (fNTupleName.empty())
482 fNTupleName = fDescriptorBuilder.GetDescriptor().GetName();
483
484 // For the page reads, we rely on the I/O scheduler to define the read requests
485 fFile->SetBuffering(false);
486
487 // Set file size once after buffering is turned off
488 fFileSize = fFile->GetSize();
489
490 return fDescriptorBuilder.MoveDescriptor();
491}
492
494{
495 // Track seek distance (excluding file structure reads)
496 if (fLastOffset == 0)
497 return;
498
499 assert(fFileCounters);
500 const auto distance =
501 static_cast<std::uint64_t>(std::abs(static_cast<std::int64_t>(offset) - static_cast<std::int64_t>(fLastOffset)));
502 fFileCounters->fSzSkip.Add(distance);
503}
504
505void ROOT::Internal::RPageSourceFile::LoadPageListImpl(const RNTupleLocator &locator, unsigned char *buffer)
506{
507 RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
508 std::lock_guard lockGuard(fReaderLock);
509 const auto offset = locator.GetPosition<std::uint64_t>();
510 UpdateSkipCounter(offset);
511 fReader.ReadBuffer(buffer, locator.GetNBytesOnStorage(), offset);
512 fLastOffset = offset + locator.GetNBytesOnStorage();
513}
514
516{
517 RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
518 std::lock_guard lockGuard(fReaderLock);
519 const auto offset = locator.GetPosition<std::uint64_t>();
520 UpdateSkipCounter(offset);
521 fReader.ReadBuffer(const_cast<void *>(sealedPage.GetBuffer()), sealedPage.GetBufferSize(), offset);
522 fLastOffset = offset + sealedPage.GetBufferSize();
523}
524
525std::unique_ptr<ROOT::Internal::RPageSource> ROOT::Internal::RPageSourceFile::CloneImpl() const
526{
527 auto clone = new RPageSourceFile(fNTupleName, fOptions);
528 clone->fFile = fFile->Clone();
529 clone->fReader = ROOT::Internal::RMiniFileReader(clone->fFile.get());
530 return std::unique_ptr<RPageSourceFile>(clone);
531}
532
533std::unique_ptr<ROOT::Internal::RCluster>
535 std::vector<ROOT::Internal::RRawFile::RIOVec> &readRequests)
536{
537 struct ROnDiskPageLocator {
538 ROOT::DescriptorId_t fColumnId = 0;
539 ROOT::NTupleSize_t fPageNo = 0;
540 std::uint64_t fOffset = 0;
541 std::uint64_t fSize = 0;
542 std::size_t fBufPos = 0;
543 };
544
545 std::vector<ROnDiskPageLocator> onDiskPages;
546 auto activeSize = 0;
547 auto pageZeroMap = std::make_unique<ROnDiskPageMap>();
548 PrepareLoadCluster(
549 clusterKey, *pageZeroMap,
550 [&](ROOT::DescriptorId_t physicalColumnId, ROOT::NTupleSize_t pageNo,
551 const ROOT::RClusterDescriptor::RPageInfo &pageInfo) {
552 const auto &pageLocator = pageInfo.GetLocator();
553 if (pageLocator.GetType() == RNTupleLocator::kTypeUnknown)
554 throw RException(R__FAIL("tried to read a page with an unknown locator"));
555 const auto nBytes = pageLocator.GetNBytesOnStorage() + pageInfo.HasChecksum() * kNBytesPageChecksum;
556 activeSize += nBytes;
557 onDiskPages.push_back({physicalColumnId, pageNo, pageLocator.GetPosition<std::uint64_t>(), nBytes, 0});
558 });
559
560 // Linearize the page requests by file offset
561 std::sort(onDiskPages.begin(), onDiskPages.end(),
562 [](const ROnDiskPageLocator &a, const ROnDiskPageLocator &b) { return a.fOffset < b.fOffset; });
563
564 // In order to coalesce close-by pages, we collect the sizes of the gaps between pages on disk. We then order
565 // the gaps by size, sum them up and find a cutoff for the largest gap that we tolerate when coalescing pages.
566 // The size of the cutoff is given by the fraction of extra bytes we are willing to read in order to reduce
567 // the number of read requests. We thus schedule the lowest number of requests given a tolerable fraction
568 // of extra bytes.
569 // TODO(jblomer): Eventually we may want to select the parameter at runtime according to link latency and speed,
570 // memory consumption, device block size.
571 float maxOverhead = 0.25 * float(activeSize);
572 std::vector<std::size_t> gaps;
573 if (onDiskPages.size())
574 gaps.reserve(onDiskPages.size() - 1);
575 for (unsigned i = 1; i < onDiskPages.size(); ++i) {
576 std::int64_t gap =
577 static_cast<int64_t>(onDiskPages[i].fOffset) - (onDiskPages[i - 1].fSize + onDiskPages[i - 1].fOffset);
578 gaps.emplace_back(std::max(gap, std::int64_t(0)));
579 // If the pages overlap, substract the overlapped bytes from `activeSize`
580 activeSize += std::min(gap, std::int64_t(0));
581 }
582 std::sort(gaps.begin(), gaps.end());
583 std::size_t gapCut = 0;
584 std::size_t currentGap = 0;
585 float szExtra = 0.0;
586 for (auto g : gaps) {
587 if (g != currentGap) {
588 gapCut = currentGap;
589 currentGap = g;
590 }
591 szExtra += g;
592 if (szExtra > maxOverhead)
593 break;
594 }
595
596 // In a first step, we coalesce the read requests and calculate the cluster buffer size.
597 // In a second step, we'll fix-up the memory destinations for the read calls given the
598 // address of the allocated buffer. We must not touch, however, the read requests from previous
599 // calls to PrepareSingleCluster()
600 const auto currentReadRequestIdx = readRequests.size();
601
603 // To simplify the first loop iteration, pretend an empty request starting at the first page's fOffset.
604 if (!onDiskPages.empty())
605 req.fOffset = onDiskPages[0].fOffset;
606 std::size_t szPayload = 0;
607 std::size_t szOverhead = 0;
608 const std::uint64_t maxKeySize = fReader.GetMaxKeySize();
609 for (auto &s : onDiskPages) {
610 R__ASSERT(s.fSize > 0);
611 const std::int64_t readUpTo = req.fOffset + req.fSize;
612 // Note: byte ranges of pages may overlap
613 const std::uint64_t overhead = std::max(static_cast<std::int64_t>(s.fOffset) - readUpTo, std::int64_t(0));
614 const std::uint64_t extent = std::max(static_cast<std::int64_t>(s.fOffset + s.fSize) - readUpTo, std::int64_t(0));
615 if (req.fSize + extent < maxKeySize && overhead <= gapCut) {
616 szPayload += (extent - overhead);
617 szOverhead += overhead;
618 s.fBufPos = reinterpret_cast<intptr_t>(req.fBuffer) + s.fOffset - req.fOffset;
619 req.fSize += extent;
620 continue;
621 }
622
623 // close the current request and open new one
624 if (req.fSize > 0)
625 readRequests.emplace_back(req);
626
627 req.fBuffer = reinterpret_cast<unsigned char *>(req.fBuffer) + req.fSize;
628 s.fBufPos = reinterpret_cast<intptr_t>(req.fBuffer);
629
630 szPayload += s.fSize;
631 req.fOffset = s.fOffset;
632 req.fSize = s.fSize;
633 }
634 readRequests.emplace_back(req);
635 fCounters->fSzReadPayload.Add(szPayload);
636 fCounters->fSzReadOverhead.Add(szOverhead);
637
638 // Register the on disk pages in a page map
639 auto buffer = new unsigned char[reinterpret_cast<intptr_t>(req.fBuffer) + req.fSize];
640 auto pageMap = std::make_unique<ROOT::Internal::ROnDiskPageMapHeap>(std::unique_ptr<unsigned char[]>(buffer));
641 for (const auto &s : onDiskPages) {
642 ROnDiskPage::Key key(s.fColumnId, s.fPageNo);
643 pageMap->Register(key, ROnDiskPage(buffer + s.fBufPos, s.fSize));
644 }
645 fCounters->fNPageRead.Add(onDiskPages.size());
646 for (auto i = currentReadRequestIdx; i < readRequests.size(); ++i) {
647 readRequests[i].fBuffer = buffer + reinterpret_cast<intptr_t>(readRequests[i].fBuffer);
648 }
649
650 auto cluster = std::make_unique<RCluster>(clusterKey.fClusterId);
651 cluster->Adopt(std::move(pageMap));
652 cluster->Adopt(std::move(pageZeroMap));
653 for (auto colId : clusterKey.fPhysicalColumnSet)
654 cluster->SetColumnAvailable(colId);
655 return cluster;
656}
657
658std::vector<std::unique_ptr<ROOT::Internal::RCluster>>
659ROOT::Internal::RPageSourceFile::LoadClusters(std::span<RCluster::RKey> clusterKeys)
660{
661 fCounters->fNClusterLoaded.Add(clusterKeys.size());
662
663 std::vector<std::unique_ptr<ROOT::Internal::RCluster>> clusters;
664 std::vector<ROOT::Internal::RRawFile::RIOVec> readRequests;
665
666 clusters.reserve(clusterKeys.size());
667 for (const auto &key : clusterKeys) {
668 clusters.emplace_back(PrepareSingleCluster(key, readRequests));
669 }
670
671 auto nReqs = readRequests.size();
672 auto readvLimits = fFile->GetReadVLimits();
673 // We never want to do vectorized reads of split blobs, so we limit our single size to maxKeySize.
674 readvLimits.fMaxSingleSize = std::min<size_t>(readvLimits.fMaxSingleSize, fReader.GetMaxKeySize());
675
676 int iReq = 0;
677 while (nReqs > 0) {
678 auto nBatch = std::min(nReqs, readvLimits.fMaxReqs);
679
680 if (readvLimits.HasSizeLimit()) {
681 std::uint64_t totalSize = 0;
682 for (std::size_t i = 0; i < nBatch; ++i) {
683 if (readRequests[iReq + i].fSize > readvLimits.fMaxSingleSize) {
684 nBatch = i;
685 break;
686 }
687
688 totalSize += readRequests[iReq + i].fSize;
689 if (totalSize > readvLimits.fMaxTotalSize) {
690 nBatch = i;
691 break;
692 }
693 }
694 }
695
696 std::lock_guard lockGuard(fReaderLock);
697
698 // Track seek distance for each read request (excluding file structure reads)
699 for (std::size_t i = 0; i < nBatch; ++i) {
700 const auto offset = readRequests[iReq + i].fOffset;
701 UpdateSkipCounter(offset);
702 fLastOffset = offset + readRequests[iReq + i].fSize;
703 }
704
705 if (nBatch <= 1) {
706 nBatch = 1;
707 RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
708 fReader.ReadBuffer(readRequests[iReq].fBuffer, readRequests[iReq].fSize, readRequests[iReq].fOffset);
709 } else {
710 RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
711 fFile->ReadV(&readRequests[iReq], nBatch);
712 }
713 fCounters->fNReadV.Inc();
714 fCounters->fNRead.Add(nBatch);
715
716 iReq += nBatch;
717 nReqs -= nBatch;
718 }
719
720 return clusters;
721}
fBuffer
dim_t fSize
#define R__FAIL(msg)
Short-hand to return an RResult<T> in an error state; the RError is implicitly converted into RResult...
Definition RError.hxx:322
#define b(i)
Definition RSha256.hxx:100
#define g(i)
Definition RSha256.hxx:105
#define a(i)
Definition RSha256.hxx:99
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:139
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t mask
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h length
char name[80]
Definition TGX11.cxx:142
A thread-safe integral performance counter.
A metric element that computes its floating point value from other counters.
A collection of Counter objects with a name, a unit, and a description.
const RNTuplePerfCounter * GetLocalCounter(std::string_view name) const
Searches counters registered in this object only. Returns nullptr if name is not found.
CounterPtrT MakeCounter(const std::string &name, Args &&... args)
Record wall time and CPU time between construction and destruction.
An in-memory subset of the packed and compressed pages of a cluster.
Definition RCluster.hxx:147
Read RNTuple data blocks from a TFile container, provided by a RRawFile.
Definition RMiniFile.hxx:55
static std::size_t Zip(const void *from, std::size_t nbytes, int compression, void *to)
Returns the size of the compressed data, written into the provided output buffer.
static void Unzip(const void *from, size_t nbytes, size_t dataLen, void *to)
The nbytes parameter provides the size ls of the from buffer.
Write RNTuple data blocks in a TFile or a bare file container.
static std::unique_ptr< RNTupleFileWriter > Append(std::string_view ntupleName, TDirectory &fileOrDirectory, std::uint64_t maxKeySize, bool isHidden)
The directory parameter can also be a TFile object (TFile inherits from TDirectory).
static std::unique_ptr< RNTupleFileWriter > Recreate(std::string_view ntupleName, std::string_view path, EContainerFormat containerFormat, const ROOT::RNTupleWriteOptions &options)
Create or truncate the local file given by path with the new empty RNTuple identified by ntupleName.
static RResult< void > DeserializeFooter(const void *buffer, std::uint64_t bufSize, ROOT::Internal::RNTupleDescriptorBuilder &descBuilder)
static RResult< StreamerInfoMap_t > DeserializeStreamerInfos(const std::string &extraTypeInfoContent)
static RResult< void > DeserializeHeader(const void *buffer, std::uint64_t bufSize, ROOT::Internal::RNTupleDescriptorBuilder &descBuilder)
A memory region that contains packed and compressed pages.
Definition RCluster.hxx:98
A page as being stored on disk, that is packed and compressed.
Definition RCluster.hxx:40
Base class for a sink with a physical storage backend.
void UpdateSchema(const ROOT::Internal::RNTupleModelChangeset &changeset, ROOT::NTupleSize_t firstEntry) override
Incorporate incremental changes to the model into the ntuple descriptor.
void EnableDefaultMetrics(const std::string &prefix)
Enables the default set of metrics provided by RPageSink.
Storage provider that write ntuple pages into a file.
void CommitBatchOfPages(CommitBatch &batch, std::vector< RNTupleLocator > &locators)
Subroutine of CommitSealedPageVImpl, used to perform a vector write of the (multi-)range of pages con...
RPageSinkFile(std::string_view ntupleName, const ROOT::RNTupleWriteOptions &options)
std::unique_ptr< RPageSink > CloneAsHidden(std::string_view name, const ROOT::RNTupleWriteOptions &opts) const override
Creates a new sink with the same underlying storage as this but writing to a different RNTuple named ...
RNTupleLocator CommitSealedPageImpl(ROOT::DescriptorId_t physicalColumnId, const RPageStorage::RSealedPage &sealedPage) override
std::uint64_t StageClusterImpl() final
Returns the number of bytes written to storage (excluding metadata)
void InitImpl(unsigned char *serializedHeader, std::uint32_t length) final
RNTupleLocator WriteSealedPage(const RPageStorage::RSealedPage &sealedPage, std::size_t bytesPacked)
We pass bytesPacked so that TFile::ls() reports a reasonable value for the compression ratio of the c...
RNTupleLocator CommitClusterGroupImpl(unsigned char *serializedPageList, std::uint32_t length) final
Returns the locator of the page list envelope of the given buffer that contains the serialized page l...
RNTupleLink CommitDatasetImpl() final
std::unique_ptr< ROOT::Internal::RNTupleFileWriter > fWriter
void UpdateSchema(const ROOT::Internal::RNTupleModelChangeset &changeset, ROOT::NTupleSize_t firstEntry) final
Incorporate incremental changes to the model into the ntuple descriptor.
std::vector< RNTupleLocator > CommitSealedPageVImpl(std::span< RPageStorage::RSealedPageGroup > ranges, const std::vector< bool > &mask) final
Vector commit of preprocessed pages.
Storage provider that reads ntuple pages from a file.
ROOT::RNTupleDescriptor AttachImpl() final
LoadStructureImpl() has been called before AttachImpl() is called
std::int64_t fFileSize
Total file size, set once in AttachImpl()
std::unique_ptr< ROOT::Internal::RCluster > PrepareSingleCluster(const ROOT::Internal::RCluster::RKey &clusterKey, std::vector< RRawFile::RIOVec > &readRequests)
Helper function for LoadClusters: it prepares the memory buffer (page map) and the read requests for ...
std::unique_ptr< RPageSource > OpenWithDifferentAnchor(const ROOT::Internal::RNTupleLink &anchorLink, const ROOT::RNTupleReadOptions &options={}) final
Creates a new PageSource using the same underlying file as this but referring to a different RNTuple,...
void UpdateSkipCounter(std::uint64_t offset)
static std::unique_ptr< RPageSourceFile > CreateFromAnchor(const RNTuple &anchor, const ROOT::RNTupleReadOptions &options=ROOT::RNTupleReadOptions())
Used from the RNTuple class to build a datasource if the anchor is already available.
void LoadPageListImpl(const RNTupleLocator &locator, unsigned char *buffer) final
std::vector< std::unique_ptr< ROOT::Internal::RCluster > > LoadClusters(std::span< ROOT::Internal::RCluster::RKey > clusterKeys) final
Populates all the pages of the given cluster ids and columns; it is possible that some columns do not...
std::unique_ptr< RFileCounters > fFileCounters
void LoadSealedPageImpl(const RNTupleLocator &locator, RSealedPage &sealedPage) final
RPageSourceFile(std::string_view ntupleName, const ROOT::RNTupleReadOptions &options)
std::unique_ptr< RPageSource > CloneImpl() const final
The cloned page source creates a new raw file and reader and opens its own file descriptor to the dat...
void LoadStructureImpl() final
Fills fStructureBuffer with the compressed header and footer.
std::unique_ptr< RRawFile > fFile
An RRawFile is used to request the necessary byte ranges from a local or a remote file.
std::optional< RNTuple > fAnchor
Either provided by CreateFromAnchor, or read from the ROOT file given the ntuple name.
ROOT::Internal::RMiniFileReader fReader
Takes the fFile to read ntuple blobs from it.
Abstract interface to read data from an ntuple.
void EnableDefaultMetrics(const std::string &prefix)
Enables the default set of metrics provided by RPageSource.
ROOT::Experimental::Detail::RNTupleMetrics fMetrics
The RRawFileTFile wraps an open TFile, but does not take ownership.
The RRawFile provides read-only access to local and remote files.
Definition RRawFile.hxx:43
static std::unique_ptr< RRawFile > Create(std::string_view url, ROptions options=ROptions())
Factory method that returns a suitable concrete implementation according to the transport in the url.
Definition RRawFile.cxx:65
The field for a class with dictionary.
Definition RField.hxx:184
Base class for all ROOT issued exceptions.
Definition RError.hxx:78
A field translates read and write calls from/to underlying columns to/from tree values.
An interface to read from, or write to, a ROOT file, as well as performing other common operations.
Definition RFile.hxx:254
The on-storage metadata of an RNTuple.
Generic information about the physical location of data.
std::uint64_t GetNBytesOnStorage() const
ELocatorType GetType() const
For non-disk locators, the value for the Type field.
T GetPosition() const
Note that for GetPosition() / SetPosition(), the locator type must correspond (kTypeFile,...
void SetPosition(std::uint64_t position)
void SetNBytesOnStorage(std::uint64_t nBytesOnStorage)
Common user-tunable settings for reading RNTuples.
Common user-tunable settings for storing RNTuples.
std::uint64_t GetMaxKeySize() const
Representation of an RNTuple data set in a ROOT file.
Definition RNTuple.hxx:67
TFile * fFile
! The file from which the ntuple was streamed, registered in the custom streamer
Definition RNTuple.hxx:123
The SoA field provides I/O for an in-memory SoA layout linked to an on-disk collection of the underly...
Definition RFieldSoA.hxx:54
The field for a class using ROOT standard streaming.
Definition RField.hxx:245
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
TVirtualStreamerInfo * GetStreamerInfo(Int_t version=0, Bool_t isTransient=kFALSE) const
returns a pointer to the TVirtualStreamerInfo object for version If the object does not exist,...
Definition TClass.cxx:4720
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition TClass.cxx:2999
Describe directory structure in memory.
Definition TDirectory.h:45
virtual const TUrl * GetEndpointUrl() const
Definition TFile.h:323
TClass * IsA() const override
Definition TFile.h:436
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
const ROOT::RNTuple * GetAnchorFromFile(const RPageSourceFile &source)
std::uint64_t DescriptorId_t
Distriniguishes elements of the same type within a descriptor, e.g. different fields.
std::uint64_t NTupleSize_t
Integer type long enough to hold the maximum number of entries in a column.
The identifiers that specifies the content of a (partial) cluster.
Definition RCluster.hxx:151
ROOT::DescriptorId_t fClusterId
Definition RCluster.hxx:152
The incremental changes to a RNTupleModel
std::vector< ROOT::RFieldBase * > fAddedFields
Points to the fields in fModel that were added as part of an updater transaction.
On-disk pages within a page source are identified by the column and page number.
Definition RCluster.hxx:50
size_t fSize
Total size in bytes of the batch.
std::vector< const RSealedPage * > fSealedPages
The list of pages to commit.
size_t fBytesPacked
Total uncompressed size of the elements in the page batch.
File-specific I/O performance counters.
A sealed page contains the bytes of a page as written to storage (packed & compressed).
Used for vector reads from multiple offsets into multiple buffers.
Definition RRawFile.hxx:61
std::size_t fSize
The number of desired bytes.
Definition RRawFile.hxx:67
void * fBuffer
The destination for reading.
Definition RRawFile.hxx:63
std::uint64_t fOffset
The file offset.
Definition RRawFile.hxx:65
Information about a single page in the context of a cluster's page range.
const RNTupleLocator & GetLocator() const