Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RPageStorage.cxx
Go to the documentation of this file.
1/// \file RPageStorage.cxx
2/// \author Jakob Blomer <jblomer@cern.ch>
3/// \date 2018-10-04
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/RPageStorage.hxx>
15#include <ROOT/RColumn.hxx>
16#include <ROOT/RFieldBase.hxx>
20#include <ROOT/RNTupleModel.hxx>
22#include <ROOT/RNTupleUtils.hxx>
23#include <ROOT/RNTupleZip.hxx>
25#include <ROOT/RPageSinkBuf.hxx>
26#include <ROOT/StringUtils.hxx>
27#ifdef R__ENABLE_DAOS
29#endif
30#ifdef R__ENABLE_S3
32#endif
33
34#include <Compression.h>
35#include <TError.h>
36
37#include <algorithm>
38#include <atomic>
39#include <cassert>
40#include <cstring>
41#include <functional>
42#include <memory>
43#include <string_view>
44#include <unordered_map>
45#include <utility>
46
53
55
59
65
68{
69 auto [itr, _] = fColumnInfos.emplace(physicalColumnId, std::vector<RColumnInfo>());
70 for (auto &columnInfo : itr->second) {
71 if (columnInfo.fElementId == elementId) {
72 columnInfo.fRefCounter++;
73 return;
74 }
75 }
76 itr->second.emplace_back(RColumnInfo{elementId, 1});
77}
78
81{
82 auto itr = fColumnInfos.find(physicalColumnId);
83 R__ASSERT(itr != fColumnInfos.end());
84 for (std::size_t i = 0; i < itr->second.size(); ++i) {
85 if (itr->second[i].fElementId != elementId)
86 continue;
87
88 itr->second[i].fRefCounter--;
89 if (itr->second[i].fRefCounter == 0) {
90 itr->second.erase(itr->second.begin() + i);
91 if (itr->second.empty()) {
92 fColumnInfos.erase(itr);
93 }
94 }
95 break;
96 }
97}
98
100{
102 for (const auto &[physicalColumnId, _] : fColumnInfos)
103 result.insert(physicalColumnId);
104 return result;
105}
106
108{
109 if (fFirstEntry == ROOT::kInvalidNTupleIndex) {
110 /// Entry range unset, we assume that the entry range covers the complete source
111 return true;
112 }
113
114 if (clusterDesc.GetNEntries() == 0)
115 return true;
116 if ((clusterDesc.GetFirstEntryIndex() + clusterDesc.GetNEntries()) <= fFirstEntry)
117 return false;
118 if (clusterDesc.GetFirstEntryIndex() >= (fFirstEntry + fNEntries))
119 return false;
120 return true;
121}
122
124 : fClusterPool(*this, ROOT::Internal::RNTupleReadOptionsManip::GetClusterBunchSize(options)),
125 fPagePool(*this),
127 fOptions(options),
128 fMetrics("")
129{
130}
131
133
134std::unique_ptr<ROOT::Internal::RPageSource>
135ROOT::Internal::RPageSource::Create(std::string_view ntupleName, std::string_view location,
136 const ROOT::RNTupleReadOptions &options)
137{
138 if (ntupleName.empty()) {
139 throw RException(R__FAIL("empty RNTuple name"));
140 }
141 if (location.empty()) {
142 throw RException(R__FAIL("empty storage location"));
143 }
144 if (location.find("daos://") == 0)
145#ifdef R__ENABLE_DAOS
146 return std::make_unique<ROOT::Experimental::Internal::RPageSourceDaos>(ntupleName, location, options);
147#else
148 throw RException(R__FAIL("This RNTuple build does not support DAOS."));
149#endif
150
151 if (ROOT::StartsWith(location, "ntpl+s3+http://") || ROOT::StartsWith(location, "ntpl+s3+https://")) {
152#ifdef R__ENABLE_S3
153 return std::make_unique<ROOT::Experimental::Internal::RPageSourceS3>(ntupleName, location, options);
154#else
155 throw RException(R__FAIL("This RNTuple build does not support S3. Rebuild ROOT with the 'curl' "
156 "cmake option enabled (-Dcurl=ON) to enable the S3 backend."));
157#endif
158 }
159
160 return std::make_unique<ROOT::Internal::RPageSourceFile>(ntupleName, location, options);
161}
162
164{
166 auto physicalId =
167 GetSharedDescriptorGuard()->FindPhysicalColumnId(fieldId, column.GetIndex(), column.GetRepresentationIndex());
169 fActivePhysicalColumns.Insert(physicalId, column.GetElement()->GetIdentifier());
170 return physicalId;
171}
172
174{
175 fActivePhysicalColumns.Erase(column.GetOnDiskId(), column.GetElement()->GetIdentifier());
176}
177
179{
180 if ((range.fFirstEntry + range.fNEntries) > GetNEntries()) {
181 throw RException(R__FAIL("invalid entry range"));
182 }
183 fEntryRange = range;
184}
185
187{
188 if (!fHasStructure)
189 LoadStructureImpl();
190 fHasStructure = true;
191}
192
194{
195 if (fIsAttached)
196 return;
197
198 fDeserializationMode = mode;
199
200 LoadStructure();
201
202 {
203 auto descGuard = GetExclDescriptorGuard();
204 descGuard.MoveIn(AttachImpl());
205 fStructureBuffer.Reset();
206
207 NTupleSize_t sumClusterCount = 0;
208 fCumulativeClusterCounts.reserve(descGuard->GetNClusterGroups());
209 for (const auto &cgDesc : descGuard->GetClusterGroupIterable()) {
210 sumClusterCount += cgDesc.GetNClusters();
211 fCumulativeClusterCounts.emplace_back(sumClusterCount);
212 }
213 }
214
215 if (fOptions.GetMetadataMode() == RNTupleReadOptions::EMetadataMode::kEager)
216 LoadAllPageLists();
217
218 fIsAttached = true;
219}
220
222{
223 auto descGuard = GetExclDescriptorGuard();
224
225 for (const auto &cgDesc : descGuard->GetClusterGroupIterable()) {
226 LoadPageList(cgDesc.GetId(), descGuard);
227 }
228 // By clearing the access sequence with all page lists loaded, we make EnsureClusterDetails() always take the
229 // fast path that doesn't try further maintaining the list.
230 fClusterGroupAccessSequence.clear();
231}
232
234{
235 const auto &cgDesc = exclGuard->GetClusterGroupDescriptor(clusterGroupId);
236 if (cgDesc.HasClusterDetails())
237 return;
238
239 auto buffer =
240 MakeUninitArray<unsigned char>(cgDesc.GetPageListLength() + cgDesc.GetPageListLocator().GetNBytesOnStorage());
241 auto zipBuffer = buffer.get() + cgDesc.GetPageListLength();
242 LoadPageListImpl(cgDesc.GetPageListLocator(), zipBuffer);
243 RNTupleDecompressor::Unzip(zipBuffer, cgDesc.GetPageListLocator().GetNBytesOnStorage(), cgDesc.GetPageListLength(),
244 buffer.get());
245 RNTupleSerializer::DeserializePageList(buffer.get(), cgDesc.GetPageListLength(), cgDesc.GetId(), *exclGuard,
246 fDeserializationMode);
247}
248
249std::unique_ptr<ROOT::Internal::RPageSource> ROOT::Internal::RPageSource::Clone() const
250{
251 auto clone = CloneImpl();
252 if (fIsAttached) {
253 clone->GetExclDescriptorGuard().MoveIn(GetSharedDescriptorGuard()->Clone());
254 clone->fHasStructure = true;
255 clone->fIsAttached = true;
256 clone->fDeserializationMode = fDeserializationMode;
257 clone->fCumulativeClusterCounts = fCumulativeClusterCounts;
258 }
259 return clone;
260}
261
264{
265 assert(descGuard.IsValid());
266 if (cgId == kInvalidDescriptorId)
267 return descGuard;
268
269 // After LoadAllPages(), itrSeq == fClusterGroupAccessSequence.begin() == fClusterGroupAccessSequence.end()
270 auto itrSeq = std::find(fClusterGroupAccessSequence.begin(), fClusterGroupAccessSequence.end(), cgId);
271
272 if (descGuard->GetClusterGroupDescriptor(cgId).HasClusterDetails() &&
273 (itrSeq == fClusterGroupAccessSequence.begin())) {
274 return descGuard;
275 }
276
277 descGuard.Release();
278
279 auto exclGuard = GetExclDescriptorGuard();
280
281 itrSeq = std::find(fClusterGroupAccessSequence.begin(), fClusterGroupAccessSequence.end(), cgId);
282
283 if (exclGuard->GetClusterGroupDescriptor(cgId).HasClusterDetails()) {
284 // Either between releasing the shared guard and acquiring the exclusive guard the cluster group details appeared
285 // or the cluster group details were present initially but we need to update the access sequence.
286 assert(itrSeq != fClusterGroupAccessSequence.end());
287 fClusterGroupAccessSequence.erase(itrSeq);
288 fClusterGroupAccessSequence.push_front(cgId);
289 return exclGuard;
290 }
291
292 assert(itrSeq == fClusterGroupAccessSequence.end());
293 const auto nClusterGroups = fClusterGroupAccessSequence.size();
294 const auto clusterGroupBudget = Internal::RNTupleReadOptionsManip::GetClusterGroupBudget(fOptions);
295 assert(clusterGroupBudget > 0);
296 if ((nClusterGroups >= clusterGroupBudget) && (nClusterGroups > fPinnedClusterGroups.size())) {
297 // Remove as many cluster group details as necessary to allow for adding one more and still staying within
298 // the budget. Take into account, however, that pinned cluster groups cannot be removed.
299 auto nRemove = std::min(nClusterGroups - fPinnedClusterGroups.size(), nClusterGroups - clusterGroupBudget + 1);
300 // We iterate from the back to the front of the list, in reverse order of last access (i.e.: starting from the
301 // least recently used), and we skip pinned cluster groups.
302 for (auto lru = fClusterGroupAccessSequence.rbegin(); nRemove > 0;) {
303 if (fPinnedClusterGroups.count(*lru) > 0) {
304 ++lru;
305 continue;
306 }
307 exclGuard->DropClusterGroupDetails(*lru);
308 // The forward iterator corresponding to the reverse iterator lru is prev(lru.base).
309 // After removal, next points to the element following the removed one. All other iterators are invalid.
310 auto next = fClusterGroupAccessSequence.erase(std::prev(lru.base()));
311 // make_reverse_iterator brings lru back to the element before the removed one
312 lru = std::make_reverse_iterator(next);
313 nRemove--;
314 };
315 assert(fClusterGroupAccessSequence.size() > 0);
316 }
317 fClusterGroupAccessSequence.push_front(cgId);
318
319 LoadPageList(cgId, exclGuard);
320
321 return exclGuard;
322}
323
325{
326 // We use `cluster + 1` because fCumulativeClusterCounts stores the cumulative _number_ of clusters and not
327 // the last cluster IDs.
328 auto iter = std::lower_bound(fCumulativeClusterCounts.begin(), fCumulativeClusterCounts.end(), clusterId + 1);
329 if (iter == fCumulativeClusterCounts.end())
331 return std::distance(fCumulativeClusterCounts.begin(), iter);
332}
333
335{
336 return GetSharedDescriptorGuard()->GetNEntries();
337}
338
340{
341 auto sharedGuard = GetSharedDescriptorGuard();
342 if (sharedGuard->GetNClusters() == 0)
343 return 0;
344
345 const auto lastClusterGroupId = sharedGuard->GetNClusterGroups() - 1;
346 auto descGuard = EnsureClusterDetails(lastClusterGroupId, std::move(sharedGuard));
347
348 const auto &cgDesc = descGuard->GetClusterGroupDescriptor(lastClusterGroupId);
349 const auto &cd = descGuard->GetClusterDescriptor(cgDesc.GetClusterIds().back());
350 R__ASSERT(cd.ContainsColumn(physicalColumnId));
351
352 const auto &columnRange = cd.GetColumnRange(physicalColumnId);
353 return columnRange.GetFirstElementIndex() + columnRange.GetNElements();
354}
355
357{
358 fPinnedClusters.insert(clusterId);
359 ++fPinnedClusterGroups[FindClusterGroupId(clusterId)];
360}
361
363{
364 fPinnedClusters.erase(clusterId);
365 auto itr = fPinnedClusterGroups.find(FindClusterGroupId(clusterId));
366 assert(itr != fPinnedClusterGroups.end() && itr->second > 0);
367 if (--itr->second == 0)
368 fPinnedClusterGroups.erase(itr);
369}
370
373{
374 // At the cost of an additional cluster descriptor lock, we could use a more general approach that looks for the
375 // cluster containing the entry index after the last entry of the current cluster.
376 // At the moment, however, we know that cluster IDs are consecutive and clusters are not sharded.
377 auto sharedGuard = GetSharedDescriptorGuard();
378 assert(clusterId < sharedGuard->GetNClusters());
379 nextId = clusterId + 1;
380 if (nextId == sharedGuard->GetNClusters()) {
381 nextId = kInvalidDescriptorId;
382 return sharedGuard;
383 }
384 return EnsureClusterDetails(FindClusterGroupId(nextId), std::move(sharedGuard));
385}
386
389{
391 RAnyDescriptorGuard descGuard = GetSharedDescriptorGuard();
392
393 if (descGuard->GetNClusterGroups() == 0)
394 return descGuard;
395
396 // Binary search in the cluster group list, followed by a binary search in the clusters of that cluster group
397
398 const auto cgIter = descGuard->GetClusterGroupIterable().begin();
399 std::size_t cgLeft = 0;
400 std::size_t cgRight = descGuard->GetNClusterGroups() - 1;
401 while (cgLeft <= cgRight) {
402 const std::size_t cgMidpoint = (cgLeft + cgRight) / 2;
403 const auto &cgDesc = *(cgIter + cgMidpoint);
404
405 if (cgDesc.GetMinEntry() > entryIdx) {
406 R__ASSERT(cgMidpoint > 0);
407 cgRight = cgMidpoint - 1;
408 continue;
409 }
410
411 if (cgDesc.GetMinEntry() + cgDesc.GetEntrySpan() <= entryIdx) {
412 cgLeft = cgMidpoint + 1;
413 continue;
414 }
415
416 // Binary search in the current cluster group; since we already checked the element range boundaries,
417 // the element must be in that cluster group.
418 const auto tgtClusterGroupId = cgDesc.GetId();
419 descGuard = EnsureClusterDetails(tgtClusterGroupId, std::move(descGuard));
420
421 const auto &clusterIds = descGuard->GetClusterGroupDescriptor(tgtClusterGroupId).GetClusterIds();
422 std::size_t clusterLeft = 0;
423 std::size_t clusterRight = clusterIds.size() - 1;
424 while (clusterLeft <= clusterRight) {
425 const std::size_t clusterMidpoint = (clusterLeft + clusterRight) / 2;
426 const auto &clusterDesc = descGuard->GetClusterDescriptor(clusterIds[clusterMidpoint]);
427
428 if (clusterDesc.GetFirstEntryIndex() > entryIdx) {
429 R__ASSERT(clusterMidpoint > 0);
430 clusterRight = clusterMidpoint - 1;
431 continue;
432 }
433
434 if (clusterDesc.GetFirstEntryIndex() + clusterDesc.GetNEntries() <= entryIdx) {
435 clusterLeft = clusterMidpoint + 1;
436 continue;
437 }
438
439 cid = clusterIds[clusterMidpoint];
440 return descGuard;
441 }
442 R__ASSERT(false);
443 }
444 return descGuard;
445}
446
447namespace {
448
449// Searches the index of a column in a certain cluster group. If the column index is found, returns the list
450// of cluster IDs in that group. Otherwise, increment or decrement the given clusterGroupId to indicate to which
451// side of the cluster groups the search should continue.
452const std::vector<ROOT::DescriptorId_t> *
453SearchInClusterGroup(ROOT::DescriptorId_t physicalColumnId, ROOT::NTupleSize_t index,
455{
456 const auto &clusterIds = descGuard->GetClusterGroupDescriptor(clusterGroupId).GetClusterIds();
457 R__ASSERT(!clusterIds.empty());
458
459 const auto &firstColumnRange = descGuard->GetClusterDescriptor(clusterIds.front()).GetColumnRange(physicalColumnId);
460 if (firstColumnRange.GetFirstElementIndex() > index) {
461 // Look into previous cluster groups
462 R__ASSERT(clusterGroupId > 0);
463 clusterGroupId--;
464 return nullptr;
465 }
466
467 const auto &lastColumnRange = descGuard->GetClusterDescriptor(clusterIds.back()).GetColumnRange(physicalColumnId);
468 if ((lastColumnRange.GetFirstElementIndex() + lastColumnRange.GetNElements()) <= index) {
469 // Look into the following cluster groups (if applicable)
470 if (++clusterGroupId == descGuard->GetNClusterGroups())
471 clusterGroupId = ROOT::kInvalidDescriptorId;
472 return nullptr;
473 }
474
475 return &clusterIds;
476}
477
478// Binary search in the sorted list clusterIdList. The caller has to ensure that the index of the given column
479// is in fact in the list of provided cluster IDs.
480ROOT::DescriptorId_t FindClusterIdInList(ROOT::DescriptorId_t physicalColumnId, ROOT::NTupleSize_t index,
481 const std::vector<ROOT::DescriptorId_t> &clusterIds,
483{
484 std::size_t clusterLeft = 0;
485 std::size_t clusterRight = clusterIds.size() - 1;
486 while (clusterLeft <= clusterRight) {
487 const std::size_t clusterMidpoint = (clusterLeft + clusterRight) / 2;
488 const auto clusterId = clusterIds[clusterMidpoint];
489 const auto &columnRange = descGuard->GetClusterDescriptor(clusterId).GetColumnRange(physicalColumnId);
490
491 if (columnRange.Contains(index)) {
492 return clusterId;
493 }
494
495 if (columnRange.GetFirstElementIndex() > index) {
496 R__ASSERT(clusterMidpoint > 0);
497 clusterRight = clusterMidpoint - 1;
498 continue;
499 }
500
501 if (columnRange.GetFirstElementIndex() + columnRange.GetNElements() <= index) {
502 clusterLeft = clusterMidpoint + 1;
503 continue;
504 }
505 }
506
507 R__ASSERT(false);
509}
510
511} // anonymous namespace
512
515{
517 RAnyDescriptorGuard descGuard = GetSharedDescriptorGuard();
518
519 if (descGuard->GetNClusterGroups() == 0)
520 return descGuard;
521
522 // Shortcuts: most cases do not require a full binary search in the list of cluster groups.
523
524 // Case 1: look around the last used cluster
525 const std::vector<DescriptorId_t> *clusterIds = nullptr;
526 const DescriptorId_t cgGuess =
527 ((index == 0) || (fLastUsedCluster == kInvalidDescriptorId)) ? 0 : FindClusterGroupId(fLastUsedCluster);
528 DescriptorId_t cgHint = cgGuess;
529 // Try twice: if the column index is not found in the cluster group of the last used cluster, cgHint will point
530 // to the adjacent cluster group either preceeding or following the cluster group and we'll try again.
531 for (int i = 0; i < 2; ++i) {
532 descGuard = EnsureClusterDetails(cgHint, std::move(descGuard));
533 if ((clusterIds = SearchInClusterGroup(physicalColumnId, index, cgHint, descGuard))) {
534 cid = FindClusterIdInList(physicalColumnId, index, *clusterIds, descGuard);
535 return descGuard;
536 }
537 if (cgHint == kInvalidDescriptorId)
538 return descGuard;
539 }
540 assert(cgHint != cgGuess);
541
542 // Case 2: look into the pinned cluster groups
543 // We expect only few pinned cluster groups, so we do a linear search with pruning
544 const bool isRightSided = cgHint > cgGuess; // whether to look to the right or to the left of cgHint (cgGuess)
545 for (auto [cgPinned, _] : fPinnedClusterGroups) {
546 if (isRightSided && (cgPinned < cgHint)) {
547 // Skip the left side of pinned cluster groups if we already know the column index cannot be here
548 continue;
549 } else if (!isRightSided && (cgPinned > cgHint)) {
550 // Prune the search on the right side of pinned cluster groups
551 break;
552 }
553
554 descGuard = EnsureClusterDetails(cgPinned, std::move(descGuard));
555 cgHint = cgPinned;
556 if ((clusterIds = SearchInClusterGroup(physicalColumnId, index, cgHint, descGuard))) {
557 cid = FindClusterIdInList(physicalColumnId, index, *clusterIds, descGuard);
558 return descGuard;
559 }
560
561 if (cgHint < cgPinned) {
562 // No point in moving further to the right of the pinned cluster groups
563 break;
564 }
565 }
566
567 // Case 3: top-level columns can use the entry-based search
568 const auto &columnDesc = descGuard->GetColumnDescriptor(physicalColumnId);
569 if (columnDesc.GetIndex() == 0) {
570 // Start search with the parent field of the current column
571 auto fieldId = descGuard->GetFieldDescriptor(columnDesc.GetFieldId()).GetParentId();
572 while (fieldId != descGuard->GetFieldZeroId()) {
573 const auto &fieldDesc = descGuard->GetFieldDescriptor(fieldId);
574 if ((fieldDesc.GetStructure() != ENTupleStructure::kPlain) &&
575 (fieldDesc.GetStructure() != ENTupleStructure::kRecord)) {
576 break;
577 }
578 fieldId = fieldDesc.GetParentId();
579 }
580 if (fieldId == descGuard->GetFieldZeroId()) {
581 descGuard.Release();
582 return FindClusterId(index, cid);
583 }
584 }
585
586 // Binary search in the cluster group list, followed by a binary search in the clusters of that cluster group
587 // We could use the information from the shortcut search to restrict the left and right borders further.
588 // Left out for simplicity.
589
590 std::size_t cgLeft = 0;
591 std::size_t cgRight = descGuard->GetNClusterGroups() - 1;
592 while (cgLeft <= cgRight) {
593 const std::size_t cgMidpoint = (cgLeft + cgRight) / 2;
594 descGuard = EnsureClusterDetails(cgMidpoint, std::move(descGuard));
595
596 cgHint = cgMidpoint;
597 clusterIds = SearchInClusterGroup(physicalColumnId, index, cgHint, descGuard);
598
599 if (clusterIds) {
600 cid = FindClusterIdInList(physicalColumnId, index, *clusterIds, descGuard);
601 break;
602 }
603
604 if (cgHint == ROOT::kInvalidDescriptorId) {
605 break;
606 } else if (cgHint < cgMidpoint) {
607 // Look into the lower half of cluster groups
608 cgRight = cgMidpoint - 1;
609 } else {
610 // Look into the upper half of cluster groups
611 cgLeft = cgMidpoint + 1;
612 }
613 }
614 return descGuard;
615}
616
618{
619 if (!fTaskScheduler)
620 return;
621
622 RNTupleAtomicTimer timer(fCounters->fTimeWallUnzip, fCounters->fTimeCpuUnzip);
623
624 const auto clusterId = cluster->GetId();
625 auto descriptorGuard = EnsureClusterDetails(FindClusterGroupId(clusterId), GetSharedDescriptorGuard());
626 const auto &clusterDescriptor = descriptorGuard->GetClusterDescriptor(clusterId);
627
628 fPreloadedClusters[clusterDescriptor.GetFirstEntryIndex()] = clusterId;
629
630 std::atomic<bool> foundChecksumFailure{false};
631
632 const auto &columnsInCluster = cluster->GetAvailPhysicalColumns();
633
634 std::vector<std::pair<Internal::RPage, Internal::RPagePool::RKey>> allPages;
635 // We allocate the space for all the pages upfront so that the TBB tasks do not need to lock the vector.
636 // In general, the number of uncompressed pages is larger than the number of sealed pages because we
637 // may decompress the same page into different in-memory representations.
638 std::size_t nPages = 0;
639 // We run a short version of the main loop to determine the number of uncompressed pages
640 for (const auto columnId : columnsInCluster) {
641 if (fActivePhysicalColumns.HasColumnInfos(columnId)) {
642 nPages += fActivePhysicalColumns.GetColumnInfos(columnId).size() *
643 clusterDescriptor.GetPageRange(columnId).GetPageInfos().size();
644 }
645 }
646 allPages.resize(nPages);
647 std::size_t iPage = 0;
648
649 std::vector<std::unique_ptr<RColumnElementBase>> allElements;
650 for (const auto columnId : columnsInCluster) {
651 // By the time we unzip a cluster, the set of active columns may have already changed wrt. to the moment when
652 // we requested reading the cluster. That doesn't matter much, we simply decompress what is now in the list
653 // of active columns.
654 if (!fActivePhysicalColumns.HasColumnInfos(columnId))
655 continue;
656 const auto &columnInfos = fActivePhysicalColumns.GetColumnInfos(columnId);
657 const auto indexOffset = clusterDescriptor.GetColumnRange(columnId).GetFirstElementIndex();
658
659 allElements.reserve(allElements.size() + columnInfos.size());
660 for (const auto &info : columnInfos) {
661 allElements.emplace_back(GenerateColumnElement(info.fElementId));
662 const auto element = allElements.back().get();
663
664 const auto &pageRange = clusterDescriptor.GetPageRange(columnId);
665 std::uint64_t pageNo = 0;
666 std::uint64_t firstInPage = 0;
667 for (const auto &pi : pageRange.GetPageInfos()) {
668 auto onDiskPage = cluster->GetOnDiskPage(ROnDiskPage::Key{columnId, pageNo});
669 RSealedPage sealedPage;
670 sealedPage.SetNElements(pi.GetNElements());
671 sealedPage.SetHasChecksum(pi.HasChecksum());
672 sealedPage.SetBufferSize(pi.GetLocator().GetNBytesOnStorage() +
673 pi.HasChecksum() * RSealedPage::kNBytesPageChecksum);
674 sealedPage.SetBuffer(onDiskPage->GetAddress());
675 R__ASSERT(onDiskPage->GetSize() == sealedPage.GetBufferSize());
676
677 auto taskFunc = [this, columnId, clusterId, firstInPage, sealedPage, element, iPage, indexOffset,
678 &foundChecksumFailure, &allPages]() {
679 auto rv = UnsealPage(sealedPage, *element);
680 if (!rv) {
681 foundChecksumFailure = true;
682 return;
683 }
684 auto newPage = rv.Unwrap();
685 fCounters->fSzUnzip.Add(element->GetSize() * sealedPage.GetNElements());
686
687 newPage.SetWindow(indexOffset + firstInPage,
688 ROOT::Internal::RPage::RClusterInfo(clusterId, indexOffset));
689 const ROOT::Internal::RPagePool::RKey keyPagePool{columnId, element->GetIdentifier().fInMemoryType};
690 allPages[iPage] = std::make_pair(std::move(newPage), keyPagePool);
691 };
692
693 if (sealedPage.GetNElements() * element->GetSize() < kInlineDecompressionThreshold) {
694 taskFunc();
695 } else {
696 fTaskScheduler->AddTask(taskFunc);
697 }
698
699 firstInPage += pi.GetNElements();
700 pageNo++;
701 iPage++;
702 } // for all pages in column
703 } // for all in-memory types of the column
704 } // for all columns in cluster
705
706 fTaskScheduler->Wait();
707 fCounters->fNPageUnsealed.Add(nPages);
708
709 if (foundChecksumFailure) {
710 throw RException(R__FAIL("page checksum verification failed, data corruption detected"));
711 }
712
713 fPagePool.PreloadPageV(allPages);
714}
715
717 const RCluster::RKey &clusterKey, ROnDiskPageMap &pageZeroMap,
719 &perPageFunc)
720{
721 auto descriptorGuard = EnsureClusterDetails(FindClusterGroupId(clusterKey.fClusterId), GetSharedDescriptorGuard());
722 const auto &clusterDesc = descriptorGuard->GetClusterDescriptor(clusterKey.fClusterId);
723
724 for (auto physicalColumnId : clusterKey.fPhysicalColumnSet) {
725 if (clusterDesc.GetColumnRange(physicalColumnId).IsSuppressed())
726 continue;
727
728 const auto &pageRange = clusterDesc.GetPageRange(physicalColumnId);
729 ROOT::NTupleSize_t pageNo = 0;
730 for (const auto &pageInfo : pageRange.GetPageInfos()) {
731 if (pageInfo.GetLocator().GetType() == RNTupleLocator::kTypePageZero) {
732 pageZeroMap.Register(ROnDiskPage::Key{physicalColumnId, pageNo},
734 pageInfo.GetLocator().GetNBytesOnStorage()));
735 } else {
736 perPageFunc(physicalColumnId, pageNo, pageInfo);
737 }
738 ++pageNo;
739 }
740 }
741}
742
744{
745 if (fLastUsedCluster == clusterId)
746 return;
747
748 ROOT::NTupleSize_t firstEntryIndex = kInvalidNTupleIndex;
749 {
750 auto descGuard = EnsureClusterDetails(FindClusterGroupId(clusterId), GetSharedDescriptorGuard());
751 firstEntryIndex = descGuard->GetClusterDescriptor(clusterId).GetFirstEntryIndex();
752 }
753 auto itr = fPreloadedClusters.begin();
754 while ((itr != fPreloadedClusters.end()) && (itr->first < firstEntryIndex)) {
755 if (fPinnedClusters.count(itr->second) > 0) {
756 ++itr;
757 } else {
758 fPagePool.Evict(itr->second);
759 itr = fPreloadedClusters.erase(itr);
760 }
761 }
762 std::size_t poolWindow = 0;
763 while ((itr != fPreloadedClusters.end()) &&
765 ++itr;
766 ++poolWindow;
767 }
768 while (itr != fPreloadedClusters.end()) {
769 if (fPinnedClusters.count(itr->second) > 0) {
770 ++itr;
771 } else {
772 fPagePool.Evict(itr->second);
773 itr = fPreloadedClusters.erase(itr);
774 }
775 }
776
777 fLastUsedCluster = clusterId;
778}
779
781 RSealedPage &sealedPage)
782{
783 const auto clusterId = localIndex.GetClusterId();
784
786 {
787 auto descriptorGuard = EnsureClusterDetails(FindClusterGroupId(clusterId), GetSharedDescriptorGuard());
788 const auto &clusterDescriptor = descriptorGuard->GetClusterDescriptor(clusterId);
789 pageInfo = clusterDescriptor.GetPageRange(physicalColumnId).Find(localIndex.GetIndexInCluster());
790 }
791
792 assert(pageInfo.GetLocator().GetType() != RNTupleLocator::kTypePageZero);
793
794 sealedPage.SetBufferSize(pageInfo.GetLocator().GetNBytesOnStorage() +
796 sealedPage.SetNElements(pageInfo.GetNElements());
797 sealedPage.SetHasChecksum(pageInfo.HasChecksum());
798
799 if (!sealedPage.GetBuffer())
800 return;
801
802 LoadSealedPageImpl(pageInfo.GetLocator(), sealedPage);
804}
805
808{
809 const auto &pageInfo = pageSummary.fPageInfo;
810 assert(pageInfo.GetLocator().GetType() == RNTupleLocator::kTypePageZero);
811
812 const auto elemInMemoryType = elem.GetIdentifier().fInMemoryType;
813
814 auto pageZero = fPageAllocator.NewPage(elem.GetSize(), pageInfo.GetNElements());
815 pageZero.GrowUnchecked(pageInfo.GetNElements());
816 std::memset(pageZero.GetBuffer(), 0, pageZero.GetNBytes());
817 pageZero.SetWindow(pageSummary.fColumnOffset + pageInfo.GetFirstElementIndex(),
818 RPage::RClusterInfo(pageSummary.fClusterId, pageSummary.fColumnOffset));
819 return fPagePool.RegisterPage(std::move(pageZero), RPagePool::RKey{pageSummary.fPhysicalColumnId, elemInMemoryType});
820}
821
824{
826 throw RException(R__FAIL("tried to read a page with an unknown locator"));
827 } else if (pageSummary.fPageInfo.GetLocator().GetType() == RNTupleLocator::kTypePageZero) {
828 return LoadZeroPage(pageSummary, elem);
829 }
830
831 const auto &columnId = pageSummary.fPhysicalColumnId;
832 const auto &clusterId = pageSummary.fClusterId;
833 const auto &pageInfo = pageSummary.fPageInfo;
834
835 const auto elemInMemoryType = elem.GetIdentifier().fInMemoryType;
836
837 UpdateLastUsedCluster(clusterId);
838
839 RSealedPage sealedPage;
840 sealedPage.SetNElements(pageInfo.GetNElements());
841 sealedPage.SetHasChecksum(pageInfo.HasChecksum());
842 sealedPage.SetBufferSize(pageInfo.GetLocator().GetNBytesOnStorage() +
843 pageInfo.HasChecksum() * RSealedPage::kNBytesPageChecksum);
844 std::unique_ptr<unsigned char[]> directReadBuffer; // only used if cluster pool is turned off
845
846 if (fOptions.GetClusterCache() == ROOT::RNTupleReadOptions::EClusterCache::kOff) {
847 directReadBuffer = MakeUninitArray<unsigned char>(sealedPage.GetBufferSize());
848 sealedPage.SetBuffer(directReadBuffer.get());
849 LoadSealedPageImpl(pageInfo.GetLocator(), sealedPage);
850
851 fCounters->fNPageRead.Inc();
852 fCounters->fNRead.Inc();
853 fCounters->fSzReadPayload.Add(sealedPage.GetBufferSize());
854 } else {
855 if (!fCurrentCluster || (fCurrentCluster->GetId() != clusterId) || !fCurrentCluster->ContainsColumn(columnId))
856 fCurrentCluster = fClusterPool.GetCluster(clusterId, fActivePhysicalColumns.ToColumnSet());
857 R__ASSERT(fCurrentCluster->ContainsColumn(columnId));
858
859 // The cluster pool may have unzipped the required page into the page pool
860 auto cachedPageRef = fPagePool.GetPage(ROOT::Internal::RPagePool::RKey{columnId, elemInMemoryType},
861 RNTupleLocalIndex(clusterId, pageInfo.GetFirstElementIndex()));
862 if (!cachedPageRef.Get().IsNull())
863 return cachedPageRef;
864
865 ROnDiskPage::Key key(columnId, pageInfo.GetPageNumber());
866 auto onDiskPage = fCurrentCluster->GetOnDiskPage(key);
867 R__ASSERT(onDiskPage && (sealedPage.GetBufferSize() == onDiskPage->GetSize()));
868 sealedPage.SetBuffer(onDiskPage->GetAddress());
869 }
870
871 ROOT::Internal::RPage newPage;
872 {
873 RNTupleAtomicTimer timer(fCounters->fTimeWallUnzip, fCounters->fTimeCpuUnzip);
874 newPage = UnsealPage(sealedPage, elem).Unwrap();
875 fCounters->fSzUnzip.Add(elem.GetSize() * pageInfo.GetNElements());
876 }
877
878 newPage.SetWindow(pageSummary.fColumnOffset + pageInfo.GetFirstElementIndex(),
879 ROOT::Internal::RPage::RClusterInfo(clusterId, pageSummary.fColumnOffset));
880 fCounters->fNPageUnsealed.Inc();
881
882 return fPagePool.RegisterPage(std::move(newPage), RPagePool::RKey{columnId, elemInMemoryType});
883}
884
886 const RColumnElementBase &elem,
887 ROOT::NTupleSize_t globalIndex)
888{
889 const ROOT::Internal::RPagePool::RKey poolKey{physicalColumnId, elem.GetIdentifier().fInMemoryType};
890 auto cachedPageRef = fPagePool.GetPage(poolKey, globalIndex);
891 if (!cachedPageRef.Get().IsNull()) {
892 UpdateLastUsedCluster(cachedPageRef.Get().GetClusterInfo().GetId());
893 return cachedPageRef;
894 }
895
896 RPageSummary pageSummary;
897 {
898 pageSummary.fPhysicalColumnId = physicalColumnId;
899 auto descriptorGuard = FindClusterId(physicalColumnId, globalIndex, pageSummary.fClusterId);
900
901 if (pageSummary.fClusterId == ROOT::kInvalidDescriptorId)
902 throw RException(R__FAIL("entry with index " + std::to_string(globalIndex) + " out of bounds"));
903
904 const auto &clusterDescriptor = descriptorGuard->GetClusterDescriptor(pageSummary.fClusterId);
905 const auto &columnRange = clusterDescriptor.GetColumnRange(physicalColumnId);
906 if (columnRange.IsSuppressed())
908
909 pageSummary.fColumnOffset = columnRange.GetFirstElementIndex();
910 R__ASSERT(pageSummary.fColumnOffset <= globalIndex);
911 pageSummary.fPageInfo =
912 clusterDescriptor.GetPageRange(physicalColumnId).Find(globalIndex - pageSummary.fColumnOffset);
913 }
914
915 return LoadPageFromSummary(pageSummary, elem);
916}
917
919 const RColumnElementBase &elem,
920 RNTupleLocalIndex localIndex)
921{
922 const auto clusterId = localIndex.GetClusterId();
923
924 const ROOT::Internal::RPagePool::RKey poolKey{physicalColumnId, elem.GetIdentifier().fInMemoryType};
925 auto cachedPageRef = fPagePool.GetPage(poolKey, localIndex);
926 if (!cachedPageRef.Get().IsNull()) {
927 UpdateLastUsedCluster(clusterId);
928 return cachedPageRef;
929 }
930
931 if (clusterId == kInvalidDescriptorId)
932 throw RException(R__FAIL("entry out of bounds"));
933
934 RPageSummary pageSummary;
935 {
936 auto descriptorGuard = EnsureClusterDetails(FindClusterGroupId(clusterId), GetSharedDescriptorGuard());
937 const auto &clusterDescriptor = descriptorGuard->GetClusterDescriptor(clusterId);
938 const auto &columnRange = clusterDescriptor.GetColumnRange(physicalColumnId);
939 if (columnRange.IsSuppressed())
941
942 pageSummary.fPhysicalColumnId = physicalColumnId;
943 pageSummary.fClusterId = clusterId;
944 pageSummary.fColumnOffset = columnRange.GetFirstElementIndex();
945 pageSummary.fPageInfo = clusterDescriptor.GetPageRange(physicalColumnId).Find(localIndex.GetIndexInCluster());
946 }
947
948 return LoadPageFromSummary(pageSummary, elem);
949}
950
952{
953 fMetrics = RNTupleMetrics(prefix);
954 fMetrics.ObserveMetrics(fClusterPool.GetMetrics());
955 fMetrics.ObserveMetrics(fPagePool.GetMetrics());
956 fCounters = std::make_unique<RCounters>(RCounters{
957 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("nReadV", "", "number of vector read requests"),
958 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("nRead", "", "number of byte ranges read"),
959 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("szReadPayload", "B", "volume read from storage (required)"),
960 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("szReadOverhead", "B", "volume read from storage (overhead)"),
961 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("szUnzip", "B", "volume after unzipping"),
962 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("nClusterLoaded", "",
963 "number of partial clusters preloaded from storage"),
964 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("nPageRead", "", "number of pages read from storage"),
965 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("nPageUnsealed", "", "number of pages unzipped and decoded"),
966 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("timeWallRead", "ns", "wall clock time spent reading"),
967 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("timeWallUnzip", "ns", "wall clock time spent decompressing"),
968 *fMetrics.MakeCounter<RNTupleTickCounter<RNTupleAtomicCounter> *>("timeCpuRead", "ns", "CPU time spent reading"),
969 *fMetrics.MakeCounter<RNTupleTickCounter<RNTupleAtomicCounter> *>("timeCpuUnzip", "ns",
970 "CPU time spent decompressing"),
971 *fMetrics.MakeCounter<RNTupleCalcPerf *>(
972 "bwRead", "MB/s", "bandwidth compressed bytes read per second", fMetrics,
973 [](const RNTupleMetrics &metrics) -> std::pair<bool, double> {
974 if (const auto szReadPayload = metrics.GetLocalCounter("szReadPayload")) {
975 if (const auto szReadOverhead = metrics.GetLocalCounter("szReadOverhead")) {
976 if (const auto timeWallRead = metrics.GetLocalCounter("timeWallRead")) {
977 if (auto walltime = timeWallRead->GetValueAsInt()) {
978 double payload = szReadPayload->GetValueAsInt();
979 double overhead = szReadOverhead->GetValueAsInt();
980 // unit: bytes / nanosecond = GB/s
981 return {true, (1000. * (payload + overhead) / walltime)};
982 }
983 }
984 }
985 }
986 return {false, -1.};
987 }),
988 *fMetrics.MakeCounter<RNTupleCalcPerf *>(
989 "bwReadUnzip", "MB/s", "bandwidth uncompressed bytes read per second", fMetrics,
990 [](const RNTupleMetrics &metrics) -> std::pair<bool, double> {
991 if (const auto szUnzip = metrics.GetLocalCounter("szUnzip")) {
992 if (const auto timeWallRead = metrics.GetLocalCounter("timeWallRead")) {
993 if (auto walltime = timeWallRead->GetValueAsInt()) {
994 double unzip = szUnzip->GetValueAsInt();
995 // unit: bytes / nanosecond = GB/s
996 return {true, 1000. * unzip / walltime};
997 }
998 }
999 }
1000 return {false, -1.};
1001 }),
1002 *fMetrics.MakeCounter<RNTupleCalcPerf *>(
1003 "bwUnzip", "MB/s", "decompression bandwidth of uncompressed bytes per second", fMetrics,
1004 [](const RNTupleMetrics &metrics) -> std::pair<bool, double> {
1005 if (const auto szUnzip = metrics.GetLocalCounter("szUnzip")) {
1006 if (const auto timeWallUnzip = metrics.GetLocalCounter("timeWallUnzip")) {
1007 if (auto walltime = timeWallUnzip->GetValueAsInt()) {
1008 double unzip = szUnzip->GetValueAsInt();
1009 // unit: bytes / nanosecond = GB/s
1010 return {true, 1000. * unzip / walltime};
1011 }
1012 }
1013 }
1014 return {false, -1.};
1015 }),
1016 *fMetrics.MakeCounter<RNTupleCalcPerf *>(
1017 "rtReadEfficiency", "", "ratio of payload over all bytes read", fMetrics,
1018 [](const RNTupleMetrics &metrics) -> std::pair<bool, double> {
1019 if (const auto szReadPayload = metrics.GetLocalCounter("szReadPayload")) {
1020 if (const auto szReadOverhead = metrics.GetLocalCounter("szReadOverhead")) {
1021 if (auto payload = szReadPayload->GetValueAsInt()) {
1022 // r/(r+o) = 1/((r+o)/r) = 1/(1 + o/r)
1023 return {true, 1. / (1. + (1. * szReadOverhead->GetValueAsInt()) / payload)};
1024 }
1025 }
1026 }
1027 return {false, -1.};
1028 }),
1029 *fMetrics.MakeCounter<RNTupleCalcPerf *>("rtCompression", "", "ratio of compressed bytes / uncompressed bytes",
1030 fMetrics, [](const RNTupleMetrics &metrics) -> std::pair<bool, double> {
1031 if (const auto szReadPayload =
1032 metrics.GetLocalCounter("szReadPayload")) {
1033 if (const auto szUnzip = metrics.GetLocalCounter("szUnzip")) {
1034 if (auto unzip = szUnzip->GetValueAsInt()) {
1035 return {true, (1. * szReadPayload->GetValueAsInt()) / unzip};
1036 }
1037 }
1038 }
1039 return {false, -1.};
1040 })});
1041}
1042
1045{
1046 return UnsealPage(sealedPage, element, fPageAllocator);
1047}
1048
1050 const RColumnElementBase &element,
1052{
1053 // Unsealing a page zero is a no-op. `RPageRange::ExtendToFitColumnRange()` guarantees that the page zero buffer is
1054 // large enough to hold `sealedPage.fNElements`
1056 auto page = pageAlloc.NewPage(element.GetSize(), sealedPage.GetNElements());
1057 page.GrowUnchecked(sealedPage.GetNElements());
1058 memset(page.GetBuffer(), 0, page.GetNBytes());
1059 return page;
1060 }
1061
1062 auto rv = sealedPage.VerifyChecksumIfEnabled();
1063 if (!rv)
1064 return R__FORWARD_ERROR(rv);
1065
1066 const auto bytesPacked = element.GetPackedSize(sealedPage.GetNElements());
1067 auto page = pageAlloc.NewPage(element.GetPackedSize(), sealedPage.GetNElements());
1068 if (sealedPage.GetDataSize() != bytesPacked) {
1069 ROOT::Internal::RNTupleDecompressor::Unzip(sealedPage.GetBuffer(), sealedPage.GetDataSize(), bytesPacked,
1070 page.GetBuffer());
1071 } else {
1072 // We cannot simply map the sealed page as we don't know its life time. Specialized page sources
1073 // may decide to implement to not use UnsealPage but to custom mapping / decompression code.
1074 // Note that usually pages are compressed.
1075 memcpy(page.GetBuffer(), sealedPage.GetBuffer(), bytesPacked);
1076 }
1077
1078 if (!element.IsMappable()) {
1079 auto tmp = pageAlloc.NewPage(element.GetSize(), sealedPage.GetNElements());
1080 element.Unpack(tmp.GetBuffer(), page.GetBuffer(), sealedPage.GetNElements());
1081 page = std::move(tmp);
1082 }
1083
1084 page.GrowUnchecked(sealedPage.GetNElements());
1085 return page;
1086}
1087
1089{
1090 if (fHasStreamerInfosRegistered)
1091 return;
1092
1093 for (const auto &extraTypeInfo : fDescriptor.GetExtraTypeInfoIterable()) {
1094 if (extraTypeInfo.GetContentId() != EExtraTypeInfoIds::kStreamerInfo)
1095 continue;
1096 // We don't need the result, it's enough that during deserialization, BuildCheck() is called for every
1097 // streamer info record.
1098 RNTupleSerializer::DeserializeStreamerInfos(extraTypeInfo.GetContent()).Unwrap();
1099 }
1100
1101 fHasStreamerInfosRegistered = true;
1102}
1103
1104//------------------------------------------------------------------------------
1105
1107{
1108 // Make the sort order unique by adding the physical on-disk column id as a secondary key
1109 if (fCurrentPageSize == other.fCurrentPageSize)
1110 return fColumn->GetOnDiskId() > other.fColumn->GetOnDiskId();
1111 return fCurrentPageSize > other.fCurrentPageSize;
1112}
1113
1114bool ROOT::Internal::RWritePageMemoryManager::TryEvict(std::size_t targetAvailableSize, std::size_t pageSizeLimit)
1115{
1116 if (fMaxAllocatedBytes - fCurrentAllocatedBytes >= targetAvailableSize)
1117 return true;
1118
1119 auto itr = fColumnsSortedByPageSize.begin();
1120 while (itr != fColumnsSortedByPageSize.end()) {
1121 if (itr->fCurrentPageSize <= pageSizeLimit)
1122 break;
1123 if (itr->fCurrentPageSize == itr->fInitialPageSize) {
1124 ++itr;
1125 continue;
1126 }
1127
1128 // Flushing the current column will invalidate itr
1129 auto itrFlush = itr++;
1130
1131 RColumnInfo next;
1132 if (itr != fColumnsSortedByPageSize.end())
1133 next = *itr;
1134
1135 itrFlush->fColumn->Flush();
1136 if (fMaxAllocatedBytes - fCurrentAllocatedBytes >= targetAvailableSize)
1137 return true;
1138
1139 if (next.fColumn == nullptr)
1140 return false;
1141 itr = fColumnsSortedByPageSize.find(next);
1142 };
1143
1144 return false;
1145}
1146
1147bool ROOT::Internal::RWritePageMemoryManager::TryUpdate(RWriteColumn &column, std::size_t newWritePageSize)
1148{
1149 const RColumnInfo key{&column, column.GetWritePageCapacity(), 0};
1150 auto itr = fColumnsSortedByPageSize.find(key);
1151 if (itr == fColumnsSortedByPageSize.end()) {
1152 if (!TryEvict(newWritePageSize, 0))
1153 return false;
1154 fColumnsSortedByPageSize.insert({&column, newWritePageSize, newWritePageSize});
1155 fCurrentAllocatedBytes += newWritePageSize;
1156 return true;
1157 }
1158
1159 RColumnInfo elem{*itr};
1160 assert(newWritePageSize >= elem.fInitialPageSize);
1161
1162 if (newWritePageSize == elem.fCurrentPageSize)
1163 return true;
1164
1165 fColumnsSortedByPageSize.erase(itr);
1166
1167 if (newWritePageSize < elem.fCurrentPageSize) {
1168 // Page got smaller
1169 fCurrentAllocatedBytes -= elem.fCurrentPageSize - newWritePageSize;
1170 elem.fCurrentPageSize = newWritePageSize;
1171 fColumnsSortedByPageSize.insert(elem);
1172 return true;
1173 }
1174
1175 // Page got larger, we may need to make space available
1176 const auto diffBytes = newWritePageSize - elem.fCurrentPageSize;
1177 if (!TryEvict(diffBytes, elem.fCurrentPageSize)) {
1178 // Don't change anything, let the calling column flush itself
1179 // TODO(jblomer): we may consider skipping the column in TryEvict and thus avoiding erase+insert
1180 fColumnsSortedByPageSize.insert(elem);
1181 return false;
1182 }
1183 fCurrentAllocatedBytes += diffBytes;
1184 elem.fCurrentPageSize = newWritePageSize;
1185 fColumnsSortedByPageSize.insert(elem);
1186 return true;
1187}
1188
1189//------------------------------------------------------------------------------
1190
1192 : fNTupleName(name), fOptions(options.Clone()), fWritePageMemoryManager(options.GetPageBufferBudget()), fMetrics("")
1193{
1195}
1196
1198
1200{
1201 assert(config.fPage);
1202 assert(config.fElement);
1203 assert(config.fBuffer);
1204
1205 unsigned char *pageBuf = reinterpret_cast<unsigned char *>(config.fPage->GetBuffer());
1206 bool isAdoptedBuffer = true;
1207 auto nBytesPacked = config.fPage->GetNBytes();
1208 auto nBytesChecksum = config.fWriteChecksum * RSealedPage::kNBytesPageChecksum;
1209
1210 if (!config.fElement->IsMappable()) {
1211 nBytesPacked = config.fElement->GetPackedSize(config.fPage->GetNElements());
1212 pageBuf = new unsigned char[nBytesPacked];
1213 isAdoptedBuffer = false;
1214 config.fElement->Pack(pageBuf, config.fPage->GetBuffer(), config.fPage->GetNElements());
1215 }
1216 auto nBytesZipped = nBytesPacked;
1217
1218 if ((config.fCompressionSettings != 0) || !config.fElement->IsMappable() || !config.fAllowAlias ||
1219 config.fWriteChecksum) {
1220 nBytesZipped =
1221 ROOT::Internal::RNTupleCompressor::Zip(pageBuf, nBytesPacked, config.fCompressionSettings, config.fBuffer);
1222 if (!isAdoptedBuffer)
1223 delete[] pageBuf;
1224 pageBuf = reinterpret_cast<unsigned char *>(config.fBuffer);
1225 isAdoptedBuffer = true;
1226 }
1227
1228 R__ASSERT(isAdoptedBuffer);
1229
1230 RSealedPage sealedPage{pageBuf, nBytesZipped + nBytesChecksum, config.fPage->GetNElements(), config.fWriteChecksum};
1231 sealedPage.ChecksumIfEnabled();
1232
1233 return sealedPage;
1234}
1235
1238{
1239 const auto nBytes = page.GetNBytes() + GetWriteOptions().GetEnablePageChecksums() * RSealedPage::kNBytesPageChecksum;
1240 if (fSealPageBuffer.size() < nBytes)
1241 fSealPageBuffer.resize(nBytes);
1242
1243 RSealPageConfig config;
1244 config.fPage = &page;
1245 config.fElement = &element;
1246 config.fCompressionSettings = GetWriteOptions().GetCompression();
1247 config.fWriteChecksum = GetWriteOptions().GetEnablePageChecksums();
1248 config.fAllowAlias = true;
1249 config.fBuffer = fSealPageBuffer.data();
1250
1251 return SealPage(config);
1252}
1253
1255{
1256 for (const auto &cb : fOnDatasetCommitCallbacks)
1257 cb(*this);
1258 return CommitDatasetImpl();
1259}
1260
1262{
1263 R__ASSERT(nElements > 0);
1264 const auto elementSize = column.GetElement()->GetSize();
1265 const auto nBytes = elementSize * nElements;
1266 if (!fWritePageMemoryManager.TryUpdate(column, nBytes))
1267 return ROOT::Internal::RPage();
1268 return fPageAllocator.NewPage(elementSize, nElements);
1269}
1270
1271//------------------------------------------------------------------------------
1272
1273std::unique_ptr<ROOT::Internal::RPageSink>
1274ROOT::Internal::RPagePersistentSink::Create(std::string_view ntupleName, std::string_view location,
1275 const ROOT::RNTupleWriteOptions &options)
1276{
1277 if (ntupleName.empty()) {
1278 throw RException(R__FAIL("empty RNTuple name"));
1279 }
1280 if (location.empty()) {
1281 throw RException(R__FAIL("empty storage location"));
1282 }
1283 if (location.find("daos://") == 0) {
1284#ifdef R__ENABLE_DAOS
1285 return std::make_unique<ROOT::Experimental::Internal::RPageSinkDaos>(ntupleName, location, options);
1286#else
1287 throw RException(R__FAIL("This RNTuple build does not support DAOS."));
1288#endif
1289 }
1290
1291 if (ROOT::StartsWith(location, "ntpl+s3+http://") || ROOT::StartsWith(location, "ntpl+s3+https://")) {
1292#ifdef R__ENABLE_S3
1293 return std::make_unique<ROOT::Experimental::Internal::RPageSinkS3>(ntupleName, location, options);
1294#else
1295 throw RException(R__FAIL("This RNTuple build does not support S3. Rebuild ROOT with the 'curl' "
1296 "cmake option enabled (-Dcurl=ON) to enable the S3 backend."));
1297#endif
1298 }
1299
1300 // Otherwise assume that the user wants us to create a file.
1301 return std::make_unique<ROOT::Internal::RPageSinkFile>(ntupleName, location, options);
1302}
1303
1305 const ROOT::RNTupleWriteOptions &options)
1306 : RPageSink(name, options)
1307{
1308}
1309
1311
1313{
1314 auto columnId = fDescriptorBuilder.GetDescriptor().GetNPhysicalColumns();
1315 RColumnDescriptorBuilder columnBuilder;
1316 columnBuilder.LogicalColumnId(columnId)
1317 .PhysicalColumnId(columnId)
1318 .FieldId(fieldId)
1320 .ValueRange(column.GetValueRange())
1321 .Type(column.GetType())
1322 .Index(column.GetIndex())
1325 // For late model extension, we assume that the primary column representation is the active one for the
1326 // deferred range. All other representations are suppressed.
1327 if (column.ForWriting()->GetFirstElementIndex() > 0 && column.GetRepresentationIndex() > 0)
1328 columnBuilder.SetSuppressedDeferred();
1329 fDescriptorBuilder.AddColumn(columnBuilder.MoveDescriptor().Unwrap());
1330 return columnId;
1331}
1332
1334 ROOT::NTupleSize_t firstEntry)
1335{
1336 if (fIsInitialized) {
1337 for (const auto &field : changeset.fAddedFields) {
1338 if (field->GetStructure() == ENTupleStructure::kStreamer) {
1339 throw ROOT::RException(R__FAIL("a Model cannot be extended with Streamer fields"));
1340 }
1341 }
1342 }
1343
1344 const auto &descriptor = fDescriptorBuilder.GetDescriptor();
1345
1346 if (descriptor.GetNLogicalColumns() > descriptor.GetNPhysicalColumns()) {
1347 // If we already have alias columns, add an offset to the alias columns so that the new physical columns
1348 // of the changeset follow immediately the already existing physical columns
1349 auto getNColumns = [](const ROOT::RFieldBase &f) -> std::size_t {
1350 const auto &reps = f.GetColumnRepresentatives();
1351 if (reps.empty())
1352 return 0;
1353 return reps.size() * reps[0].size();
1354 };
1355 std::uint32_t nNewPhysicalColumns = 0;
1356 for (auto f : changeset.fAddedFields) {
1357 nNewPhysicalColumns += getNColumns(*f);
1358 for (const auto &descendant : *f)
1359 nNewPhysicalColumns += getNColumns(descendant);
1360 }
1361 fDescriptorBuilder.ShiftAliasColumns(nNewPhysicalColumns);
1362 }
1363
1364 auto addField = [&](ROOT::RFieldBase &f) {
1365 auto fieldId = descriptor.GetNFields();
1366 fDescriptorBuilder.AddField(f, fieldId);
1367 fDescriptorBuilder.AddFieldLink(f.GetParent()->GetOnDiskId(), fieldId);
1368 f.SetOnDiskId(fieldId);
1369 ROOT::Internal::CallConnectPageSinkOnField(f, *this, firstEntry); // issues in turn calls to `AddColumn()`
1370 };
1371 auto addProjectedField = [&](ROOT::RFieldBase &f) {
1372 auto fieldId = descriptor.GetNFields();
1373 auto sourceFieldId =
1375 fDescriptorBuilder.AddField(f, fieldId);
1376 fDescriptorBuilder.AddFieldLink(f.GetParent()->GetOnDiskId(), fieldId);
1377 fDescriptorBuilder.AddFieldProjection(sourceFieldId, fieldId);
1378 f.SetOnDiskId(fieldId);
1379 for (const auto &source : descriptor.GetColumnIterable(sourceFieldId)) {
1380 auto targetId = descriptor.GetNLogicalColumns();
1381 RColumnDescriptorBuilder columnBuilder;
1382 columnBuilder.LogicalColumnId(targetId)
1383 .PhysicalColumnId(source.GetLogicalId())
1384 .FieldId(fieldId)
1385 .BitsOnStorage(source.GetBitsOnStorage())
1386 .ValueRange(source.GetValueRange())
1387 .Type(source.GetType())
1388 .Index(source.GetIndex())
1389 .RepresentationIndex(source.GetRepresentationIndex());
1390 fDescriptorBuilder.AddColumn(columnBuilder.MoveDescriptor().Unwrap());
1391 }
1392 };
1393
1394 R__ASSERT(firstEntry >= fPrevClusterNEntries);
1395 const auto nColumnsBeforeUpdate = descriptor.GetNPhysicalColumns();
1396 for (auto f : changeset.fAddedFields) {
1397 addField(*f);
1398 for (auto &descendant : *f)
1399 addField(descendant);
1400 }
1401 for (auto f : changeset.fAddedProjectedFields) {
1402 addProjectedField(*f);
1403 for (auto &descendant : *f)
1404 addProjectedField(descendant);
1405 }
1406
1407 const auto nColumns = descriptor.GetNPhysicalColumns();
1408 fOpenColumnRanges.reserve(fOpenColumnRanges.size() + (nColumns - nColumnsBeforeUpdate));
1409 fOpenPageRanges.reserve(fOpenPageRanges.size() + (nColumns - nColumnsBeforeUpdate));
1410 for (ROOT::DescriptorId_t i = nColumnsBeforeUpdate; i < nColumns; ++i) {
1412 columnRange.SetPhysicalColumnId(i);
1413 // We set the first element index in the current cluster to the first element that is part of a materialized page
1414 // (i.e., that is part of a page list). For columns created during late model extension, however, the column range
1415 // is fixed up as needed by `RClusterDescriptorBuilder::AddExtendedColumnRanges()` on read back.
1416 columnRange.SetFirstElementIndex(descriptor.GetColumnDescriptor(i).GetFirstElementIndex());
1417 columnRange.SetNElements(0);
1418 columnRange.SetCompressionSettings(GetWriteOptions().GetCompression());
1419 fOpenColumnRanges.emplace_back(columnRange);
1421 pageRange.SetPhysicalColumnId(i);
1422 fOpenPageRanges.emplace_back(std::move(pageRange));
1423 }
1424
1425 // Mapping of memory to on-disk column IDs usually happens during serialization of the ntuple header. If the
1426 // header was already serialized, this has to be done manually as it is required for page list serialization.
1427 if (fSerializationContext.GetHeaderSize() > 0)
1428 fSerializationContext.MapSchema(descriptor, /*forHeaderExtension=*/true);
1429}
1430
1432{
1433 if (extraTypeInfo.GetContentId() != EExtraTypeInfoIds::kStreamerInfo)
1434 throw RException(R__FAIL("ROOT bug: unexpected type extra info in UpdateExtraTypeInfo()"));
1435
1436 fInfosOfStreamerFields.merge(RNTupleSerializer::DeserializeStreamerInfos(extraTypeInfo.GetContent()).Unwrap());
1437}
1438
1440{
1441 fDescriptorBuilder.SetNTuple(GetNTupleName(), model.GetDescription());
1442 fDescriptorBuilder.SetVersionForWriting();
1443 const auto &descriptor = fDescriptorBuilder.GetDescriptor();
1444
1445 auto &fieldZero = ROOT::Internal::GetFieldZeroOfModel(model);
1446 fDescriptorBuilder.AddField(fieldZero, 0);
1447 fieldZero.SetOnDiskId(0);
1448 auto &projectedFields = ROOT::Internal::GetProjectedFieldsOfModel(model);
1449 projectedFields.GetFieldZero().SetOnDiskId(0);
1450
1451 ROOT::Internal::RNTupleModelChangeset initialChangeset{model};
1452 initialChangeset.fAddedFields.reserve(fieldZero.GetMutableSubfields().size());
1453 for (auto f : fieldZero.GetMutableSubfields())
1454 initialChangeset.fAddedFields.emplace_back(f);
1455 initialChangeset.fAddedProjectedFields.reserve(projectedFields.GetFieldZero().GetMutableSubfields().size());
1456 for (auto f : projectedFields.GetFieldZero().GetMutableSubfields())
1457 initialChangeset.fAddedProjectedFields.emplace_back(f);
1458 UpdateSchema(initialChangeset, 0U);
1459
1460 fSerializationContext = RNTupleSerializer::SerializeHeader(nullptr, descriptor).Unwrap();
1461 auto buffer = MakeUninitArray<unsigned char>(fSerializationContext.GetHeaderSize());
1462 fSerializationContext = RNTupleSerializer::SerializeHeader(buffer.get(), descriptor).Unwrap();
1463 CommitHeaderImpl(buffer.get(), fSerializationContext.GetHeaderSize());
1464
1465 fDescriptorBuilder.BeginHeaderExtension();
1466}
1467
1468std::unique_ptr<ROOT::RNTupleModel>
1470{
1471 // Create new descriptor
1472 fDescriptorBuilder.SetSchemaFromExisting(srcDescriptor);
1473 // This is needed to be able to use GetTypeNameForComparison()
1474 fDescriptorBuilder.SetVersionForWriting();
1475 const auto &descriptor = fDescriptorBuilder.GetDescriptor();
1476
1477 // Create column/page ranges
1478 const auto nColumns = descriptor.GetNPhysicalColumns();
1479 R__ASSERT(fOpenColumnRanges.empty() && fOpenPageRanges.empty());
1480 fOpenColumnRanges.reserve(nColumns);
1481 fOpenPageRanges.reserve(nColumns);
1482 for (ROOT::DescriptorId_t i = 0; i < nColumns; ++i) {
1483 const auto &column = descriptor.GetColumnDescriptor(i);
1485 columnRange.SetPhysicalColumnId(i);
1486 columnRange.SetFirstElementIndex(column.GetFirstElementIndex());
1487 columnRange.SetNElements(0);
1488 columnRange.SetCompressionSettings(GetWriteOptions().GetCompression());
1489 fOpenColumnRanges.emplace_back(columnRange);
1491 pageRange.SetPhysicalColumnId(i);
1492 fOpenPageRanges.emplace_back(std::move(pageRange));
1493 }
1494
1495 if (copyClusters) {
1496 // Clone and add all cluster descriptors
1497 R__ASSERT(srcDescriptor.GetNClusters() == srcDescriptor.GetNActiveClusters());
1498 for (const auto &cluster : srcDescriptor.GetActiveClusterIterable()) {
1499 auto nEntries = cluster.GetNEntries();
1500 for (unsigned int i = 0; i < fOpenColumnRanges.size(); ++i) {
1501 R__ASSERT(fOpenColumnRanges[i].GetPhysicalColumnId() == i);
1502 if (!cluster.ContainsColumn(i)) // a cluster may not contain a column if that column is deferred
1503 break;
1504 const auto &columnRange = cluster.GetColumnRange(i);
1505 R__ASSERT(columnRange.GetPhysicalColumnId() == i);
1506 // TODO: properly handle suppressed columns (check MarkSuppressedColumnRange())
1507 fOpenColumnRanges[i].IncrementFirstElementIndex(columnRange.GetNElements());
1508 }
1509 fDescriptorBuilder.AddCluster(cluster.Clone());
1510 fPrevClusterNEntries += nEntries;
1511 }
1512 }
1513
1514 // Create model
1516 modelOpts.SetReconstructProjections(true);
1517 // We want to emulate unknown types to allow merging RNTuples containing types that we lack dictionaries for.
1518 modelOpts.SetEmulateUnknownTypes(true);
1519 auto model = descriptor.CreateModel(modelOpts);
1520 if (!copyClusters) {
1521 auto &projectedFields = ROOT::Internal::GetProjectedFieldsOfModel(*model);
1522 projectedFields.GetFieldZero().SetOnDiskId(model->GetConstFieldZero().GetOnDiskId());
1523 }
1524
1525 // Serialize header and init from it
1526 fSerializationContext = RNTupleSerializer::SerializeHeader(nullptr, descriptor).Unwrap();
1527 auto buffer = MakeUninitArray<unsigned char>(fSerializationContext.GetHeaderSize());
1528 fSerializationContext = RNTupleSerializer::SerializeHeader(buffer.get(), descriptor).Unwrap();
1529 CommitHeaderImpl(buffer.get(), fSerializationContext.GetHeaderSize());
1530
1531 fDescriptorBuilder.BeginHeaderExtension();
1532
1533 // mark this sink as initialized
1534 fIsInitialized = true;
1535
1536 return model;
1537}
1538
1541 std::span<const RColumnFormat> newRepresentation,
1542 std::uint64_t clusterOffset)
1543{
1544 const auto &descriptor = fDescriptorBuilder.GetDescriptor();
1545
1546 assert(&descriptor.GetFieldDescriptor(field.GetId()) == &field);
1547 assert(!field.IsProjectedField());
1548 assert(field.GetColumnCardinality() > 0);
1549 assert(!field.GetLogicalColumnIds().empty());
1550 assert(newRepresentation.size() == field.GetColumnCardinality());
1551
1552 const std::size_t firstPhysicalIndex = fDescriptorBuilder.GetDescriptor().GetNPhysicalColumns();
1553 const std::uint16_t reprIndex = field.GetLogicalColumnIds().size() / field.GetColumnCardinality();
1554
1555 fDescriptorBuilder.ShiftAliasColumns(newRepresentation.size());
1556
1557 std::uint16_t columnIndex = 0; // index into the representation
1558 for (auto columnRepr : newRepresentation) {
1559 std::size_t bitsOnStorage = columnRepr.fBitWidth;
1560 if (!bitsOnStorage) {
1561 const auto [rangeMin, rangeMax] = ROOT::Internal::RColumnElementBase::GetValidBitRange(columnRepr.fType);
1562 if (rangeMin != rangeMax) {
1563 throw ROOT::RException(R__FAIL("bit width must be given for columns of variable bit width"));
1564 }
1565 bitsOnStorage = rangeMin;
1566 }
1567
1568 const ROOT::DescriptorId_t firstReprColumnId = field.GetLogicalColumnIds()[columnIndex];
1569 const auto &firstReprColumnRange = fOpenColumnRanges.at(firstReprColumnId);
1570 const ROOT::DescriptorId_t columnId = firstPhysicalIndex + columnIndex;
1571 // NOTE: this is always non-negative because it's the sum of two unsigned integers.
1572 const std::uint64_t newReprFirstElemIndex = firstReprColumnRange.GetFirstElementIndex() + clusterOffset;
1573
1574 RColumnDescriptorBuilder columnBuilder;
1575 columnBuilder.LogicalColumnId(columnId)
1576 .PhysicalColumnId(columnId)
1577 .FieldId(field.GetId())
1578 .BitsOnStorage(bitsOnStorage)
1579 .Type(columnRepr.fType)
1580 .Index(columnIndex)
1581 .FirstElementIndex(newReprFirstElemIndex)
1582 .RepresentationIndex(reprIndex)
1583 .ValueRange(columnRepr.fValueRange);
1584 if (newReprFirstElemIndex)
1585 columnBuilder.SetSuppressedDeferred();
1586 fDescriptorBuilder.AddColumn(columnBuilder.MoveDescriptor().Unwrap());
1587
1588 if (newReprFirstElemIndex != 0) {
1589 for (auto parentId = field.GetParentId(); parentId != ROOT::kInvalidDescriptorId;) {
1590 const ROOT::RFieldDescriptor &parent = descriptor.GetFieldDescriptor(parentId);
1593 fDescriptorBuilder.SetFeature(RNTupleDescriptor::kFeatureFlag_NestedDeferredColumns);
1594 break;
1595 }
1596 parentId = parent.GetParentId();
1597 }
1598 }
1599
1601 columnRange.SetPhysicalColumnId(columnId);
1602 columnRange.SetFirstElementIndex(firstReprColumnRange.GetFirstElementIndex());
1603 columnRange.SetNElements(0);
1604 columnRange.SetCompressionSettings(GetWriteOptions().GetCompression());
1605 fOpenColumnRanges.emplace_back(columnRange);
1606
1608 pageRange.SetPhysicalColumnId(columnId);
1609 fOpenPageRanges.emplace_back(std::move(pageRange));
1610
1611 fSerializationContext.MapPhysicalColumnId(columnId);
1612
1613 ++columnIndex;
1614 }
1615
1616 fDescriptorBuilder.EnsureValidDescriptor().ThrowOnError();
1617
1618 return firstPhysicalIndex;
1619}
1620
1622 const ROOT::RFieldDescriptor &field,
1623 ROOT::DescriptorId_t physicalId)
1624{
1625 const auto &pointedColumn = desc.GetColumnDescriptor(physicalId);
1626 assert(!pointedColumn.IsAliasColumn());
1627 assert(field.IsProjectedField());
1628
1629 const auto columnId = fDescriptorBuilder.GetDescriptor().GetNLogicalColumns();
1630 RColumnDescriptorBuilder columnBuilder;
1631 columnBuilder.LogicalColumnId(columnId)
1632 .PhysicalColumnId(physicalId)
1633 .FieldId(field.GetId())
1634 .Type(pointedColumn.GetType())
1635 .Index(pointedColumn.GetIndex())
1636 .BitsOnStorage(pointedColumn.GetBitsOnStorage())
1637 .ValueRange(pointedColumn.GetValueRange())
1638 .FirstElementIndex(pointedColumn.GetFirstElementIndex())
1639 .RepresentationIndex(pointedColumn.GetRepresentationIndex());
1640 fDescriptorBuilder.AddColumn(columnBuilder.MoveDescriptor().Unwrap());
1641
1642 fDescriptorBuilder.EnsureValidDescriptor().ThrowOnError();
1643}
1644
1646{
1647 fOpenColumnRanges.at(physicalColumnId).SetIsSuppressed(true);
1648}
1649
1651 const ROOT::Internal::RPage &page)
1652{
1653 fOpenColumnRanges.at(physicalColumnId).IncrementNElements(page.GetNElements());
1654
1655 RSealedPage sealedPage;
1656 {
1657 RNTupleAtomicTimer timer(fCounters->fTimeWallZip, fCounters->fTimeCpuZip);
1658 sealedPage = SealPage(page, elem);
1659 }
1660 fCounters->fSzZip.Add(page.GetNBytes());
1661
1663 pageInfo.SetNElements(page.GetNElements());
1664 pageInfo.SetLocator(CommitSealedPageImpl(physicalColumnId, sealedPage));
1665 pageInfo.SetHasChecksum(GetWriteOptions().GetEnablePageChecksums());
1666 fOpenPageRanges.at(physicalColumnId).GetPageInfos().emplace_back(pageInfo);
1667}
1668
1670 const RSealedPage &sealedPage)
1671{
1672 fOpenColumnRanges.at(physicalColumnId).IncrementNElements(sealedPage.GetNElements());
1673
1675 pageInfo.SetNElements(sealedPage.GetNElements());
1676 pageInfo.SetLocator(CommitSealedPageImpl(physicalColumnId, sealedPage));
1677 pageInfo.SetHasChecksum(sealedPage.GetHasChecksum());
1678 fOpenPageRanges.at(physicalColumnId).GetPageInfos().emplace_back(pageInfo);
1679}
1680
1681std::vector<ROOT::RNTupleLocator>
1683 const std::vector<bool> &mask)
1684{
1685 std::vector<ROOT::RNTupleLocator> locators;
1686 locators.reserve(mask.size());
1687 std::size_t i = 0;
1688 for (auto &range : ranges) {
1689 for (auto sealedPageIt = range.fFirst; sealedPageIt != range.fLast; ++sealedPageIt) {
1690 if (mask[i++])
1691 locators.push_back(CommitSealedPageImpl(range.fPhysicalColumnId, *sealedPageIt));
1692 }
1693 }
1694 locators.shrink_to_fit();
1695 return locators;
1696}
1697
1698void ROOT::Internal::RPagePersistentSink::CommitSealedPageV(std::span<RSealedPageGroup> ranges)
1699{
1700 /// Used in the `originalPages` map
1701 struct RSealedPageLink {
1702 const RSealedPage *fSealedPage = nullptr; ///< Points to the first occurrence of a page with a specific checksum
1703 std::size_t fLocatorIdx = 0; ///< The index in the locator vector returned by CommitSealedPageVImpl()
1704 };
1705
1706 std::vector<bool> mask;
1707 // For every sealed page, stores the corresponding index in the locator vector returned by CommitSealedPageVImpl()
1708 std::vector<std::size_t> locatorIndexes;
1709 // Maps page checksums to the first sealed page with that checksum
1710 std::unordered_map<std::uint64_t, RSealedPageLink> originalPages;
1711 std::size_t iLocator = 0;
1712 for (auto &range : ranges) {
1713 const auto rangeSize = std::distance(range.fFirst, range.fLast);
1714 mask.reserve(mask.size() + rangeSize);
1715 locatorIndexes.reserve(locatorIndexes.size() + rangeSize);
1716
1717 for (auto sealedPageIt = range.fFirst; sealedPageIt != range.fLast; ++sealedPageIt) {
1718 if (!fFeatures.fCanMergePages || !GetWriteOptions().GetEnableSamePageMerging()) {
1719 mask.emplace_back(true);
1720 locatorIndexes.emplace_back(iLocator++);
1721 continue;
1722 }
1723 // Same page merging requires page checksums - this is checked in the write options
1724 R__ASSERT(sealedPageIt->GetHasChecksum());
1725
1726 const auto chk = sealedPageIt->GetChecksum().Unwrap();
1727 auto itr = originalPages.find(chk);
1728 if (itr == originalPages.end()) {
1729 originalPages.insert({chk, {&(*sealedPageIt), iLocator}});
1730 mask.emplace_back(true);
1731 locatorIndexes.emplace_back(iLocator++);
1732 continue;
1733 }
1734
1735 const auto *p = itr->second.fSealedPage;
1736 if ((sealedPageIt->GetDataSize() != p->GetDataSize()) ||
1737 (memcmp(sealedPageIt->GetBuffer(), p->GetBuffer(), p->GetDataSize()) != 0)) {
1738 mask.emplace_back(true);
1739 locatorIndexes.emplace_back(iLocator++);
1740 continue;
1741 }
1742
1743 mask.emplace_back(false);
1744 locatorIndexes.emplace_back(itr->second.fLocatorIdx);
1745 }
1746
1747 mask.shrink_to_fit();
1748 locatorIndexes.shrink_to_fit();
1749 }
1750
1751 auto locators = CommitSealedPageVImpl(ranges, mask);
1752 unsigned i = 0;
1753
1754 for (auto &range : ranges) {
1755 for (auto sealedPageIt = range.fFirst; sealedPageIt != range.fLast; ++sealedPageIt) {
1756 fOpenColumnRanges.at(range.fPhysicalColumnId).IncrementNElements(sealedPageIt->GetNElements());
1757
1759 pageInfo.SetNElements(sealedPageIt->GetNElements());
1760 pageInfo.SetLocator(locators[locatorIndexes[i++]]);
1761 pageInfo.SetHasChecksum(sealedPageIt->GetHasChecksum());
1762 fOpenPageRanges.at(range.fPhysicalColumnId).GetPageInfos().emplace_back(pageInfo);
1763 }
1764 }
1765}
1766
1769{
1770 RStagedCluster stagedCluster;
1771 stagedCluster.fNBytesWritten = StageClusterImpl();
1772 stagedCluster.fNEntries = nNewEntries;
1773
1774 for (unsigned int i = 0; i < fOpenColumnRanges.size(); ++i) {
1775 RStagedCluster::RColumnInfo columnInfo;
1776 columnInfo.fCompressionSettings = fOpenColumnRanges[i].GetCompressionSettings().value();
1777 if (fOpenColumnRanges[i].IsSuppressed()) {
1778 assert(fOpenPageRanges[i].GetPageInfos().empty());
1779 columnInfo.fPageRange.SetPhysicalColumnId(i);
1780 columnInfo.fIsSuppressed = true;
1781 // We reset suppressed columns to the state they would have if they were active (not suppressed).
1782 fOpenColumnRanges[i].SetNElements(0);
1783 fOpenColumnRanges[i].SetIsSuppressed(false);
1784 } else {
1785 std::swap(columnInfo.fPageRange, fOpenPageRanges[i]);
1786 fOpenPageRanges[i].SetPhysicalColumnId(i);
1787
1788 columnInfo.fNElements = fOpenColumnRanges[i].GetNElements();
1789 fOpenColumnRanges[i].SetNElements(0);
1790 }
1791 stagedCluster.fColumnInfos.push_back(std::move(columnInfo));
1792 }
1793
1794 return stagedCluster;
1795}
1796
1798{
1799 for (const auto &cluster : clusters) {
1800 RClusterDescriptorBuilder clusterBuilder;
1801 clusterBuilder.ClusterId(fPrevGroupNClusters + fDescriptorBuilder.GetDescriptor().GetNActiveClusters())
1802 .FirstEntryIndex(fPrevClusterNEntries)
1803 .NEntries(cluster.fNEntries);
1804 for (const auto &columnInfo : cluster.fColumnInfos) {
1805 const auto colId = columnInfo.fPageRange.GetPhysicalColumnId();
1806 fNPagesInGroup += columnInfo.fPageRange.GetPageInfos().size();
1807 if (columnInfo.fIsSuppressed) {
1808 assert(columnInfo.fPageRange.GetPageInfos().empty());
1809 clusterBuilder.MarkSuppressedColumnRange(colId);
1810 } else {
1811 clusterBuilder.CommitColumnRange(colId, fOpenColumnRanges[colId].GetFirstElementIndex(),
1812 columnInfo.fCompressionSettings, columnInfo.fPageRange);
1813 fOpenColumnRanges[colId].IncrementFirstElementIndex(columnInfo.fNElements);
1814 }
1815 }
1816
1817 clusterBuilder.CommitSuppressedColumnRanges(fDescriptorBuilder.GetDescriptor()).ThrowOnError();
1818 for (const auto &columnInfo : cluster.fColumnInfos) {
1819 if (!columnInfo.fIsSuppressed)
1820 continue;
1821 const auto colId = columnInfo.fPageRange.GetPhysicalColumnId();
1822 // For suppressed columns, we need to reset the first element index to the first element of the next (upcoming)
1823 // cluster. This information has been determined for the committed cluster descriptor through
1824 // CommitSuppressedColumnRanges(), so we can use the information from the descriptor.
1825 const auto &columnRangeFromDesc = clusterBuilder.GetColumnRange(colId);
1826 fOpenColumnRanges[colId].SetFirstElementIndex(columnRangeFromDesc.GetFirstElementIndex() +
1827 columnRangeFromDesc.GetNElements());
1828 }
1829
1830 fDescriptorBuilder.AddCluster(clusterBuilder.MoveDescriptor().Unwrap());
1831 fPrevClusterNEntries += cluster.fNEntries;
1832 const auto &writeOpts = GetWriteOptions();
1833 if (fNPagesInGroup > writeOpts.GetClusterGroupPageThreshold() && writeOpts.GetClusterGroupPageThreshold() > 0) {
1834 CommitClusterGroup();
1835 }
1836 }
1837}
1838
1840{
1841 const auto &descriptor = fDescriptorBuilder.GetDescriptor();
1842
1843 const auto nClusters = descriptor.GetNActiveClusters();
1844 if (nClusters == 0) {
1845 assert(fNPagesInGroup == 0);
1846 return;
1847 }
1848
1849 std::vector<ROOT::DescriptorId_t> physClusterIDs;
1850 physClusterIDs.reserve(nClusters);
1851 for (ROOT::NTupleSize_t i = 0; i < nClusters; ++i) {
1852 physClusterIDs.emplace_back(fSerializationContext.MapClusterId(fPrevGroupNClusters + i));
1853 }
1854
1855 auto szPageList =
1856 RNTupleSerializer::SerializePageList(nullptr, descriptor, physClusterIDs, fSerializationContext).Unwrap();
1857 auto bufPageList = MakeUninitArray<unsigned char>(szPageList);
1858 RNTupleSerializer::SerializePageList(bufPageList.get(), descriptor, physClusterIDs, fSerializationContext);
1859
1860 const auto clusterGroupId = descriptor.GetNClusterGroups();
1861 const auto locator = CommitClusterGroupImpl(bufPageList.get(), szPageList);
1863 cgBuilder.ClusterGroupId(clusterGroupId).PageListLocator(locator).PageListLength(szPageList);
1864 const auto &firstClusterDesc = descriptor.GetClusterDescriptor(fPrevGroupNClusters);
1865 const auto &lastClusterDesc = descriptor.GetClusterDescriptor(fPrevGroupNClusters + nClusters - 1);
1866 cgBuilder.MinEntry(firstClusterDesc.GetFirstEntryIndex())
1867 .EntrySpan(lastClusterDesc.GetFirstEntryIndex() + lastClusterDesc.GetNEntries() -
1868 firstClusterDesc.GetFirstEntryIndex())
1869 .NClusters(nClusters);
1870 std::vector<ROOT::DescriptorId_t> clusterIds;
1871 clusterIds.reserve(nClusters);
1872 for (ROOT::NTupleSize_t i = 0; i < nClusters; ++i) {
1873 clusterIds.emplace_back(fPrevGroupNClusters + i);
1874 }
1875 cgBuilder.AddSortedClusters(clusterIds);
1876 fDescriptorBuilder.AddClusterGroup(cgBuilder.MoveDescriptor().Unwrap());
1877 fSerializationContext.MapClusterGroupId(clusterGroupId);
1878 fDescriptorBuilder.GetDescriptor().DropClusterGroupDetails(clusterGroupId);
1879
1880 fPrevGroupNClusters += nClusters;
1881 fNPagesInGroup = 0;
1882}
1883
1885 const RNTupleLink &attrAnchorInfo)
1886{
1887 using namespace ROOT::Internal::RNTupleAttributes;
1888
1889 RNTupleAttrSetDescriptorBuilder attrSetDescBuilder;
1890 auto attrSetDesc = attrSetDescBuilder.SchemaVersion(kSchemaVersionMajor, kSchemaVersionMinor)
1891 .AnchorLength(attrAnchorInfo.fLength)
1892 .AnchorLocator(attrAnchorInfo.fLocator)
1893 .Name(attrSetName)
1895 .Unwrap();
1896 fDescriptorBuilder.AddAttributeSet(std::move(attrSetDesc)).ThrowOnError();
1897}
1898
1900{
1901 if (!fInfosOfStreamerFields.empty()) {
1902 // De-duplicate extra type infos before writing. Usually we won't have them already in the descriptor, but
1903 // this may happen when we are writing back an already-existing RNTuple, e.g. when doing incremental merging.
1904 for (const auto &etDesc : fDescriptorBuilder.GetDescriptor().GetExtraTypeInfoIterable()) {
1905 if (etDesc.GetContentId() == EExtraTypeInfoIds::kStreamerInfo) {
1906 // The specification mandates that the type name for a kStreamerInfo should be empty and the type version
1907 // should be zero.
1908 R__ASSERT(etDesc.GetTypeName().empty());
1909 R__ASSERT(etDesc.GetTypeVersion() == 0);
1910 auto etInfo = RNTupleSerializer::DeserializeStreamerInfos(etDesc.GetContent()).Unwrap();
1911 fInfosOfStreamerFields.merge(etInfo);
1912 }
1913 }
1914
1915 RExtraTypeInfoDescriptorBuilder extraInfoBuilder;
1917 .Content(RNTupleSerializer::SerializeStreamerInfos(fInfosOfStreamerFields));
1918 fDescriptorBuilder.ReplaceExtraTypeInfo(extraInfoBuilder.MoveDescriptor().Unwrap());
1919 }
1920
1921 const auto &descriptor = fDescriptorBuilder.GetDescriptor();
1922
1923 auto szFooter = RNTupleSerializer::SerializeFooter(nullptr, descriptor, fSerializationContext).Unwrap();
1924 auto bufFooter = MakeUninitArray<unsigned char>(szFooter);
1925 RNTupleSerializer::SerializeFooter(bufFooter.get(), descriptor, fSerializationContext);
1926
1927 return CommitDatasetImpl(bufFooter.get(), szFooter);
1928}
1929
1931{
1932 fMetrics = RNTupleMetrics(prefix);
1933 fCounters = std::make_unique<RCounters>(RCounters{
1934 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("nPageCommitted", "", "number of pages committed to storage"),
1935 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("szWritePayload", "B", "volume written for committed pages"),
1936 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("szZip", "B", "volume before zipping"),
1937 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("timeWallWrite", "ns", "wall clock time spent writing"),
1938 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("timeWallZip", "ns", "wall clock time spent compressing"),
1939 *fMetrics.MakeCounter<RNTupleTickCounter<RNTupleAtomicCounter> *>("timeCpuWrite", "ns", "CPU time spent writing"),
1940 *fMetrics.MakeCounter<RNTupleTickCounter<RNTupleAtomicCounter> *>("timeCpuZip", "ns",
1941 "CPU time spent compressing")});
1942}
Interpolation descriptor
Definition HS3Parser.cxx:37
#define R__FORWARD_ERROR(res)
Short-hand to return an RResult<T> in an error state (i.e. after checking)
Definition RError.hxx:326
#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 f(i)
Definition RSha256.hxx:104
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:139
winID h TVirtualViewer3D TVirtualGLPainter p
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 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 index
Option_t Option_t TPoint TPoint const char mode
char name[80]
Definition TGX11.cxx:142
#define _(A, B)
Definition cfortran.h:112
A thread-safe integral performance counter.
A metric element that computes its floating point value from other counters.
std::int64_t GetValueAsInt() const override
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.
Record wall time and CPU time between construction and destruction.
A helper class for piece-wise construction of an RClusterDescriptor.
RResult< void > MarkSuppressedColumnRange(ROOT::DescriptorId_t physicalId)
Books the given column ID as being suppressed in this cluster.
RResult< void > CommitColumnRange(ROOT::DescriptorId_t physicalId, std::uint64_t firstElementIndex, std::uint32_t compressionSettings, const RClusterDescriptor::RPageRange &pageRange)
RClusterDescriptorBuilder & NEntries(std::uint64_t nEntries)
RResult< void > CommitSuppressedColumnRanges(const RNTupleDescriptor &desc)
Sets the first element index and number of elements for all the suppressed column ranges.
RResult< RClusterDescriptor > MoveDescriptor()
Move out the full cluster descriptor including page locations.
const RClusterDescriptor::RColumnRange & GetColumnRange(ROOT::DescriptorId_t physicalId)
RClusterDescriptorBuilder & ClusterId(ROOT::DescriptorId_t clusterId)
A helper class for piece-wise construction of an RClusterGroupDescriptor.
RClusterGroupDescriptorBuilder & EntrySpan(std::uint64_t entrySpan)
RClusterGroupDescriptorBuilder & PageListLocator(const RNTupleLocator &pageListLocator)
RClusterGroupDescriptorBuilder & PageListLength(std::uint64_t pageListLength)
RClusterGroupDescriptorBuilder & MinEntry(std::uint64_t minEntry)
void AddSortedClusters(const std::vector< ROOT::DescriptorId_t > &clusterIds)
RResult< RClusterGroupDescriptor > MoveDescriptor()
RClusterGroupDescriptorBuilder & ClusterGroupId(ROOT::DescriptorId_t clusterGroupId)
RClusterGroupDescriptorBuilder & NClusters(std::uint32_t nClusters)
An in-memory subset of the packed and compressed pages of a cluster.
Definition RCluster.hxx:147
std::unordered_set< ROOT::DescriptorId_t > ColumnSet_t
Definition RCluster.hxx:149
const ColumnSet_t & GetAvailPhysicalColumns() const
Definition RCluster.hxx:191
const ROnDiskPage * GetOnDiskPage(const ROnDiskPage::Key &key) const
Definition RCluster.cxx:30
ROOT::DescriptorId_t GetId() const
Definition RCluster.hxx:190
A helper class for piece-wise construction of an RColumnDescriptor.
RColumnDescriptorBuilder & SetSuppressedDeferred()
RColumnDescriptorBuilder & LogicalColumnId(ROOT::DescriptorId_t logicalColumnId)
RColumnDescriptorBuilder & FieldId(ROOT::DescriptorId_t fieldId)
RColumnDescriptorBuilder & BitsOnStorage(std::uint16_t bitsOnStorage)
RColumnDescriptorBuilder & ValueRange(double min, double max)
RColumnDescriptorBuilder & Type(ROOT::ENTupleColumnType type)
RColumnDescriptorBuilder & PhysicalColumnId(ROOT::DescriptorId_t physicalColumnId)
RColumnDescriptorBuilder & FirstElementIndex(std::uint64_t firstElementIdx)
RColumnDescriptorBuilder & Index(std::uint32_t index)
RColumnDescriptorBuilder & RepresentationIndex(std::uint16_t representationIndex)
RResult< RColumnDescriptor > MoveDescriptor()
Attempt to make a column descriptor.
A column element encapsulates the translation between basic C++ types and their column representation...
virtual bool IsMappable() const
Derived, typed classes tell whether the on-storage layout is bitwise identical to the memory layout.
static std::pair< std::uint16_t, std::uint16_t > GetValidBitRange(ROOT::ENTupleColumnType type)
Most types have a fixed on-disk bit width.
virtual void Unpack(void *destination, const void *source, std::size_t count) const
If the on-storage layout and the in-memory layout differ, unpacking creates a memory page from an on-...
virtual RIdentifier GetIdentifier() const =0
virtual void Pack(void *destination, const void *source, std::size_t count) const
If the on-storage layout and the in-memory layout differ, packing creates an on-disk page from an in-...
std::size_t GetPackedSize(std::size_t nElements=1U) const
A column is a storage-backed array of a simple, fixed-size type, from which pages can be mapped into ...
Definition RColumn.hxx:40
std::optional< std::pair< double, double > > GetValueRange() const
Definition RColumn.hxx:81
std::uint16_t GetRepresentationIndex() const
Definition RColumn.hxx:87
ROOT::Internal::RColumnElementBase * GetElement() const
Definition RColumn.hxx:74
ROOT::ENTupleColumnType GetType() const
Definition RColumn.hxx:75
ROOT::DescriptorId_t GetOnDiskId() const
Definition RColumn.hxx:88
RWriteColumn * ForWriting()
Definition RColumn.hxx:419
std::uint16_t GetBitsOnStorage() const
Definition RColumn.hxx:76
std::uint32_t GetIndex() const
Definition RColumn.hxx:86
A helper class for piece-wise construction of an RExtraTypeInfoDescriptor.
RResult< RExtraTypeInfoDescriptor > MoveDescriptor()
RExtraTypeInfoDescriptorBuilder & ContentId(EExtraTypeInfoIds contentId)
RExtraTypeInfoDescriptorBuilder & Content(const std::string &content)
RNTupleAttrSetDescriptorBuilder & Name(std::string_view name)
RNTupleAttrSetDescriptorBuilder & SchemaVersion(std::uint16_t major, std::uint16_t minor)
RResult< ROOT::RNTupleAttrSetDescriptor > MoveDescriptor()
Attempt to make an AttributeSet descriptor.
RNTupleAttrSetDescriptorBuilder & AnchorLocator(const RNTupleLocator &loc)
RNTupleAttrSetDescriptorBuilder & AnchorLength(std::uint32_t length)
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.
static unsigned int GetClusterBunchSize(const RNTupleReadOptions &options)
static unsigned int GetClusterGroupBudget(const RNTupleReadOptions &options)
static RResult< void > DeserializePageList(const void *buffer, std::uint64_t bufSize, ROOT::DescriptorId_t clusterGroupId, RNTupleDescriptor &desc, EDescriptorDeserializeMode mode)
static RResult< StreamerInfoMap_t > DeserializeStreamerInfos(const std::string &extraTypeInfoContent)
static RResult< std::uint32_t > SerializePageList(void *buffer, const RNTupleDescriptor &desc, std::span< ROOT::DescriptorId_t > physClusterIDs, const RContext &context)
static RResult< std::uint32_t > SerializeFooter(void *buffer, const RNTupleDescriptor &desc, const RContext &context)
static RResult< RContext > SerializeHeader(void *buffer, const RNTupleDescriptor &desc)
static std::string SerializeStreamerInfos(const StreamerInfoMap_t &infos)
A memory region that contains packed and compressed pages.
Definition RCluster.hxx:98
void Register(const ROnDiskPage::Key &key, const ROnDiskPage &onDiskPage)
Inserts information about a page stored in fMemory.
Definition RCluster.hxx:115
A page as being stored on disk, that is packed and compressed.
Definition RCluster.hxx:40
Abstract interface to allocate and release pages.
virtual RPage NewPage(std::size_t elementSize, std::size_t nElements)=0
Reserves memory large enough to hold nElements of the given size.
RStagedCluster StageCluster(ROOT::NTupleSize_t nNewEntries) final
Stage the current cluster and create a new one for the following data.
void UpdateSchema(const ROOT::Internal::RNTupleModelChangeset &changeset, ROOT::NTupleSize_t firstEntry) override
Incorporate incremental changes to the model into the ntuple descriptor.
std::unique_ptr< RNTupleModel > InitFromDescriptor(const ROOT::RNTupleDescriptor &descriptor, bool copyClusters)
Initialize sink based on an existing descriptor and fill into the descriptor builder,...
void UpdateExtraTypeInfo(const ROOT::RExtraTypeInfoDescriptor &extraTypeInfo) final
Adds an extra type information record to schema.
void CommitAttributeSet(std::string_view attrSetName, const RNTupleLink &attrAnchorInfo) final
Adds the given anchor information (name + locator) into the main RNTuple's descriptor as an attribute...
RPagePersistentSink(std::string_view ntupleName, const ROOT::RNTupleWriteOptions &options)
void CommitSealedPageV(std::span< RSealedPageGroup > ranges) final
Write a vector of preprocessed pages to storage. The corresponding columns must have been added befor...
void AddAliasColumn(const ROOT::RNTupleDescriptor &desc, const ROOT::RFieldDescriptor &field, ROOT::DescriptorId_t physicalId)
Adds a new alias column pointing to an existing column with the given physical id to the given field.
void CommitStagedClusters(std::span< RStagedCluster > clusters) final
Commit staged clusters, logically appending them to the ntuple descriptor.
static std::unique_ptr< RPageSink > Create(std::string_view ntupleName, std::string_view location, const ROOT::RNTupleWriteOptions &options=ROOT::RNTupleWriteOptions())
Guess the concrete derived page source from the location.
void InitImpl(RNTupleModel &model) final
Updates the descriptor and calls InitImpl() that handles the backend-specific details (file,...
DescriptorId_t AddColumn(ROOT::DescriptorId_t fieldId, const ROOT::Internal::RColumn &column) final
Add a column belonging to a certain field to the descriptor and return its on-disk ID.
virtual std::vector< RNTupleLocator > CommitSealedPageVImpl(std::span< RSealedPageGroup > ranges, const std::vector< bool > &mask)
Vector commit of preprocessed pages.
void CommitSuppressedColumn(DescriptorId_t physicalColumnId) final
Commits a suppressed column for the current cluster.
void CommitClusterGroup() final
Write out the page locations (page list envelope) for all the committed clusters since the last call ...
void CommitPage(DescriptorId_t physicalColumnId, const RColumnElementBase &elem, const ROOT::Internal::RPage &page) final
Write a page to the storage. The column must have been added before.
void EnableDefaultMetrics(const std::string &prefix)
Enables the default set of metrics provided by RPageSink.
ROOT::DescriptorId_t AddColumnRepresentation(const ROOT::RFieldDescriptor &field, std::span< const ROOT::Internal::RColumnFormat > newRepresentation, std::uint64_t clusterOffset)
Adds a new column representation to the given field.
void CommitSealedPage(ROOT::DescriptorId_t physicalColumnId, const RSealedPage &sealedPage) final
Write a preprocessed page to storage. The column must have been added before.
Reference to a page stored in the page pool.
Abstract interface to write data into an ntuple.
RNTupleLink CommitDataset()
Run the registered callbacks and finalize the current cluster and the entrire data set.
RSealedPage SealPage(const ROOT::Internal::RPage &page, const ROOT::Internal::RColumnElementBase &element)
Helper for streaming a page.
virtual ROOT::Internal::RPage ReservePage(RWriteColumn &column, std::size_t nElements)
Get a new, empty page for the given column that can be filled with up to nElements; nElements must be...
RPageSink(std::string_view ntupleName, const ROOT::RNTupleWriteOptions &options)
virtual const ROOT::RNTupleDescriptor & GetDescriptor() const =0
Return the RNTupleDescriptor being constructed.
std::unordered_map< ROOT::DescriptorId_t, std::vector< RColumnInfo > > fColumnInfos
Maps physical column IDs to all the requested in-memory representations.
void Insert(ROOT::DescriptorId_t physicalColumnId, ROOT::Internal::RColumnElementBase::RIdentifier elementId)
ROOT::Internal::RCluster::ColumnSet_t ToColumnSet() const
void Erase(ROOT::DescriptorId_t physicalColumnId, ROOT::Internal::RColumnElementBase::RIdentifier elementId)
Either a shared or an exclusive lock guard.
An RAII wrapper used for the writable access to RPageSource::fDescriptor. See GetSharedDescriptorGuar...
RAnyDescriptorGuard FindNextClusterId(ROOT::DescriptorId_t clusterId, ROOT::DescriptorId_t &nextId)
Uses FindClusterId to search for the cluster with the entry index following the last entry index of t...
ROOT::Internal::RClusterPool fClusterPool
The cluster pool asynchronously preloads the next few clusters.
void LoadStructure()
Loads header and footer without decompressing or deserializing them.
ROOT::Internal::RPageRef LoadPageFromSummary(const RPageSummary &pageSummary, const RColumnElementBase &elem)
ROOT::Experimental::Detail::RNTupleMetrics fMetrics
void LoadAllPageLists()
Load all remaining cluster details.
ROOT::Internal::RPageRef LoadZeroPage(const RPageSummary &pageSummary, const RColumnElementBase &elem)
ROOT::RNTupleReadOptions fOptions
void RegisterStreamerInfos()
Builds the streamer info records from the descriptor's extra type info section.
ROOT::NTupleSize_t GetNElements(ROOT::DescriptorId_t physicalColumnId)
RAnyDescriptorGuard EnsureClusterDetails(DescriptorId_t cgId, RAnyDescriptorGuard descGuard)
Ensures that fDescriptor has cluster details loaded for the given cluster group ID.
void Attach(ROOT::Internal::RNTupleSerializer::EDescriptorDeserializeMode mode=ROOT::Internal::RNTupleSerializer::EDescriptorDeserializeMode::kForReading)
Open the physical storage container and deserialize header and footer.
void UnzipCluster(ROOT::Internal::RCluster *cluster)
Parallel decompression and unpacking of the pages in the given cluster.
void EnableDefaultMetrics(const std::string &prefix)
Enables the default set of metrics provided by RPageSource.
ROOT::NTupleSize_t GetNEntries()
virtual ROOT::Internal::RPageRef LoadPage(DescriptorId_t physicalColumnId, const RColumnElementBase &elem, ROOT::NTupleSize_t globalIndex)
Allocates and fills a page that contains the index-th element.
DescriptorId_t AddColumn(ROOT::DescriptorId_t fieldId, const ROOT::Internal::RColumn &column)
void UpdateLastUsedCluster(ROOT::DescriptorId_t clusterId)
Does nothing if fLastUsedCluster == clusterId.
std::string fNTupleName
Initially empty if the page source is created from an anchor.
void UnpinCluster(ROOT::DescriptorId_t clusterId)
Allows the given cluster to be evicted from the cluster pool and page pool.
void PinCluster(ROOT::DescriptorId_t clusterId)
Instructs the cluster pool and page pool to consider the given cluster as active (should stay cached)...
ROOT::Internal::RPagePool fPagePool
Pages that are unzipped with IMT are staged into the page pool.
RAnyDescriptorGuard FindClusterId(ROOT::DescriptorId_t physicalColumnId, ROOT::NTupleSize_t index, ROOT::DescriptorId_t &cid)
Returns a shared descriptor guard to ensure that the returned cluster id is useable,...
void LoadSealedPage(ROOT::DescriptorId_t physicalColumnId, RNTupleLocalIndex localIndex, RSealedPage &sealedPage)
Read the packed and compressed bytes of a page into the memory buffer provided by sealedPage.
void LoadPageList(DescriptorId_t clusterGroupId, const RExclDescriptorGuard &exclGuard)
RPageSource(std::string_view ntupleName, const ROOT::RNTupleReadOptions &fOptions)
DescriptorId_t FindClusterGroupId(DescriptorId_t clusterId) const
Uses binary search in fCumulativeClusterCounts to determine the cluster group that the cluster ID bel...
void PrepareLoadCluster(const ROOT::Internal::RCluster::RKey &clusterKey, ROOT::Internal::ROnDiskPageMap &pageZeroMap, const std::function< void(ROOT::DescriptorId_t, ROOT::NTupleSize_t, const ROOT::RClusterDescriptor::RPageInfo &)> &perPageFunc)
Prepare a page range read for the column set in clusterKey.
void SetEntryRange(const REntryRange &range)
Promise to only read from the given entry range.
std::unique_ptr< RPageSource > Clone() const
Open the same storage multiple time, e.g.
void DropColumn(const ROOT::Internal::RColumn &column)
static std::unique_ptr< RPageSource > Create(std::string_view ntupleName, std::string_view location, const ROOT::RNTupleReadOptions &options=ROOT::RNTupleReadOptions())
Guess the concrete derived page source from the file name (location)
static RResult< ROOT::Internal::RPage > UnsealPage(const RSealedPage &sealedPage, const ROOT::Internal::RColumnElementBase &element, ROOT::Internal::RPageAllocator &pageAlloc)
Helper for unstreaming a page.
Stores information about the cluster in which this page resides.
Definition RPage.hxx:52
A page is a slice of a column that is mapped into memory.
Definition RPage.hxx:43
std::uint32_t GetNElements() const
Definition RPage.hxx:120
std::size_t GetNBytes() const
The space taken by column elements in the buffer.
Definition RPage.hxx:111
void * GrowUnchecked(std::uint32_t nElements)
Increases the number elements in the page.
Definition RPage.hxx:149
void * GetBuffer() const
Definition RPage.hxx:142
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:22
void SetWindow(const ROOT::NTupleSize_t rangeFirst, const RClusterInfo &clusterInfo)
Seek the page to a certain position of the column.
Definition RPage.hxx:157
const ROOT::RFieldBase * GetSourceField(const ROOT::RFieldBase *target) const
std::size_t GetWritePageCapacity() const
Definition RColumn.hxx:407
ROOT::NTupleSize_t GetFirstElementIndex() const
Definition RColumn.hxx:408
bool TryEvict(std::size_t targetAvailableSize, std::size_t pageSizeLimit)
Flush columns in order of allocated write page size until the sum of all write page allocations leave...
bool TryUpdate(ROOT::Internal::RWriteColumn &column, std::size_t newWritePageSize)
Try to register the new write page size for the given column.
The window of element indexes of a particular column in a particular cluster.
void SetCompressionSettings(std::optional< std::uint32_t > comp)
void SetPhysicalColumnId(ROOT::DescriptorId_t id)
void SetFirstElementIndex(ROOT::NTupleSize_t idx)
Records the partition of data into pages for a particular column in a particular cluster.
void SetPhysicalColumnId(ROOT::DescriptorId_t id)
Metadata for RNTuple clusters.
ROOT::NTupleSize_t GetNEntries() const
const RColumnRange & GetColumnRange(ROOT::DescriptorId_t physicalId) const
ROOT::NTupleSize_t GetFirstEntryIndex() const
bool HasClusterDetails() const
A cluster group is loaded in two stages.
const std::vector< ROOT::DescriptorId_t > & GetClusterIds() const
Base class for all ROOT issued exceptions.
Definition RError.hxx:78
Field specific extra type information from the header / extenstion header.
const std::string & GetContent() const
EExtraTypeInfoIds GetContentId() const
A field translates read and write calls from/to underlying columns to/from tree values.
ROOT::DescriptorId_t GetOnDiskId() const
Metadata stored for every field of an RNTuple.
ROOT::DescriptorId_t GetId() const
const std::vector< ROOT::DescriptorId_t > & GetLogicalColumnIds() const
ROOT::ENTupleStructure GetStructure() const
std::uint32_t GetColumnCardinality() const
ROOT::DescriptorId_t GetParentId() const
The on-storage metadata of an RNTuple.
const RClusterGroupDescriptor & GetClusterGroupDescriptor(ROOT::DescriptorId_t clusterGroupId) const
const RColumnDescriptor & GetColumnDescriptor(ROOT::DescriptorId_t columnId) const
const RFieldDescriptor & GetFieldDescriptor(ROOT::DescriptorId_t fieldId) const
RClusterDescriptorIterable GetActiveClusterIterable() const
RClusterGroupDescriptorIterable GetClusterGroupIterable() const
std::size_t GetNActiveClusters() const
ROOT::NTupleSize_t R__DEPRECATED(6, 46, "This function is ill-conceived in the descriptor " "as not all cluster descriptors may be present. This interface is no longer publicly exposed.") GetNElements(ROOT ROOT::DescriptorId_t GetFieldZeroId() const
Returns the logical parent of all top-level RNTuple data fields.
std::size_t GetNClusters() const
std::size_t GetNPhysicalColumns() const
@ kFeatureFlag_NestedDeferredColumns
Signals that the RNTuple contains at least one deferred column that is part of a collection and was e...
const RClusterDescriptor & GetClusterDescriptor(ROOT::DescriptorId_t clusterId) const
std::size_t GetNClusterGroups() const
Addresses a column element or field item relative to a particular cluster, instead of a global NTuple...
ROOT::NTupleSize_t GetIndexInCluster() const
ROOT::DescriptorId_t GetClusterId() const
std::uint64_t GetNBytesOnStorage() const
ELocatorType GetType() const
For non-disk locators, the value for the Type field.
The RNTupleModel encapulates the schema of an RNTuple.
Common user-tunable settings for reading RNTuples.
Common user-tunable settings for storing RNTuples.
void ThrowOnError()
Short-hand method to throw an exception in the case of errors.
Definition RError.hxx:312
The class is used as a return type for operations that can fail; wraps a value of type T or an RError...
Definition RError.hxx:222
ROOT::RFieldZero & GetFieldZeroOfModel(RNTupleModel &model)
RResult< void > EnsureValidNameForRNTuple(std::string_view name, std::string_view where)
Check whether a given string is a valid name according to the RNTuple specification.
RProjectedFields & GetProjectedFieldsOfModel(RNTupleModel &model)
std::unique_ptr< RColumnElementBase > GenerateColumnElement(std::type_index inMemoryType, ROOT::ENTupleColumnType onDiskType)
void CallConnectPageSinkOnField(RFieldBase &, ROOT::Internal::RPageSink &, ROOT::NTupleSize_t firstEntry=0)
std::uint64_t DescriptorId_t
Distriniguishes elements of the same type within a descriptor, e.g. different fields.
constexpr NTupleSize_t kInvalidNTupleIndex
bool StartsWith(std::string_view string, std::string_view prefix)
std::uint64_t NTupleSize_t
Integer type long enough to hold the maximum number of entries in a column.
constexpr DescriptorId_t kInvalidDescriptorId
The identifiers that specifies the content of a (partial) cluster.
Definition RCluster.hxx:151
ROOT::DescriptorId_t fClusterId
Definition RCluster.hxx:152
Every concrete RColumnElement type is identified by its on-disk type (column type) and the in-memory ...
The incremental changes to a RNTupleModel
std::vector< ROOT::RFieldBase * > fAddedProjectedFields
Points to the projected fields in fModel that were added as part of an updater transaction.
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
Default I/O performance counters that get registered in fMetrics.
Parameters for the SealPage() method.
bool fWriteChecksum
Adds a 8 byte little-endian xxhash3 checksum to the page payload.
std::uint32_t fCompressionSettings
Compression algorithm and level to apply.
void * fBuffer
Location for sealed output. The memory buffer has to be large enough.
const ROOT::Internal::RPage * fPage
Input page to be sealed.
bool fAllowAlias
If false, the output buffer must not point to the input page buffer, which would otherwise be an opti...
const ROOT::Internal::RColumnElementBase * fElement
Corresponds to the page's elements, for size calculation etc.
Cluster that was staged, but not yet logically appended to the RNTuple.
std::vector< RColumnInfo > fColumnInfos
Default I/O performance counters that get registered in fMetrics
Used in SetEntryRange / GetEntryRange.
bool IntersectsWith(const ROOT::RClusterDescriptor &clusterDesc) const
Returns true if the given cluster has entries within the entry range.
Summarizes meta-data necessary to load a certain page. Used by LoadPageFromSummary().
ROOT::RClusterDescriptor::RPageInfoExtended fPageInfo
Location of the page on disk.
std::uint64_t fColumnOffset
The first element number of the page's column in the given cluster.
A sealed page contains the bytes of a page as written to storage (packed & compressed).
static constexpr std::size_t kNBytesPageChecksum
The page checksum is a 64bit xxhash3.
void SetBufferSize(std::size_t bufferSize)
std::size_t GetBufferSize() const
std::size_t GetDataSize() const
void SetNElements(std::uint32_t nElements)
void SetBuffer(const void *buffer)
const void * GetBuffer() const
RResult< void > VerifyChecksumIfEnabled() const
std::uint32_t GetNElements() const
void SetHasChecksum(bool hasChecksum)
bool operator>(const RColumnInfo &other) const
Information about a single page in the context of a cluster's page range.
void SetLocator(const RNTupleLocator &locator)
const RNTupleLocator & GetLocator() const