Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RPageStorageFile.cxx
Go to the documentation of this file.
1/// \file RPageStorageFile.cxx
2/// \ingroup NTuple
3/// \author Jakob Blomer <jblomer@cern.ch>
4/// \date 2019-11-25
5
6/*************************************************************************
7 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
8 * All rights reserved. *
9 * *
10 * For the licensing terms see $ROOTSYS/LICENSE. *
11 * For the list of contributors see $ROOTSYS/README/CREDITS. *
12 *************************************************************************/
13
14#include <ROOT/RCluster.hxx>
15#include <ROOT/RClusterPool.hxx>
16#include <ROOT/RLogger.hxx>
18#include <ROOT/RNTupleModel.hxx>
20#include <ROOT/RNTupleZip.hxx>
21#include <ROOT/RPage.hxx>
23#include <ROOT/RPagePool.hxx>
25#include <ROOT/RRawFile.hxx>
27#include <ROOT/RNTupleUtil.hxx>
28
29#include <RVersion.h>
30#include <TDirectory.h>
31#include <TError.h>
33
34#include <algorithm>
35#include <cstdio>
36#include <cstdlib>
37#include <cstring>
38#include <iterator>
39#include <limits>
40#include <utility>
41
42#include <functional>
43#include <mutex>
44
56
63
70
77
79
81{
83 auto szZipHeader =
84 RNTupleCompressor::Zip(serializedHeader, length, GetWriteOptions().GetCompression(), zipBuffer.get());
85 fWriter->WriteNTupleHeader(zipBuffer.get(), szZipHeader, length);
86}
87
90{
92
93 auto fnAddStreamerInfo = [this](const ROOT::RFieldBase *field) {
94 const TClass *cl = nullptr;
95 if (auto classField = dynamic_cast<const RClassField *>(field)) {
96 cl = classField->GetClass();
97 } else if (auto streamerField = dynamic_cast<const RStreamerField *>(field)) {
98 cl = streamerField->GetClass();
99 }
100 if (!cl)
101 return;
102
103 auto streamerInfo = cl->GetStreamerInfo(field->GetTypeVersion());
104 if (!streamerInfo) {
105 throw RException(R__FAIL(std::string("cannot get streamerInfo for ") + cl->GetName() + " [" +
106 std::to_string(field->GetTypeVersion()) + "]"));
107 }
108 fInfosOfClassFields[streamerInfo->GetNumber()] = streamerInfo;
109 };
110
111 for (const auto field : changeset.fAddedFields) {
113 for (const auto &subField : *field) {
115 }
116 }
117}
118
121{
122 std::uint64_t offsetData;
123 {
124 RNTupleAtomicTimer timer(fCounters->fTimeWallWrite, fCounters->fTimeCpuWrite);
125 offsetData = fWriter->WriteBlob(sealedPage.GetBuffer(), sealedPage.GetBufferSize(), bytesPacked);
126 }
127
129 result.SetPosition(offsetData);
130 result.SetNBytesOnStorage(sealedPage.GetDataSize());
131 fCounters->fNPageCommitted.Inc();
132 fCounters->fSzWritePayload.Add(sealedPage.GetBufferSize());
133 fNBytesCurrentCluster += sealedPage.GetBufferSize();
134 return result;
135}
136
139{
140 auto element = columnHandle.fColumn->GetElement();
142 {
143 RNTupleAtomicTimer timer(fCounters->fTimeWallZip, fCounters->fTimeCpuZip);
144 sealedPage = SealPage(page, *element);
145 }
146
147 fCounters->fSzZip.Add(page.GetNBytes());
148 return WriteSealedPage(sealedPage, element->GetPackedSize(page.GetNElements()));
149}
150
153{
154 const auto nBits = fDescriptorBuilder.GetDescriptor().GetColumnDescriptor(physicalColumnId).GetBitsOnStorage();
155 const auto bytesPacked = (nBits * sealedPage.GetNElements() + 7) / 8;
156 return WriteSealedPage(sealedPage, bytesPacked);
157}
158
160{
161 RNTupleAtomicTimer timer(fCounters->fTimeWallWrite, fCounters->fTimeCpuWrite);
162
163 std::uint64_t offset = fWriter->ReserveBlob(batch.fSize, batch.fBytesPacked);
164
165 locators.reserve(locators.size() + batch.fSealedPages.size());
166
167 for (const auto *pagePtr : batch.fSealedPages) {
168 fWriter->WriteIntoReservedBlob(pagePtr->GetBuffer(), pagePtr->GetBufferSize(), offset);
170 locator.SetPosition(offset);
171 locator.SetNBytesOnStorage(pagePtr->GetDataSize());
172 locators.push_back(locator);
173 offset += pagePtr->GetBufferSize();
174 }
175
176 fCounters->fNPageCommitted.Add(batch.fSealedPages.size());
177 fCounters->fSzWritePayload.Add(batch.fSize);
178 fNBytesCurrentCluster += batch.fSize;
179
180 batch.fSize = 0;
181 batch.fBytesPacked = 0;
182 batch.fSealedPages.clear();
183}
184
185std::vector<ROOT::RNTupleLocator>
186ROOT::Internal::RPageSinkFile::CommitSealedPageVImpl(std::span<RPageStorage::RSealedPageGroup> ranges,
187 const std::vector<bool> &mask)
188{
189 const std::uint64_t maxKeySize = fOptions->GetMaxKeySize();
190
192 std::vector<RNTupleLocator> locators;
193
194 std::size_t iPage = 0;
195 for (auto rangeIt = ranges.begin(); rangeIt != ranges.end(); ++rangeIt) {
196 auto &range = *rangeIt;
197 if (range.fFirst == range.fLast) {
198 // Skip empty ranges, they might not have a physical column ID!
199 continue;
200 }
201
202 const auto bitsOnStorage =
203 fDescriptorBuilder.GetDescriptor().GetColumnDescriptor(range.fPhysicalColumnId).GetBitsOnStorage();
204
205 for (auto sealedPageIt = range.fFirst; sealedPageIt != range.fLast; ++sealedPageIt, ++iPage) {
206 if (!mask[iPage])
207 continue;
208
209 const auto bytesPacked = (bitsOnStorage * sealedPageIt->GetNElements() + 7) / 8;
210
211 if (batch.fSize > 0 && batch.fSize + sealedPageIt->GetBufferSize() > maxKeySize) {
212 /**
213 * Adding this page would exceed maxKeySize. Since we always want to write into a single key
214 * with vectorized writes, we commit the current set of pages before proceeding.
215 * NOTE: we do this *before* checking if sealedPageIt->GetBufferSize() > maxKeySize to guarantee that
216 * we always flush the current batch before doing an individual WriteBlob. This way we
217 * preserve the assumption that a CommitBatch always contain a sequential set of pages.
218 */
219 CommitBatchOfPages(batch, locators);
220 }
221
222 if (sealedPageIt->GetBufferSize() > maxKeySize) {
223 // This page alone is bigger than maxKeySize: save it by itself, since it will need to be
224 // split into multiple keys.
225
226 // Since this check implies the previous check on batchSize + newSize > maxSize, we should
227 // already have committed the current batch before writing this page.
228 assert(batch.fSize == 0);
229
230 std::uint64_t offset =
231 fWriter->WriteBlob(sealedPageIt->GetBuffer(), sealedPageIt->GetBufferSize(), bytesPacked);
233 locator.SetPosition(offset);
234 locator.SetNBytesOnStorage(sealedPageIt->GetDataSize());
235 locators.push_back(locator);
236
237 fCounters->fNPageCommitted.Inc();
238 fCounters->fSzWritePayload.Add(sealedPageIt->GetBufferSize());
239 fNBytesCurrentCluster += sealedPageIt->GetBufferSize();
240
241 } else {
242 batch.fSealedPages.emplace_back(&(*sealedPageIt));
243 batch.fSize += sealedPageIt->GetBufferSize();
244 batch.fBytesPacked += bytesPacked;
245 }
246 }
247 }
248
249 if (batch.fSize > 0) {
250 CommitBatchOfPages(batch, locators);
251 }
252
253 return locators;
254}
255
257{
258 auto result = fNBytesCurrentCluster;
259 fNBytesCurrentCluster = 0;
260 return result;
261}
262
265{
267 auto szPageListZip =
268 RNTupleCompressor::Zip(serializedPageList, length, GetWriteOptions().GetCompression(), bufPageListZip.get());
269
271 result.SetNBytesOnStorage(szPageListZip);
272 result.SetPosition(fWriter->WriteBlob(bufPageListZip.get(), szPageListZip, length));
273 return result;
274}
275
277{
278 // Add the streamer info records from streamer fields: because of runtime polymorphism we may need to add additional
279 // types not covered by the type names of the class fields
280 for (const auto &extraTypeInfo : fDescriptorBuilder.GetDescriptor().GetExtraTypeInfoIterable()) {
282 continue;
283 // Ideally, we would avoid deserializing the streamer info records of the streamer fields that we just serialized.
284 // However, this happens only once at the end of writing and only when streamer fields are used, so the
285 // preference here is for code simplicity.
286 fInfosOfClassFields.merge(RNTupleSerializer::DeserializeStreamerInfos(extraTypeInfo.GetContent()).Unwrap());
287 }
288 fWriter->UpdateStreamerInfos(fInfosOfClassFields);
289
291 auto szFooterZip =
292 RNTupleCompressor::Zip(serializedFooter, length, GetWriteOptions().GetCompression(), bufFooterZip.get());
293 fWriter->WriteNTupleFooter(bufFooterZip.get(), szFooterZip, length);
294 fWriter->Commit(GetWriteOptions().GetCompression());
295}
296
297////////////////////////////////////////////////////////////////////////////////
298
301 fClusterPool(
302 std::make_unique<RClusterPool>(*this, ROOT::Internal::RNTupleReadOptionsManip::GetClusterBunchSize(opts)))
303{
304 EnableDefaultMetrics("RPageSourceFile");
305}
306
308 std::unique_ptr<ROOT::Internal::RRawFile> file,
309 const ROOT::RNTupleReadOptions &options)
310 : RPageSourceFile(ntupleName, options)
311{
312 fFile = std::move(file);
315}
316
317ROOT::Internal::RPageSourceFile::RPageSourceFile(std::string_view ntupleName, std::string_view path,
318 const ROOT::RNTupleReadOptions &options)
319 : RPageSourceFile(ntupleName, ROOT::Internal::RRawFile::Create(path), options)
320{
321}
322
323std::unique_ptr<ROOT::Internal::RPageSourceFile>
325{
326 if (!anchor.fFile)
327 throw RException(R__FAIL("This RNTuple object was not streamed from a ROOT file (TFile or descendant)"));
328
329 std::unique_ptr<ROOT::Internal::RRawFile> rawFile;
330 // For local TFiles, TDavixFile, and TNetXNGFile, we want to open a new RRawFile to take advantage of the faster
331 // reading. We check the exact class name to avoid classes inheriting in ROOT (for example TMemFile) or in
332 // experiment frameworks.
333 std::string className = anchor.fFile->IsA()->GetName();
334 auto url = anchor.fFile->GetEndpointUrl();
335 auto protocol = std::string(url->GetProtocol());
336 if (className == "TFile") {
338 } else if (className == "TDavixFile" || className == "TNetXNGFile") {
340 } else {
342 }
343
344 auto pageSource = std::make_unique<RPageSourceFile>("", std::move(rawFile), options);
345 pageSource->fAnchor = anchor;
346 pageSource->fNTupleName = pageSource->fDescriptorBuilder.GetDescriptor().GetName();
347 return pageSource;
348}
349
351
353{
354 // If we constructed the page source with (ntuple name, path), we need to find the anchor first.
355 // Otherwise, the page source was created by OpenFromAnchor()
356 if (!fAnchor) {
357 fAnchor = fReader.GetNTuple(fNTupleName).Unwrap();
358 }
359 fReader.SetMaxKeySize(fAnchor->GetMaxKeySize());
360
361 fDescriptorBuilder.SetVersion(fAnchor->GetVersionEpoch(), fAnchor->GetVersionMajor(), fAnchor->GetVersionMinor(),
362 fAnchor->GetVersionPatch());
363 fDescriptorBuilder.SetOnDiskHeaderSize(fAnchor->GetNBytesHeader());
364 fDescriptorBuilder.AddToOnDiskFooterSize(fAnchor->GetNBytesFooter());
365
366 // Reserve enough space for the compressed and the uncompressed header/footer (see AttachImpl)
367 const auto bufSize = fAnchor->GetNBytesHeader() + fAnchor->GetNBytesFooter() +
368 std::max(fAnchor->GetLenHeader(), fAnchor->GetLenFooter());
369 fStructureBuffer.fBuffer = MakeUninitArray<unsigned char>(bufSize);
370 fStructureBuffer.fPtrHeader = fStructureBuffer.fBuffer.get();
371 fStructureBuffer.fPtrFooter = fStructureBuffer.fBuffer.get() + fAnchor->GetNBytesHeader();
372
373 auto readvLimits = fFile->GetReadVLimits();
374 // Never try to vectorize reads to a split key
375 readvLimits.fMaxSingleSize = std::min<size_t>(readvLimits.fMaxSingleSize, fAnchor->GetMaxKeySize());
376
377 if ((readvLimits.fMaxReqs < 2) ||
378 (std::max(fAnchor->GetNBytesHeader(), fAnchor->GetNBytesFooter()) > readvLimits.fMaxSingleSize) ||
379 (fAnchor->GetNBytesHeader() + fAnchor->GetNBytesFooter() > readvLimits.fMaxTotalSize)) {
380 RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
381 fReader.ReadBuffer(fStructureBuffer.fPtrHeader, fAnchor->GetNBytesHeader(), fAnchor->GetSeekHeader());
382 fReader.ReadBuffer(fStructureBuffer.fPtrFooter, fAnchor->GetNBytesFooter(), fAnchor->GetSeekFooter());
383 fCounters->fNRead.Add(2);
384 } else {
385 RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
386 R__ASSERT(fAnchor->GetNBytesHeader() < std::numeric_limits<std::size_t>::max());
387 R__ASSERT(fAnchor->GetNBytesFooter() < std::numeric_limits<std::size_t>::max());
388 ROOT::Internal::RRawFile::RIOVec readRequests[2] = {{fStructureBuffer.fPtrHeader, fAnchor->GetSeekHeader(),
389 static_cast<std::size_t>(fAnchor->GetNBytesHeader()), 0},
390 {fStructureBuffer.fPtrFooter, fAnchor->GetSeekFooter(),
391 static_cast<std::size_t>(fAnchor->GetNBytesFooter()), 0}};
392 fFile->ReadV(readRequests, 2);
393 fCounters->fNReadV.Inc();
394 }
395}
396
398{
399 auto unzipBuf = reinterpret_cast<unsigned char *>(fStructureBuffer.fPtrFooter) + fAnchor->GetNBytesFooter();
400
401 RNTupleDecompressor::Unzip(fStructureBuffer.fPtrHeader, fAnchor->GetNBytesHeader(), fAnchor->GetLenHeader(),
402 unzipBuf);
403 RNTupleSerializer::DeserializeHeader(unzipBuf, fAnchor->GetLenHeader(), fDescriptorBuilder);
404
405 RNTupleDecompressor::Unzip(fStructureBuffer.fPtrFooter, fAnchor->GetNBytesFooter(), fAnchor->GetLenFooter(),
406 unzipBuf);
407 RNTupleSerializer::DeserializeFooter(unzipBuf, fAnchor->GetLenFooter(), fDescriptorBuilder);
408
409 auto desc = fDescriptorBuilder.MoveDescriptor();
410
411 std::vector<unsigned char> buffer;
412 for (const auto &cgDesc : desc.GetClusterGroupIterable()) {
413 buffer.resize(std::max<size_t>(buffer.size(),
414 cgDesc.GetPageListLength() + cgDesc.GetPageListLocator().GetNBytesOnStorage()));
415 auto *zipBuffer = buffer.data() + cgDesc.GetPageListLength();
416 fReader.ReadBuffer(zipBuffer, cgDesc.GetPageListLocator().GetNBytesOnStorage(),
417 cgDesc.GetPageListLocator().GetPosition<std::uint64_t>());
418 RNTupleDecompressor::Unzip(zipBuffer, cgDesc.GetPageListLocator().GetNBytesOnStorage(),
419 cgDesc.GetPageListLength(), buffer.data());
420
421 RNTupleSerializer::DeserializePageList(buffer.data(), cgDesc.GetPageListLength(), cgDesc.GetId(), desc, mode);
422 }
423
424 // For the page reads, we rely on the I/O scheduler to define the read requests
425 fFile->SetBuffering(false);
426
427 return desc;
428}
429
432{
433 const auto clusterId = localIndex.GetClusterId();
434
436 {
437 auto descriptorGuard = GetSharedDescriptorGuard();
438 const auto &clusterDescriptor = descriptorGuard->GetClusterDescriptor(clusterId);
439 pageInfo = clusterDescriptor.GetPageRange(physicalColumnId).Find(localIndex.GetIndexInCluster());
440 }
441
442 sealedPage.SetBufferSize(pageInfo.GetLocator().GetNBytesOnStorage() + pageInfo.HasChecksum() * kNBytesPageChecksum);
443 sealedPage.SetNElements(pageInfo.GetNElements());
444 sealedPage.SetHasChecksum(pageInfo.HasChecksum());
445 if (!sealedPage.GetBuffer())
446 return;
447 if (pageInfo.GetLocator().GetType() != RNTupleLocator::kTypePageZero) {
448 fReader.ReadBuffer(const_cast<void *>(sealedPage.GetBuffer()), sealedPage.GetBufferSize(),
449 pageInfo.GetLocator().GetPosition<std::uint64_t>());
450 } else {
451 assert(!pageInfo.HasChecksum());
452 memcpy(const_cast<void *>(sealedPage.GetBuffer()), ROOT::Internal::RPage::GetPageZeroBuffer(),
453 sealedPage.GetBufferSize());
454 }
455
456 sealedPage.VerifyChecksumIfEnabled().ThrowOnError();
457}
458
462{
463 const auto columnId = columnHandle.fPhysicalId;
464 const auto clusterId = clusterInfo.fClusterId;
465 const auto pageInfo = clusterInfo.fPageInfo;
466
467 const auto element = columnHandle.fColumn->GetElement();
468 const auto elementSize = element->GetSize();
469 const auto elementInMemoryType = element->GetIdentifier().fInMemoryType;
470
471 if (pageInfo.GetLocator().GetType() == RNTupleLocator::kTypePageZero) {
472 auto pageZero = fPageAllocator->NewPage(elementSize, pageInfo.GetNElements());
473 pageZero.GrowUnchecked(pageInfo.GetNElements());
474 memset(pageZero.GetBuffer(), 0, pageZero.GetNBytes());
475 pageZero.SetWindow(clusterInfo.fColumnOffset + pageInfo.GetFirstElementIndex(),
477 return fPagePool.RegisterPage(std::move(pageZero), RPagePool::RKey{columnId, elementInMemoryType});
478 }
479
481 sealedPage.SetNElements(pageInfo.GetNElements());
482 sealedPage.SetHasChecksum(pageInfo.HasChecksum());
483 sealedPage.SetBufferSize(pageInfo.GetLocator().GetNBytesOnStorage() + pageInfo.HasChecksum() * kNBytesPageChecksum);
484 std::unique_ptr<unsigned char[]> directReadBuffer; // only used if cluster pool is turned off
485
486 if (fOptions.GetClusterCache() == ROOT::RNTupleReadOptions::EClusterCache::kOff) {
488 {
489 RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
490 fReader.ReadBuffer(directReadBuffer.get(), sealedPage.GetBufferSize(),
491 pageInfo.GetLocator().GetPosition<std::uint64_t>());
492 }
493 fCounters->fNPageRead.Inc();
494 fCounters->fNRead.Inc();
495 fCounters->fSzReadPayload.Add(sealedPage.GetBufferSize());
496 sealedPage.SetBuffer(directReadBuffer.get());
497 } else {
498 if (!fCurrentCluster || (fCurrentCluster->GetId() != clusterId) || !fCurrentCluster->ContainsColumn(columnId))
499 fCurrentCluster = fClusterPool->GetCluster(clusterId, fActivePhysicalColumns.ToColumnSet());
500 R__ASSERT(fCurrentCluster->ContainsColumn(columnId));
501
502 auto cachedPageRef =
504 if (!cachedPageRef.Get().IsNull())
505 return cachedPageRef;
506
507 ROnDiskPage::Key key(columnId, pageInfo.GetPageNumber());
508 auto onDiskPage = fCurrentCluster->GetOnDiskPage(key);
509 R__ASSERT(onDiskPage && (sealedPage.GetBufferSize() == onDiskPage->GetSize()));
510 sealedPage.SetBuffer(onDiskPage->GetAddress());
511 }
512
514 {
515 RNTupleAtomicTimer timer(fCounters->fTimeWallUnzip, fCounters->fTimeCpuUnzip);
516 newPage = UnsealPage(sealedPage, *element).Unwrap();
517 fCounters->fSzUnzip.Add(elementSize * pageInfo.GetNElements());
518 }
519
520 newPage.SetWindow(clusterInfo.fColumnOffset + pageInfo.GetFirstElementIndex(),
522 fCounters->fNPageUnsealed.Inc();
523 return fPagePool.RegisterPage(std::move(newPage), RPagePool::RKey{columnId, elementInMemoryType});
524}
525
526std::unique_ptr<ROOT::Internal::RPageSource> ROOT::Internal::RPageSourceFile::CloneImpl() const
527{
528 auto clone = new RPageSourceFile(fNTupleName, fOptions);
529 clone->fFile = fFile->Clone();
530 clone->fReader = ROOT::Internal::RMiniFileReader(clone->fFile.get());
531 return std::unique_ptr<RPageSourceFile>(clone);
532}
533
534std::unique_ptr<ROOT::Internal::RCluster>
536 std::vector<ROOT::Internal::RRawFile::RIOVec> &readRequests)
537{
538 struct ROnDiskPageLocator {
539 ROOT::DescriptorId_t fColumnId = 0;
540 ROOT::NTupleSize_t fPageNo = 0;
541 std::uint64_t fOffset = 0;
542 std::uint64_t fSize = 0;
543 std::size_t fBufPos = 0;
544 };
545
546 std::vector<ROnDiskPageLocator> onDiskPages;
547 auto activeSize = 0;
548 auto pageZeroMap = std::make_unique<ROnDiskPageMap>();
549 PrepareLoadCluster(clusterKey, *pageZeroMap,
552 const auto &pageLocator = pageInfo.GetLocator();
554 throw RException(R__FAIL("tried to read a page with an unknown locator"));
555 const auto nBytes =
556 pageLocator.GetNBytesOnStorage() + pageInfo.HasChecksum() * kNBytesPageChecksum;
558 onDiskPages.push_back(
559 {physicalColumnId, pageNo, pageLocator.GetPosition<std::uint64_t>(), nBytes, 0});
560 });
561
562 // Linearize the page requests by file offset
563 std::sort(onDiskPages.begin(), onDiskPages.end(),
564 [](const ROnDiskPageLocator &a, const ROnDiskPageLocator &b) { return a.fOffset < b.fOffset; });
565
566 // In order to coalesce close-by pages, we collect the sizes of the gaps between pages on disk. We then order
567 // the gaps by size, sum them up and find a cutoff for the largest gap that we tolerate when coalescing pages.
568 // The size of the cutoff is given by the fraction of extra bytes we are willing to read in order to reduce
569 // the number of read requests. We thus schedule the lowest number of requests given a tolerable fraction
570 // of extra bytes.
571 // TODO(jblomer): Eventually we may want to select the parameter at runtime according to link latency and speed,
572 // memory consumption, device block size.
573 float maxOverhead = 0.25 * float(activeSize);
574 std::vector<std::size_t> gaps;
575 if (onDiskPages.size())
576 gaps.reserve(onDiskPages.size() - 1);
577 for (unsigned i = 1; i < onDiskPages.size(); ++i) {
578 std::int64_t gap =
579 static_cast<int64_t>(onDiskPages[i].fOffset) - (onDiskPages[i - 1].fSize + onDiskPages[i - 1].fOffset);
580 gaps.emplace_back(std::max(gap, std::int64_t(0)));
581 // If the pages overlap, substract the overlapped bytes from `activeSize`
582 activeSize += std::min(gap, std::int64_t(0));
583 }
584 std::sort(gaps.begin(), gaps.end());
585 std::size_t gapCut = 0;
586 std::size_t currentGap = 0;
587 float szExtra = 0.0;
588 for (auto g : gaps) {
589 if (g != currentGap) {
591 currentGap = g;
592 }
593 szExtra += g;
594 if (szExtra > maxOverhead)
595 break;
596 }
597
598 // In a first step, we coalesce the read requests and calculate the cluster buffer size.
599 // In a second step, we'll fix-up the memory destinations for the read calls given the
600 // address of the allocated buffer. We must not touch, however, the read requests from previous
601 // calls to PrepareSingleCluster()
602 const auto currentReadRequestIdx = readRequests.size();
603
605 // To simplify the first loop iteration, pretend an empty request starting at the first page's fOffset.
606 if (!onDiskPages.empty())
607 req.fOffset = onDiskPages[0].fOffset;
608 std::size_t szPayload = 0;
609 std::size_t szOverhead = 0;
610 const std::uint64_t maxKeySize = fReader.GetMaxKeySize();
611 for (auto &s : onDiskPages) {
612 R__ASSERT(s.fSize > 0);
613 const std::int64_t readUpTo = req.fOffset + req.fSize;
614 // Note: byte ranges of pages may overlap
615 const std::uint64_t overhead = std::max(static_cast<std::int64_t>(s.fOffset) - readUpTo, std::int64_t(0));
616 const std::uint64_t extent = std::max(static_cast<std::int64_t>(s.fOffset + s.fSize) - readUpTo, std::int64_t(0));
617 if (req.fSize + extent < maxKeySize && overhead <= gapCut) {
620 s.fBufPos = reinterpret_cast<intptr_t>(req.fBuffer) + s.fOffset - req.fOffset;
621 req.fSize += extent;
622 continue;
623 }
624
625 // close the current request and open new one
626 if (req.fSize > 0)
627 readRequests.emplace_back(req);
628
629 req.fBuffer = reinterpret_cast<unsigned char *>(req.fBuffer) + req.fSize;
630 s.fBufPos = reinterpret_cast<intptr_t>(req.fBuffer);
631
632 szPayload += s.fSize;
633 req.fOffset = s.fOffset;
634 req.fSize = s.fSize;
635 }
636 readRequests.emplace_back(req);
637 fCounters->fSzReadPayload.Add(szPayload);
638 fCounters->fSzReadOverhead.Add(szOverhead);
639
640 // Register the on disk pages in a page map
641 auto buffer = new unsigned char[reinterpret_cast<intptr_t>(req.fBuffer) + req.fSize];
642 auto pageMap = std::make_unique<ROOT::Internal::ROnDiskPageMapHeap>(std::unique_ptr<unsigned char[]>(buffer));
643 for (const auto &s : onDiskPages) {
644 ROnDiskPage::Key key(s.fColumnId, s.fPageNo);
645 pageMap->Register(key, ROnDiskPage(buffer + s.fBufPos, s.fSize));
646 }
647 fCounters->fNPageRead.Add(onDiskPages.size());
648 for (auto i = currentReadRequestIdx; i < readRequests.size(); ++i) {
649 readRequests[i].fBuffer = buffer + reinterpret_cast<intptr_t>(readRequests[i].fBuffer);
650 }
651
652 auto cluster = std::make_unique<RCluster>(clusterKey.fClusterId);
653 cluster->Adopt(std::move(pageMap));
654 cluster->Adopt(std::move(pageZeroMap));
655 for (auto colId : clusterKey.fPhysicalColumnSet)
656 cluster->SetColumnAvailable(colId);
657 return cluster;
658}
659
660std::vector<std::unique_ptr<ROOT::Internal::RCluster>>
662{
663 fCounters->fNClusterLoaded.Add(clusterKeys.size());
664
665 std::vector<std::unique_ptr<ROOT::Internal::RCluster>> clusters;
666 std::vector<ROOT::Internal::RRawFile::RIOVec> readRequests;
667
668 clusters.reserve(clusterKeys.size());
669 for (auto key : clusterKeys) {
670 clusters.emplace_back(PrepareSingleCluster(key, readRequests));
671 }
672
673 auto nReqs = readRequests.size();
674 auto readvLimits = fFile->GetReadVLimits();
675 // We never want to do vectorized reads of split blobs, so we limit our single size to maxKeySize.
676 readvLimits.fMaxSingleSize = std::min<size_t>(readvLimits.fMaxSingleSize, fReader.GetMaxKeySize());
677
678 int iReq = 0;
679 while (nReqs > 0) {
680 auto nBatch = std::min(nReqs, readvLimits.fMaxReqs);
681
682 if (readvLimits.HasSizeLimit()) {
683 std::uint64_t totalSize = 0;
684 for (std::size_t i = 0; i < nBatch; ++i) {
685 if (readRequests[iReq + i].fSize > readvLimits.fMaxSingleSize) {
686 nBatch = i;
687 break;
688 }
689
690 totalSize += readRequests[iReq + i].fSize;
691 if (totalSize > readvLimits.fMaxTotalSize) {
692 nBatch = i;
693 break;
694 }
695 }
696 }
697
698 if (nBatch <= 1) {
699 nBatch = 1;
700 RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
701 fReader.ReadBuffer(readRequests[iReq].fBuffer, readRequests[iReq].fSize, readRequests[iReq].fOffset);
702 } else {
703 RNTupleAtomicTimer timer(fCounters->fTimeWallRead, fCounters->fTimeCpuRead);
704 fFile->ReadV(&readRequests[iReq], nBatch);
705 }
706 fCounters->fNReadV.Inc();
707 fCounters->fNRead.Add(nBatch);
708
709 iReq += nBatch;
710 nReqs -= nBatch;
711 }
712
713 return clusters;
714}
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:299
#define b(i)
Definition RSha256.hxx:100
#define g(i)
Definition RSha256.hxx:105
#define a(i)
Definition RSha256.hxx:99
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:125
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
Option_t Option_t TPoint TPoint const char mode
Managed a set of clusters containing compressed and packed pages.
An in-memory subset of the packed and compressed pages of a cluster.
Definition RCluster.hxx:148
Read RNTuple data blocks from a TFile container, provided by a RRawFile.
Definition RMiniFile.hxx:55
Helper class to compress data blocks in the ROOT compression frame format.
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.
Helper class to uncompress data blocks in the ROOT compression frame format.
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 > 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 std::unique_ptr< RNTupleFileWriter > Append(std::string_view ntupleName, TDirectory &fileOrDirectory, std::uint64_t maxKeySize)
The directory parameter can also be a TFile object (TFile inherits from TDirectory).
A helper class for serializing and deserialization of the RNTuple binary format.
static RResult< void > DeserializePageList(const void *buffer, std::uint64_t bufSize, ROOT::DescriptorId_t clusterGroupId, RNTupleDescriptor &desc, EDescriptorDeserializeMode mode)
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:99
A page as being stored on disk, that is packed and compressed.
Definition RCluster.hxx:41
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.
A thread-safe cache of pages loaded from the page source.
Definition RPagePool.hxx:44
Reference to a page stored in the page pool.
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::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 CommitPageImpl(ColumnHandle_t columnHandle, const RPage &page) override
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...
RNTupleLocator CommitSealedPageImpl(ROOT::DescriptorId_t physicalColumnId, const RPageStorage::RSealedPage &sealedPage) 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.
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 ...
RPageRef LoadPageImpl(ColumnHandle_t columnHandle, const RClusterInfo &clusterInfo, ROOT::NTupleSize_t idxInCluster) final
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.
ROOT::RNTupleDescriptor AttachImpl(RNTupleSerializer::EDescriptorDeserializeMode mode) final
LoadStructureImpl() has been called before AttachImpl() is called
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...
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...
std::unique_ptr< RRawFile > fFile
An RRawFile is used to request the necessary byte ranges from a local or a remote file.
ROOT::Internal::RMiniFileReader fReader
Takes the fFile to read ntuple blobs from it.
void LoadSealedPage(ROOT::DescriptorId_t physicalColumnId, RNTupleLocalIndex localIndex, RSealedPage &sealedPage) final
Read the packed and compressed bytes of a page into the memory buffer provided by sealedPage.
Abstract interface to read data from an ntuple.
void EnableDefaultMetrics(const std::string &prefix)
Enables the default set of metrics provided by RPageSource.
Stores information about the cluster in which this page resides.
Definition RPage.hxx:53
A page is a slice of a column that is mapped into memory.
Definition RPage.hxx:44
static const void * GetPageZeroBuffer()
Return a pointer to the page zero buffer used if there is no on-disk data for a particular deferred c...
Definition RPage.cxx:23
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:64
The field for a class with dictionary.
Definition RField.hxx:111
Base class for all ROOT issued exceptions.
Definition RError.hxx:79
A field translates read and write calls from/to underlying columns to/from tree values.
The on-storage metadata of an RNTuple.
Addresses a column element or field item relative to a particular cluster, instead of a global NTuple...
Generic information about the physical location of data.
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:65
const_iterator begin() const
const_iterator end() const
The field for a class using ROOT standard streaming.
Definition RField.hxx:206
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:4727
Describe directory structure in memory.
Definition TDirectory.h:45
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
std::unique_ptr< T[]> MakeUninitArray(std::size_t size)
Make an array of default-initialized elements.
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
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:152
The incremental changes to a RNTupleModel
On-disk pages within a page source are identified by the column and page number.
Definition RCluster.hxx:51
Summarizes cluster-level information that are necessary to load a certain page.
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
Information about a single page in the context of a cluster's page range.