Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RPageStorage.hxx
Go to the documentation of this file.
1/// \file ROOT/RPageStorage.hxx
2/// \author Jakob Blomer <jblomer@cern.ch>
3/// \date 2018-07-19
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#ifndef ROOT_RPageStorage
14#define ROOT_RPageStorage
15
16#include <ROOT/RError.hxx>
17#include <ROOT/RCluster.hxx>
18#include <ROOT/RClusterPool.hxx>
25#include <ROOT/RNTupleTypes.hxx>
26#include <ROOT/RNTupleUtils.hxx>
27#include <ROOT/RPage.hxx>
29#include <ROOT/RPagePool.hxx>
30#include <ROOT/RSealedPage.hxx>
31#include <ROOT/RSpan.hxx>
32#include <string_view>
33
34#include <atomic>
35#include <cassert>
36#include <cstddef>
37#include <deque>
38#include <functional>
39#include <map>
40#include <memory>
41#include <mutex>
42#include <set>
43#include <shared_mutex>
44#include <unordered_map>
45#include <unordered_set>
46#include <variant>
47#include <vector>
48
49namespace ROOT {
50
51class RNTupleModel;
52
53namespace Internal {
54
55class RColumn;
56class RWriteColumn;
57struct RNTupleModelChangeset;
58
59// clang-format off
60/**
61\class ROOT::Internal::RWritePageMemoryManager
62\ingroup NTuple
63\brief Helper to maintain a memory budget for the write pages of a set of columns
64
65The memory manager keeps track of the sum of bytes used by the write pages of a set of columns.
66It will flush (and shrink) large pages of other columns on the attempt to expand a page.
67*/
68// clang-format on
70private:
71 struct RColumnInfo {
73 std::size_t fCurrentPageSize = 0;
74 std::size_t fInitialPageSize = 0;
75
76 bool operator>(const RColumnInfo &other) const;
77 };
78
79 /// Sum of all the write page sizes (their capacity) of the columns in `fColumnsSortedByPageSize`
80 std::size_t fCurrentAllocatedBytes = 0;
81 /// Maximum allowed value for `fCurrentAllocatedBytes`, set from RNTupleWriteOptions::fPageBufferBudget
82 std::size_t fMaxAllocatedBytes = 0;
83 /// All columns that called `ReservePage()` (hence `TryUpdate()`) at least once,
84 /// sorted by their current write page size from large to small
85 std::set<RColumnInfo, std::greater<RColumnInfo>> fColumnsSortedByPageSize;
86
87 /// Flush columns in order of allocated write page size until the sum of all write page allocations
88 /// leaves space for at least targetAvailableSize bytes. Only use columns with a write page size larger
89 /// than pageSizeLimit.
90 bool TryEvict(std::size_t targetAvailableSize, std::size_t pageSizeLimit);
91
92public:
93 explicit RWritePageMemoryManager(std::size_t maxAllocatedBytes) : fMaxAllocatedBytes(maxAllocatedBytes) {}
94
95 /// Try to register the new write page size for the given column. Flush large columns to make space, if necessary.
96 /// If not enough space is available after all (sum of write pages would be larger than fMaxAllocatedBytes),
97 /// return false.
98 bool TryUpdate(ROOT::Internal::RWriteColumn &column, std::size_t newWritePageSize);
99};
100
101// clang-format off
102/**
103\class ROOT::Internal::RPageSink
104\ingroup NTuple
105\brief Abstract interface to write data into an ntuple
106
107The page sink takes the list of columns and afterwards a series of page commits and cluster commits.
108The user is responsible to commit clusters at a consistent point, i.e. when all pages corresponding to data
109up to the given entry number are committed.
110
111An object of this class may either be a wrapper (for example a RPageSinkBuf) or a "persistent" sink,
112inheriting from RPagePersistentSink.
113*/
114// clang-format on
116public:
117 using Callback_t = std::function<void(RPageSink &)>;
118
119private:
120 std::string fNTupleName;
121 /// May contain a derived class of RNTupleWriteOptions
122 std::unique_ptr<ROOT::RNTupleWriteOptions> fOptions;
123 /// Used in ReservePage to maintain the page buffer budget
125
126 std::vector<Callback_t> fOnDatasetCommitCallbacks;
127 std::vector<unsigned char> fSealPageBuffer; ///< Used as destination buffer in the simple SealPage overload
128
129protected:
132 /// Flag if sink was initialized
133 bool fIsInitialized = false;
134
135 /// Helper for streaming a page. This is commonly used in derived, concrete page sinks. Note that if
136 /// compressionSetting is 0 (uncompressed) and the page is mappable and not checksummed, the returned sealed page
137 /// will point directly to the input page buffer. Otherwise, the sealed page references fSealPageBuffer. Thus,
138 /// the buffer pointed to by the RSealedPage should never be freed.
140
141 virtual void InitImpl(RNTupleModel &model) = 0;
143
144public:
145 /// Cluster that was staged, but not yet logically appended to the RNTuple
158
159 /// Parameters for the SealPage() method
161 const ROOT::Internal::RPage *fPage = nullptr; ///< Input page to be sealed
163 nullptr; ///< Corresponds to the page's elements, for size calculation etc.
164 std::uint32_t fCompressionSettings = 0; ///< Compression algorithm and level to apply
165 /// Adds a 8 byte little-endian xxhash3 checksum to the page payload. The buffer has to be large enough to
166 /// to store the additional 8 bytes.
167 bool fWriteChecksum = true;
168 /// If false, the output buffer must not point to the input page buffer, which would otherwise be an option
169 /// if the page is mappable and should not be compressed
170 bool fAllowAlias = false;
171 /// Location for sealed output. The memory buffer has to be large enough.
172 void *fBuffer = nullptr;
173 }; // struct RSealPageConfig
174
175 /// An RAII wrapper used to synchronize a page sink. See GetSinkGuard().
177 std::mutex *fLock;
178
179 public:
180 explicit RSinkGuard(std::mutex *lock) : fLock(lock)
181 {
182 if (fLock != nullptr) {
183 fLock->lock();
184 }
185 }
186 RSinkGuard(const RSinkGuard &) = delete;
187 RSinkGuard &operator=(const RSinkGuard &) = delete;
188 RSinkGuard(RSinkGuard &&) = delete;
191 {
192 if (fLock != nullptr) {
193 fLock->unlock();
194 }
195 }
196 }; // class RPageSinkGuard
197
198 RPageSink(std::string_view ntupleName, const ROOT::RNTupleWriteOptions &options);
199
200 RPageSink(const RPageSink &) = delete;
201 RPageSink &operator=(const RPageSink &) = delete;
202 RPageSink(RPageSink &&) = default;
204 virtual ~RPageSink();
205
206 const std::string &GetNTupleName() const { return fNTupleName; }
208 bool IsInitialized() const { return fIsInitialized; }
210 /// Return the RNTupleDescriptor being constructed.
211 virtual const ROOT::RNTupleDescriptor &GetDescriptor() const = 0;
212
213 // Used in the buffered sink for parallel page compression
215
216 /// Physically creates the storage container to hold the ntuple (e.g., a keys a TFile or an S3 bucket)
217 /// Init() associates column handles to the columns referenced by the model
218 void Init(RNTupleModel &model)
219 {
220 if (fIsInitialized) {
221 throw RException(R__FAIL("already initialized"));
222 }
223 InitImpl(model);
224 fIsInitialized = true;
225 }
226
227 /// Seal a page using the provided info.
228 static RSealedPage SealPage(const RSealPageConfig &config);
229
230 /// Add a column belonging to a certain field to the descriptor and return its on-disk ID
232
233 /// Incorporate incremental changes to the model into the ntuple descriptor. This happens, e.g. if new fields were
234 /// added after the initial call to `RPageSink::Init(RNTupleModel &)`.
235 /// `firstEntry` specifies the global index for the first stored element in the added columns.
236 virtual void UpdateSchema(const ROOT::Internal::RNTupleModelChangeset &changeset, ROOT::NTupleSize_t firstEntry) = 0;
237 /// Adds an extra type information record to schema. The extra type information will be written to the
238 /// extension header. The information in the record will be merged with the existing information, e.g.
239 /// duplicate streamer info records will be removed. This method is called by the "on commit dataset" callback
240 /// registered by specific fields (e.g., streamer field) and during merging.
241 virtual void UpdateExtraTypeInfo(const ROOT::RExtraTypeInfoDescriptor &extraTypeInfo) = 0;
242
243 /// Commits a suppressed column for the current cluster. Can be called anytime before CommitCluster().
244 /// For any given column and cluster, there must be no calls to both CommitSuppressedColumn() and page commits.
245 virtual void CommitSuppressedColumn(DescriptorId_t physicalColumnId) = 0;
246 /// Write a page to the storage. The column must have been added before.
247 virtual void
248 CommitPage(DescriptorId_t physicalColumnId, const RColumnElementBase &elem, const ROOT::Internal::RPage &page) = 0;
249 /// Write a preprocessed page to storage. The column must have been added before.
250 virtual void CommitSealedPage(ROOT::DescriptorId_t physicalColumnId, const RSealedPage &sealedPage) = 0;
251 /// Write a vector of preprocessed pages to storage. The corresponding columns must have been added before.
252 virtual void CommitSealedPageV(std::span<RSealedPageGroup> ranges) = 0;
253 /// Stage the current cluster and create a new one for the following data.
254 /// Returns the object that must be passed to CommitStagedClusters to logically append the staged cluster to the
255 /// ntuple descriptor.
257 /// Commit staged clusters, logically appending them to the ntuple descriptor.
258 virtual void CommitStagedClusters(std::span<RStagedCluster> clusters) = 0;
259 /// Finalize the current cluster and create a new one for the following data.
260 /// Returns the number of bytes written to storage (excluding metadata).
261 virtual std::uint64_t CommitCluster(ROOT::NTupleSize_t nNewEntries)
262 {
263 RStagedCluster stagedClusters[] = {StageCluster(nNewEntries)};
264 CommitStagedClusters(stagedClusters);
265 return stagedClusters[0].fNBytesWritten;
266 }
267 /// Write out the page locations (page list envelope) for all the committed clusters since the last call of
268 /// CommitClusterGroup (or the beginning of writing).
269 virtual void CommitClusterGroup() = 0;
270
271 /// Creates a new sink with the same underlying storage as this but writing to a different
272 /// RNTuple named `name`. Only one of the two sinks can safely write at the same time.
273 /// The RNTuple written by this cloned sink will be stored in a hidden key (this is a convenient assumption we
274 /// make now since this method is only used to create attribute RNTuples).
275 virtual std::unique_ptr<RPageSink> CloneAsHidden(std::string_view name, const RNTupleWriteOptions &opts) const = 0;
276
277 /// Adds the given anchor information (name + locator) into the main RNTuple's descriptor as an attribute set
278 /// linked to it with the given name.
279 /// The attribute set must have already been written to storage via RNTupleAttrSetWriter::Commit().
280 /// Note that, by RNTuple specs, this is only legal to call on a non-attribute RNTuple's sink.
281 virtual void CommitAttributeSet(std::string_view attrSetName, const RNTupleLink &attrAnchorInfo) = 0;
282
283 /// The registered callback is executed at the beginning of CommitDataset();
285 /// Run the registered callbacks and finalize the current cluster and the entrire data set.
287
288 /// Get a new, empty page for the given column that can be filled with up to nElements;
289 /// nElements must be larger than zero.
290 virtual ROOT::Internal::RPage ReservePage(RWriteColumn &column, std::size_t nElements);
291
293 {
294 // By default, there is no lock and the guard does nothing.
295 return RSinkGuard(nullptr);
296 }
297}; // class RPageSink
298
299// clang-format off
300/**
301\class ROOT::Internal::RPagePersistentSink
302\ingroup NTuple
303\brief Base class for a sink with a physical storage backend
304
305Call RNTupleWriter::CommitDataset() explicitly rather than relying on the writer's destructor. A destructor
306cannot throw, so if committing fails there the error is only logged and the ntuple may be left incomplete
307on storage.
308*/
309// clang-format on
311private:
312 /// Used to map the IDs of the descriptor to the physical IDs issued during header/footer serialization
314
315 /// Remembers the starting cluster id for the next group. Used also to check if there are new clusters to commit
316 /// for a cluster group (otherwise committing a cluster group is a noop)
318 /// Keeps track of the number of pages so far committed in all the clusters of the current cluster group.
319 /// Used to automatically create a new cluster group once the user-defined threshold of pages per cluster is
320 /// surpassed.
322 /// Used to calculate the number of entries in the current cluster
324 /// Keeps track of the number of elements in the currently open cluster. Indexed by column id.
325 std::vector<ROOT::RClusterDescriptor::RColumnRange> fOpenColumnRanges;
326 /// Keeps track of the written pages in the currently open cluster. Indexed by column id.
327 std::vector<ROOT::RClusterDescriptor::RPageRange> fOpenPageRanges;
328
329 /// Union of the streamer info records that are sent from streamer fields to the sink before committing the dataset.
331
332protected:
333 /// Set of optional features supported by the persistent sink
334 struct RFeatures {
335 bool fCanMergePages = false;
336 };
337
340
341 /// Default I/O performance counters that get registered in fMetrics
351 std::unique_ptr<RCounters> fCounters;
352
353 /// Updates the descriptor and calls InitImpl() that handles the backend-specific details (file, DAOS, etc.)
354 void InitImpl(RNTupleModel &model) final;
355
356 virtual RNTupleLocator
357 CommitSealedPageImpl(ROOT::DescriptorId_t physicalColumnId, const RSealedPage &sealedPage) = 0;
358 /// Vector commit of preprocessed pages. The `ranges` array specifies a range of sealed pages to be
359 /// committed for each column. The returned vector contains, in order, the RNTupleLocator for each
360 /// page on each range in `ranges`, i.e. the first N entries refer to the N pages in `ranges[0]`,
361 /// followed by M entries that refer to the M pages in `ranges[1]`, etc.
362 /// The mask allows to skip writing out certain pages. The vector has the size of all the pages.
363 /// For every `false` value in the mask, the corresponding locator is skipped (missing) in the output vector.
364 /// The default is to call `CommitSealedPageImpl` for each page; derived classes may provide an
365 /// optimized implementation though.
366 virtual std::vector<RNTupleLocator>
367 CommitSealedPageVImpl(std::span<RSealedPageGroup> ranges, const std::vector<bool> &mask);
368 /// Returns the number of bytes written to storage (excluding metadata)
369 virtual std::uint64_t StageClusterImpl() = 0;
370
371 virtual void CommitHeaderImpl(const unsigned char *serializedHeader, std::uint32_t length) = 0;
372 /// Returns the locator of the page list envelope of the given buffer that contains the serialized page list.
373 /// Typically, the implementation takes care of compressing and writing the provided buffer.
374 virtual RNTupleLocator CommitClusterGroupImpl(unsigned char *serializedPageList, std::uint32_t length) = 0;
375 virtual RNTupleLink CommitDatasetImpl(unsigned char *serializedFooter, std::uint32_t length) = 0;
376
377 /// \return The locator and length of the written anchor.
379
380 /// Enables the default set of metrics provided by RPageSink. `prefix` will be used as the prefix for
381 /// the counters registered in the internal RNTupleMetrics object.
382 /// This set of counters can be extended by a subclass by calling `fMetrics.MakeCounter<...>()`.
383 ///
384 /// A subclass using the default set of metrics is always responsible for updating the counters
385 /// appropriately, e.g. `fCounters->fNPageCommited.Inc()`
386 void EnableDefaultMetrics(const std::string &prefix);
387
388public:
389 RPagePersistentSink(std::string_view ntupleName, const ROOT::RNTupleWriteOptions &options);
390
392 RPagePersistentSink &operator=(const RPagePersistentSink &) = delete;
394 RPagePersistentSink &operator=(RPagePersistentSink &&) = default;
395 ~RPagePersistentSink() override;
396
397 /// Guess the concrete derived page source from the location
398 static std::unique_ptr<RPageSink> Create(std::string_view ntupleName, std::string_view location,
399 const ROOT::RNTupleWriteOptions &options = ROOT::RNTupleWriteOptions());
400
401 DescriptorId_t AddColumn(ROOT::DescriptorId_t fieldId, const ROOT::Internal::RColumn &column) final;
402
404
406
407 void UpdateSchema(const ROOT::Internal::RNTupleModelChangeset &changeset, ROOT::NTupleSize_t firstEntry) override;
408 void UpdateExtraTypeInfo(const ROOT::RExtraTypeInfoDescriptor &extraTypeInfo) final;
409
410 /// Initialize sink based on an existing descriptor and fill into the descriptor builder, optionally copying over
411 /// the descriptor's clusters to this sink's descriptor.
412 /// \return The model created from the new sink's descriptor. This model should be kept alive
413 /// for at least as long as the sink.
414 [[nodiscard]] std::unique_ptr<RNTupleModel>
415 InitFromDescriptor(const ROOT::RNTupleDescriptor &descriptor, bool copyClusters);
416
417 /// Adds a new column representation to the given field. It is NOT marked as suppressed.
418 /// The first element index of the added column will be computed as the sum of the first element index of the
419 /// 0th representation's column range plus `addedFirstElementIndex` (which must be non-negative).
420 /// This can only be legally done at cluster boundary (i.e. immediately after committing a cluster or before
421 /// writing any entry). This is NOT checked for you.
422 /// `newRepresentation` must have a number of elements equal to the field's cardinality and must contain
423 /// compatible column types.
424 /// NOTE: this function was designed for use by the Merger and it's not fit as-is for use with the higher level
425 /// API layers. In other words, you cannot use this with a Writer and write data through the regular Entry/Field
426 /// API, as this function only modifies the descriptor.
427 /// \return The physical id of the first newly added column.
429 std::span<const ROOT::Internal::RColumnFormat> newRepresentation,
430 std::uint64_t clusterOffset);
431
432 /// Adds a new alias column pointing to an existing column with the given physical id to the given field.
434 ROOT::DescriptorId_t physicalId);
435
436 void CommitSuppressedColumn(DescriptorId_t physicalColumnId) final;
437 void
438 CommitPage(DescriptorId_t physicalColumnId, const RColumnElementBase &elem, const ROOT::Internal::RPage &page) final;
439 void CommitSealedPage(ROOT::DescriptorId_t physicalColumnId, const RSealedPage &sealedPage) final;
440 void CommitSealedPageV(std::span<RSealedPageGroup> ranges) final;
441 RStagedCluster StageCluster(ROOT::NTupleSize_t nNewEntries) final;
442 void CommitStagedClusters(std::span<RStagedCluster> clusters) final;
443 void CommitClusterGroup() final;
444 void CommitAttributeSet(std::string_view attrSetName, const RNTupleLink &attrAnchorInfo) final;
445}; // class RPagePersistentSink
446
447// clang-format off
448/**
449\class ROOT::Internal::RPageSource
450\ingroup NTuple
451\brief Abstract interface to read data from an ntuple
452
453The page source is initialized with the columns of interest. Alias columns from projected fields are mapped to the
454corresponding physical columns. Pages from the columns of interest can then be mapped into memory.
455The page source also gives access to the ntuple's metadata.
456*/
457// clang-format on
459 // Decompress pages smaller than 4kB directly in the main thread, not in a TBB thread
460 static constexpr std::size_t kInlineDecompressionThreshold = 4096;
461
462 /// Summarizes meta-data necessary to load a certain page. Used by LoadPageFromSummary().
466 /// The first element number of the page's column in the given cluster
467 std::uint64_t fColumnOffset = 0;
468 /// Location of the page on disk
470 };
471
472public:
473 /// Used in SetEntryRange / GetEntryRange
474 struct REntryRange {
476 ROOT::NTupleSize_t fNEntries = 0;
477
478 /// Returns true if the given cluster has entries within the entry range
479 bool IntersectsWith(const ROOT::RClusterDescriptor &clusterDesc) const;
480 };
481
482 /// An RAII wrapper used for the read-only access to `RPageSource::fDescriptor`. See `GetExclDescriptorGuard()``.
484 const ROOT::RNTupleDescriptor *fDescriptor = nullptr;
485 std::shared_mutex *fLock = nullptr;
486
487 public:
489 RSharedDescriptorGuard(const ROOT::RNTupleDescriptor &desc, std::shared_mutex &lock)
490 : fDescriptor(&desc), fLock(&lock)
491 {
492 fLock->lock_shared();
493 }
497 {
498 std::swap(fDescriptor, other.fDescriptor);
499 std::swap(fLock, other.fLock);
500 }
502 {
503 if (this == &other)
504 return *this;
505 std::swap(fDescriptor, other.fDescriptor);
506 std::swap(fLock, other.fLock);
507 return *this;
508 }
510 {
511 if (IsValid())
512 Release();
513 }
514 const ROOT::RNTupleDescriptor *operator->() const { return fDescriptor; }
515 const ROOT::RNTupleDescriptor &GetConstRef() const { return *fDescriptor; }
516 bool IsValid() const { return fLock; }
517 void Release()
518 {
519 fLock->unlock_shared();
520 fLock = nullptr;
521 fDescriptor = nullptr;
522 }
523 };
524
525 /// An RAII wrapper used for the writable access to `RPageSource::fDescriptor`. See `GetSharedDescriptorGuard()`.
527 ROOT::RNTupleDescriptor *fDescriptor = nullptr;
528 std::shared_mutex *fLock = nullptr;
529
530 public:
532 RExclDescriptorGuard(ROOT::RNTupleDescriptor &desc, std::shared_mutex &lock) : fDescriptor(&desc), fLock(&lock)
533 {
534 fLock->lock();
535 }
539 {
540 std::swap(fDescriptor, other.fDescriptor);
541 std::swap(fLock, other.fLock);
542 }
544 {
545 if (this == &other)
546 return *this;
547 std::swap(fDescriptor, other.fDescriptor);
548 std::swap(fLock, other.fLock);
549 return *this;
550 }
552 {
553 if (IsValid())
554 Release();
555 }
556 ROOT::RNTupleDescriptor &operator*() const { return *fDescriptor; }
557 ROOT::RNTupleDescriptor *operator->() const { return fDescriptor; }
558 void MoveIn(ROOT::RNTupleDescriptor desc) { *fDescriptor = std::move(desc); }
559 bool IsValid() const { return fLock; }
560 void Release()
561 {
562 fDescriptor->IncGeneration();
563 fLock->unlock();
564 fLock = nullptr;
565 fDescriptor = nullptr;
566 }
567 };
568
569 /// Either a shared or an exclusive lock guard
571 private:
572 std::variant<RSharedDescriptorGuard, RExclDescriptorGuard> fAnyGuard;
573
574 public:
575 RAnyDescriptorGuard(RSharedDescriptorGuard sharedGuard) : fAnyGuard(std::move(sharedGuard)) {}
576 RAnyDescriptorGuard(RExclDescriptorGuard exclGuard) : fAnyGuard(std::move(exclGuard)) {}
580 // The descriptor guards are subject to removal, thus silence the clang-tidy warning for the next line for now
581 RAnyDescriptorGuard &operator=(RAnyDescriptorGuard &&) = default; // NOLINT(bugprone-exception-escape)
583
585 {
586 return (fAnyGuard.index() == 0) ? std::get<0>(fAnyGuard).GetConstRef() : std::get<1>(fAnyGuard).operator*();
587 }
589 {
590 return (fAnyGuard.index() == 0) ? std::get<0>(fAnyGuard).operator->() : std::get<1>(fAnyGuard).operator->();
591 }
592 bool IsValid() const
593 {
594 return (fAnyGuard.index() == 0) ? std::get<0>(fAnyGuard).IsValid() : std::get<1>(fAnyGuard).IsValid();
595 }
596 void Release()
597 {
598 if (fAnyGuard.index() == 0)
599 std::get<0>(fAnyGuard).Release();
600 else
601 std::get<1>(fAnyGuard).Release();
602 }
603 };
604
605private:
606 /// Keeps track of the requested physical column IDs and their in-memory target type via a column element identifier.
607 /// When using alias columns (projected fields), physical columns may be requested multiple times.
609 public:
614
615 private:
616 /// Maps physical column IDs to all the requested in-memory representations.
617 /// A pair of physical column ID and in-memory representation can be requested multiple times, which is
618 /// indicated by the reference counter.
619 /// We can only have a handful of possible in-memory representations for a given column,
620 /// so it is fine to search them linearly.
621 std::unordered_map<ROOT::DescriptorId_t, std::vector<RColumnInfo>> fColumnInfos;
622
623 public:
624 void Insert(ROOT::DescriptorId_t physicalColumnId, ROOT::Internal::RColumnElementBase::RIdentifier elementId);
625 void Erase(ROOT::DescriptorId_t physicalColumnId, ROOT::Internal::RColumnElementBase::RIdentifier elementId);
626 ROOT::Internal::RCluster::ColumnSet_t ToColumnSet() const;
627 bool HasColumnInfos(ROOT::DescriptorId_t physicalColumnId) const
628 {
629 return fColumnInfos.count(physicalColumnId) > 0;
630 }
631 const std::vector<RColumnInfo> &GetColumnInfos(ROOT::DescriptorId_t physicalColumnId) const
632 {
633 return fColumnInfos.at(physicalColumnId);
634 }
635 };
636
639 mutable std::shared_mutex fDescriptorLock;
640 REntryRange fEntryRange; ///< Used by the cluster pool to prevent reading beyond the given range
641 bool fHasStructure = false; ///< Set to true once `LoadStructure()` is called
642 bool fIsAttached = false; ///< Set to true once `Attach()` is called
643 bool fHasStreamerInfosRegistered = false; ///< Set to true when RegisterStreamerInfos() is called.
644 RNTupleTaskScheduler *fTaskScheduler = nullptr; ///< For parallel page decompression
645
646 /// The interpretation of page lists, set in Attach()
649
650 /// This vector is aligned with the cluster groups in the descriptor. It stores the cumulative number of clusters
651 /// in the cluster groups. Given a cluster ID, we can thus quickly determine the cluster group that the cluster
652 /// comes from. While descriptor IDs in a descriptor in general are arbitrary, for the descriptor in the page source,
653 /// that was created from a serialized on-disk representation, we know that cluster and cluster group IDs are
654 /// issued consecutively.
655 std::vector<NTupleSize_t> fCumulativeClusterCounts;
656
657 /// The active columns are implicitly defined by the model fields or views
659
660 /// The cluster pool asynchronously preloads the next few clusters. Note that derived classes should call
661 /// StopClusterPoolBackgroundThread() in their destructor so that the I/O background thread does not call
662 /// methods from the destructed derived class.
664 /// The last cluster from which a page got loaded. Points into fClusterPool->fPool
665 ROOT::Internal::RCluster *fCurrentCluster = nullptr;
666 /// Pages that are unzipped with IMT are staged into the page pool
668
669 /// Remembers the last cluster id from which a page was requested
671 /// Clusters from where pages got preloaded in UnzipCluster(), ordered by first entry number
672 /// of the clusters. If the last used cluster changes in LoadPage(), all unused pages from
673 /// previous clusters are evicted from the page pool. Pinned clusters won't be evicted.
674 std::map<ROOT::NTupleSize_t, ROOT::DescriptorId_t> fPreloadedClusters;
675
676 /// Pinned clusters and their $2 * (cluster bunch size) - 1$ successors will not be evicted from the cluster pool.
677 /// Pages of pinned clusters won't be evicted from the page pool.
678 std::unordered_set<ROOT::DescriptorId_t> fPinnedClusters;
679 /// Reference counted map of pinned cluster groups. This map is edited by PinCluster() and UnpinCluster()
680 /// and stores the number of pinned clusters in a certain cluster group. We use a map because we iterate the sorted
681 /// list of cluster group IDs in the element-wise FindClusterId().
682 std::map<ROOT::DescriptorId_t, std::size_t> fPinnedClusterGroups;
683 /// List of loaded cluster groups, ordered by last access. The size of the list is usually bounded by the
684 /// page list budget in the read options. Pinned cluster groups can cause overspending of the budget.
685 /// We except a small number of loaded cluster groups, thus we accept O(n) complexity to edit this list.
686 std::deque<ROOT::DescriptorId_t> fClusterGroupAccessSequence;
687
688 /// Ensures that fDescriptor has cluster details loaded for the given cluster group ID. This method is expected
689 /// to be called while holding the lock passed by descGuard. The returned descriptor guard is either the
690 /// passed one or a new, exclusive guard if cluster details needed to be loaded.
691 RAnyDescriptorGuard EnsureClusterDetails(DescriptorId_t cgId, RAnyDescriptorGuard descGuard);
692 /// Uses binary search in fCumulativeClusterCounts to determine the cluster group that the cluster ID belongs in.
693 DescriptorId_t FindClusterGroupId(DescriptorId_t clusterId) const;
694
695 /// Does nothing if fLastUsedCluster == clusterId. Otherwise, updated fLastUsedCluster
696 /// and evict unused paged from the page pool of all previous clusters.
697 /// Must not be called when the descriptor guard is taken.
698 void UpdateLastUsedCluster(ROOT::DescriptorId_t clusterId);
699
700 // Populate the cluster details of the given cluster group. Must hold an exclusive descriptor lock when calling.
701 // No-op if the cluster details are already present.
702 void LoadPageList(DescriptorId_t clusterGroupId, const RExclDescriptorGuard &exclGuard);
703 // Common treatment of zero pages in LoadPageFromSummary()
704 ROOT::Internal::RPageRef LoadZeroPage(const RPageSummary &pageSummary, const RColumnElementBase &elem);
705 // Once the page is found to be missing in the page cache and all information about the page is collected,
706 // either using a global or a local element index, perform the common page loading tasks using the page summary.
707 // This includes zero page handling and prefetching the corresponding cluster.
708 ROOT::Internal::RPageRef LoadPageFromSummary(const RPageSummary &pageSummary, const RColumnElementBase &elem);
709
710protected:
711 /// Holds the uncompressed header and footer
713 std::unique_ptr<unsigned char[]> fBuffer; ///< single buffer for both header and footer
714 void *fPtrHeader = nullptr; ///< either nullptr or points into fBuffer
715 void *fPtrFooter = nullptr; ///< either nullptr or points into fBuffer
716
717 /// Called at the end of Attach(), i.e. when the header and footer are processed
718 void Reset()
719 {
720 RStructureBuffer empty;
721 std::swap(empty, *this);
722 }
723 };
724
725 /// Default I/O performance counters that get registered in `fMetrics`
745
746 std::string fNTupleName; ///< Initially empty if the page source is created from an anchor
747 std::unique_ptr<RCounters> fCounters;
748 RStructureBuffer fStructureBuffer; ///< Populated by LoadStructureImpl(), reset at the end of Attach()
749
752
753 /// Fills fStructureBuffer with the compressed header and footer
754 virtual void LoadStructureImpl() = 0;
755 /// `LoadStructureImpl()` has been called before `AttachImpl()` is called
757 /// Returns a new, unattached page source for the same data set. If the origin data source was attached, the
758 /// base class Clone() method will as an optimization not call LoadStructureImpl() and AttachImpl() again
759 /// but simply clone the existing descriptor. This means that CloneImpl(), for an attached page source, needs to
760 /// redo any operation other than loading the descriptor that may be done in LoadStructureImpl() and AttachImpl().
761 virtual std::unique_ptr<RPageSource> CloneImpl() const = 0;
762 // Loads a page list into the provided buffer. The buffer parameter needs to point to a memory region
763 // that has space for at least locator.GetNBytesOnStorage() bytes to hold the compressed page list.
764 virtual void LoadPageListImpl(const RNTupleLocator &locator, unsigned char *buffer) = 0;
765 // Returns a sealed page from storage without adding it to the page pool. The sealed pages buffer and buffer size
766 // is already initialized.
767 virtual void LoadSealedPageImpl(const RNTupleLocator &locator, RSealedPage &sealedPage) = 0;
768
769 /// Prepare a page range read for the column set in `clusterKey`. Specifically, pages referencing the
770 /// `kTypePageZero` locator are filled in `pageZeroMap`; otherwise, `perPageFunc` is called for each page. This is
771 /// commonly used as part of `LoadClusters()` in derived classes.
772 void PrepareLoadCluster(const ROOT::Internal::RCluster::RKey &clusterKey,
774 const std::function<void(ROOT::DescriptorId_t, ROOT::NTupleSize_t,
775 const ROOT::RClusterDescriptor::RPageInfo &)> &perPageFunc);
776
777 /// Enables the default set of metrics provided by RPageSource. `prefix` will be used as the prefix for
778 /// the counters registered in the internal RNTupleMetrics object.
779 /// A subclass using the default set of metrics is responsible for updating the counters
780 /// appropriately, e.g. `fCounters->fNRead.Inc()`
781 /// Alternatively, a subclass might provide its own RNTupleMetrics object by overriding the
782 /// `GetMetrics()` member function.
783 void EnableDefaultMetrics(const std::string &prefix);
784
785 /// Note that the underlying lock is not recursive. See `GetSharedDescriptorGuard()` for further information.
786 RExclDescriptorGuard GetExclDescriptorGuard() { return RExclDescriptorGuard(fDescriptor, fDescriptorLock); }
787
788 // To be called in the destructor of derived classes
790
791public:
792 RPageSource(std::string_view ntupleName, const ROOT::RNTupleReadOptions &fOptions);
793 RPageSource(const RPageSource &) = delete;
797 virtual ~RPageSource();
798 /// Guess the concrete derived page source from the file name (location)
799 static std::unique_ptr<RPageSource> Create(std::string_view ntupleName, std::string_view location,
801 /// Open the same storage multiple time, e.g. for reading in multiple threads.
802 /// If the source is already attached, the clone will be attached, too. The clone will use, however,
803 /// it's own connection to the underlying storage (e.g., file descriptor, XRootD handle, etc.)
804 std::unique_ptr<RPageSource> Clone() const;
805
806 /// Helper for unstreaming a page. This is commonly used in derived, concrete page sources. The implementation
807 /// currently always makes a memory copy, even if the sealed page is uncompressed and in the final memory layout.
808 /// The optimization of directly mapping pages is left to the concrete page source implementations.
809 RResult<ROOT::Internal::RPage> static UnsealPage(const RSealedPage &sealedPage,
812
813 const std::string GetNTupleName() const { return fNTupleName; }
816
817 void SetTaskScheduler(RNTupleTaskScheduler *taskScheduler) { fTaskScheduler = taskScheduler; }
818
819 /// Takes the read lock for the descriptor. Multiple threads can take the lock concurrently.
820 /// The underlying `std::shared_mutex`, however, is neither read nor write recursive:
821 /// within one thread, only one lock (shared or exclusive) must be acquired at the same time. This requires special
822 /// care in sections protected by `GetSharedDescriptorGuard()` and `GetExclDescriptorGuard()` especially to avoid
823 /// that the locks are acquired indirectly. As a general guideline, no other
824 /// method of the page source should be called (directly or indirectly) in a guarded section.
826 {
827 return RSharedDescriptorGuard(fDescriptor, fDescriptorLock);
828 }
829
830 // Get the on-disk of the given column and make it part of the set of active columns
832 void DropColumn(const ROOT::Internal::RColumn &column);
833
834 /// Loads header and footer without decompressing or deserializing them. This can be used to asynchronously open
835 /// a file in the background. The method is idempotent and it is called as a first step in `Attach()`.
836 /// Pages sources may or may not make use of splitting loading and processing metadata.
837 /// Therefore, `LoadStructure()` may do nothing and defer loading the metadata to `Attach()`.
838 void LoadStructure();
839 /// Open the physical storage container and deserialize header and footer
842 /// Load all remaining cluster details
843 void LoadAllPageLists();
844
845 ROOT::NTupleSize_t GetNEntries();
846 ROOT::NTupleSize_t GetNElements(ROOT::DescriptorId_t physicalColumnId);
847 /// Returns a shared descriptor guard to ensure that the returned cluster id is useable, i.e. that the
848 /// corresponding cluster was not meanwhile evicted from the set of active clusters.
849 RAnyDescriptorGuard
850 FindClusterId(ROOT::DescriptorId_t physicalColumnId, ROOT::NTupleSize_t index, ROOT::DescriptorId_t &cid);
851 /// An overload of FindClusterId that searches using a certain column element index.
852 RAnyDescriptorGuard FindClusterId(ROOT::NTupleSize_t entryIdx, ROOT::DescriptorId_t &cid);
853 /// Uses FindClusterId to search for the cluster with the entry index following the last entry index of the
854 /// given cluster.
855 RAnyDescriptorGuard FindNextClusterId(ROOT::DescriptorId_t clusterId, ROOT::DescriptorId_t &nextId);
856
857 /// Promise to only read from the given entry range. If set, prevents the cluster pool from reading-ahead beyond
858 /// the given range. The range needs to be within `[0, GetNEntries())`.
859 void SetEntryRange(const REntryRange &range);
860 REntryRange GetEntryRange() const { return fEntryRange; }
861
862 /// Allocates and fills a page that contains the index-th element. Calls into the concrete page source
863 /// for loading the corresponding sealed page of cluster where necessary.
864 /// Returns a default-constructed RPage for suppressed columns.
866 LoadPage(DescriptorId_t physicalColumnId, const RColumnElementBase &elem, ROOT::NTupleSize_t globalIndex);
867 /// Another version of `LoadPage` that allows to specify cluster-relative indexes.
868 /// Returns a default-constructed RPage for suppressed columns.
870 LoadPage(DescriptorId_t physicalColumnId, const RColumnElementBase &elem, RNTupleLocalIndex localIndex);
871
872 /// Read the packed and compressed bytes of a page into the memory buffer provided by `sealedPage`. The sealed page
873 /// can be used subsequently in a call to `RPageSink::CommitSealedPage`.
874 /// The `fSize` and `fNElements` member of the sealedPage parameters are always set. If `sealedPage.fBuffer` is
875 /// `nullptr`, no data will be copied but the returned size information can be used by the caller to allocate a large
876 /// enough buffer and call `LoadSealedPage` again.
877 void LoadSealedPage(ROOT::DescriptorId_t physicalColumnId, RNTupleLocalIndex localIndex, RSealedPage &sealedPage);
878
879 /// Populates all the pages of the given cluster ids and columns; it is possible that some columns do not
880 /// contain any pages. The page source may load more columns than the minimal necessary set from `columns`.
881 /// To indicate which columns have been loaded, `LoadClusters()`` must mark them with `SetColumnAvailable()`.
882 /// That includes the ones from the `columns` that don't have pages; otherwise subsequent requests
883 /// for the cluster would assume an incomplete cluster and trigger loading again.
884 /// `LoadClusters()` is typically called from the I/O thread of a cluster pool, i.e. the method runs
885 /// concurrently to other methods of the page source.
886 virtual std::vector<std::unique_ptr<ROOT::Internal::RCluster>>
887 LoadClusters(std::span<ROOT::Internal::RCluster::RKey> clusterKeys) = 0;
888
889 /// Parallel decompression and unpacking of the pages in the given cluster. The unzipped pages are supposed
890 /// to be preloaded in a page pool attached to the source. The method is triggered by the cluster pool's
891 /// unzip thread. It is an optional optimization, the method can safely do nothing. In particular, the
892 /// unzipping will only run if a task scheduler is set. In practice, a task scheduler is set if
893 /// implicit multi-threading is turned on.
894 void UnzipCluster(ROOT::Internal::RCluster *cluster);
895
896 /// Instructs the cluster pool and page pool to consider the given cluster as active (should stay cached).
897 void PinCluster(ROOT::DescriptorId_t clusterId);
898 /// Allows the given cluster to be evicted from the cluster pool and page pool.
899 void UnpinCluster(ROOT::DescriptorId_t clusterId);
900 const std::unordered_set<ROOT::DescriptorId_t> &GetPinnedClusters() const { return fPinnedClusters; }
901
902 // TODO(gparolini): for symmetry with SealPage(), we should either make this private or SealPage() public.
904 UnsealPage(const RSealedPage &sealedPage, const ROOT::Internal::RColumnElementBase &element);
905
906 /// Builds the streamer info records from the descriptor's extra type info section. This is necessary when
907 /// connecting streamer fields so that emulated classes can be read.
908 void RegisterStreamerInfos();
909
910 /// Creates a new PageSource using the same underlying file as this but referring to a different RNTuple,
911 /// described by `anchorLink`.
912 virtual std::unique_ptr<RPageSource> OpenWithDifferentAnchor(const ROOT::Internal::RNTupleLink &anchorLink,
913 const ROOT::RNTupleReadOptions &options = {}) = 0;
914}; // class RPageSource
915
916} // namespace Internal
917} // namespace ROOT
918
919#endif
Interpolation descriptor
Definition HS3Parser.cxx:37
#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
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 index
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h length
Option_t Option_t TPoint TPoint const char mode
char name[80]
Definition TGX11.cxx:142
A thread-safe integral performance counter.
A metric element that computes its floating point value from other counters.
A collection of Counter objects with a name, a unit, and a description.
Managed a set of clusters containing compressed and packed pages.
void StopBackgroundThread()
Stop the I/O background thread. No-op if already stopped. Called by the destructor.
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
A column element encapsulates the translation between basic C++ types and their column representation...
A column is a storage-backed array of a simple, fixed-size type, from which pages can be mapped into ...
Definition RColumn.hxx:40
A helper class for piece-wise construction of an RNTupleDescriptor.
The serialization context is used for the piecewise serialization of a descriptor.
std::map< Int_t, TVirtualStreamerInfo * > StreamerInfoMap_t
@ kForReading
Deserializes the descriptor and performs fixup on the suppressed column ranges and on clusters,...
@ kRaw
Deserializes the descriptor as-is without performing any additional fixup.
The interface of a task scheduler to schedule page (de)compression tasks.
A memory region that contains packed and compressed pages.
Definition RCluster.hxx:98
Uses standard C++ memory allocation for the column data pages.
Abstract interface to allocate and release pages.
Base class for a sink with a physical storage backend.
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,...
ROOT::NTupleSize_t fNPagesInGroup
Keeps track of the number of pages so far committed in all the clusters of the current cluster group.
ROOT::NTupleSize_t fPrevGroupNClusters
Remembers the starting cluster id for the next group.
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...
ROOT::Internal::RNTupleDescriptorBuilder fDescriptorBuilder
void CommitSealedPageV(std::span< RSealedPageGroup > ranges) final
Write a vector of preprocessed pages to storage. The corresponding columns must have been added befor...
ROOT::NTupleSize_t GetNCommittedEntries() const
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.
ROOT::Internal::RNTupleSerializer::RContext fSerializationContext
Used to map the IDs of the descriptor to the physical IDs issued during header/footer serialization.
ROOT::NTupleSize_t fPrevClusterNEntries
Used to calculate the number of entries in the current cluster.
virtual RNTupleLink CommitDatasetImpl(unsigned char *serializedFooter, std::uint32_t length)=0
virtual RNTupleLocator CommitClusterGroupImpl(unsigned char *serializedPageList, std::uint32_t length)=0
Returns the locator of the page list envelope of the given buffer that contains the serialized page l...
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,...
std::vector< ROOT::RClusterDescriptor::RPageRange > fOpenPageRanges
Keeps track of the written pages in the currently open cluster. Indexed by column id.
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.
const ROOT::RNTupleDescriptor & GetDescriptor() const final
Return the RNTupleDescriptor being constructed.
std::vector< ROOT::RClusterDescriptor::RColumnRange > fOpenColumnRanges
Keeps track of the number of elements in the currently open cluster. Indexed by column id.
std::unique_ptr< RCounters > fCounters
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.
virtual RNTupleLocator CommitSealedPageImpl(ROOT::DescriptorId_t physicalColumnId, const RSealedPage &sealedPage)=0
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.
virtual void CommitHeaderImpl(const unsigned char *serializedHeader, std::uint32_t length)=0
ROOT::Internal::RNTupleSerializer::StreamerInfoMap_t fInfosOfStreamerFields
Union of the streamer info records that are sent from streamer fields to the sink before committing t...
void CommitSealedPage(ROOT::DescriptorId_t physicalColumnId, const RSealedPage &sealedPage) final
Write a preprocessed page to storage. The column must have been added before.
virtual std::uint64_t StageClusterImpl()=0
Returns the number of bytes written to storage (excluding metadata)
A thread-safe cache of pages loaded from the page source.
Definition RPagePool.hxx:48
Reference to a page stored in the page pool.
An RAII wrapper used to synchronize a page sink. See GetSinkGuard().
RSinkGuard & operator=(const RSinkGuard &)=delete
RSinkGuard & operator=(RSinkGuard &&)=delete
RSinkGuard(const RSinkGuard &)=delete
Abstract interface to write data into an ntuple.
virtual RNTupleLink CommitDatasetImpl()=0
RPageSink(RPageSink &&)=default
RNTupleLink CommitDataset()
Run the registered callbacks and finalize the current cluster and the entrire data set.
ROOT::Experimental::Detail::RNTupleMetrics & GetMetrics()
std::vector< unsigned char > fSealPageBuffer
Used as destination buffer in the simple SealPage overload.
virtual void CommitPage(DescriptorId_t physicalColumnId, const RColumnElementBase &elem, const ROOT::Internal::RPage &page)=0
Write a page to the storage. The column must have been added before.
std::unique_ptr< ROOT::RNTupleWriteOptions > fOptions
May contain a derived class of RNTupleWriteOptions.
std::vector< Callback_t > fOnDatasetCommitCallbacks
const ROOT::RNTupleWriteOptions & GetWriteOptions() const
virtual void CommitClusterGroup()=0
Write out the page locations (page list envelope) for all the committed clusters since the last call ...
virtual RStagedCluster StageCluster(ROOT::NTupleSize_t nNewEntries)=0
Stage the current cluster and create a new one for the following data.
virtual void CommitSealedPage(ROOT::DescriptorId_t physicalColumnId, const RSealedPage &sealedPage)=0
Write a preprocessed page to storage. The column must have been added before.
virtual void CommitSealedPageV(std::span< RSealedPageGroup > ranges)=0
Write a vector of preprocessed pages to storage. The corresponding columns must have been added befor...
RPageSink & operator=(const RPageSink &)=delete
RSealedPage SealPage(const ROOT::Internal::RPage &page, const ROOT::Internal::RColumnElementBase &element)
Helper for streaming a page.
void Init(RNTupleModel &model)
Physically creates the storage container to hold the ntuple (e.g., a keys a TFile or an S3 bucket) In...
virtual void UpdateExtraTypeInfo(const ROOT::RExtraTypeInfoDescriptor &extraTypeInfo)=0
Adds an extra type information record to schema.
virtual void CommitAttributeSet(std::string_view attrSetName, const RNTupleLink &attrAnchorInfo)=0
Adds the given anchor information (name + locator) into the main RNTuple's descriptor as an attribute...
ROOT::Experimental::Detail::RNTupleMetrics fMetrics
const std::string & GetNTupleName() const
RPageSink(const RPageSink &)=delete
virtual std::unique_ptr< RPageSink > CloneAsHidden(std::string_view name, const RNTupleWriteOptions &opts) const =0
Creates a new sink with the same underlying storage as this but writing to a different RNTuple named ...
virtual void CommitStagedClusters(std::span< RStagedCluster > clusters)=0
Commit staged clusters, logically appending them to the ntuple descriptor.
virtual void CommitSuppressedColumn(DescriptorId_t physicalColumnId)=0
Commits a suppressed column for the current cluster.
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...
virtual std::uint64_t CommitCluster(ROOT::NTupleSize_t nNewEntries)
Finalize the current cluster and create a new one for the following data.
virtual void InitImpl(RNTupleModel &model)=0
virtual RSinkGuard GetSinkGuard()
virtual DescriptorId_t AddColumn(ROOT::DescriptorId_t fieldId, const ROOT::Internal::RColumn &column)=0
Add a column belonging to a certain field to the descriptor and return its on-disk ID.
virtual void SetTaskScheduler(RNTupleTaskScheduler *)
std::function< void(RPageSink &)> Callback_t
virtual void UpdateSchema(const ROOT::Internal::RNTupleModelChangeset &changeset, ROOT::NTupleSize_t firstEntry)=0
Incorporate incremental changes to the model into the ntuple descriptor.
void RegisterOnCommitDatasetCallback(const Callback_t &cb)
The registered callback is executed at the beginning of CommitDataset();.
bool fIsInitialized
Flag if sink was initialized.
RPageSink(std::string_view ntupleName, const ROOT::RNTupleWriteOptions &options)
RPageSink & operator=(RPageSink &&)=default
virtual const ROOT::RNTupleDescriptor & GetDescriptor() const =0
Return the RNTupleDescriptor being constructed.
RPageAllocatorHeap fPageAllocator
RWritePageMemoryManager fWritePageMemoryManager
Used in ReservePage to maintain the page buffer budget.
Keeps track of the requested physical column IDs and their in-memory target type via a column element...
const std::vector< RColumnInfo > & GetColumnInfos(ROOT::DescriptorId_t physicalColumnId) const
std::unordered_map< ROOT::DescriptorId_t, std::vector< RColumnInfo > > fColumnInfos
Maps physical column IDs to all the requested in-memory representations.
bool HasColumnInfos(ROOT::DescriptorId_t physicalColumnId) const
Either a shared or an exclusive lock guard.
RAnyDescriptorGuard(RAnyDescriptorGuard &&)=default
RAnyDescriptorGuard(RExclDescriptorGuard exclGuard)
std::variant< RSharedDescriptorGuard, RExclDescriptorGuard > fAnyGuard
const ROOT::RNTupleDescriptor & GetConstRef() const
RAnyDescriptorGuard & operator=(RAnyDescriptorGuard &&)=default
const ROOT::RNTupleDescriptor * operator->() const
RAnyDescriptorGuard(RSharedDescriptorGuard sharedGuard)
RAnyDescriptorGuard(const RAnyDescriptorGuard &)=delete
RAnyDescriptorGuard & operator=(const RAnyDescriptorGuard &)=delete
An RAII wrapper used for the writable access to RPageSource::fDescriptor. See GetSharedDescriptorGuar...
ROOT::RNTupleDescriptor & operator*() const
void MoveIn(ROOT::RNTupleDescriptor desc)
RExclDescriptorGuard & operator=(const RExclDescriptorGuard &)=delete
ROOT::RNTupleDescriptor * operator->() const
RExclDescriptorGuard(RExclDescriptorGuard &&other)
RExclDescriptorGuard(ROOT::RNTupleDescriptor &desc, std::shared_mutex &lock)
RExclDescriptorGuard(const RExclDescriptorGuard &)=delete
RExclDescriptorGuard & operator=(RExclDescriptorGuard &&other)
An RAII wrapper used for the read-only access to RPageSource::fDescriptor. See GetExclDescriptorGuard...
RSharedDescriptorGuard(const RSharedDescriptorGuard &)=delete
const ROOT::RNTupleDescriptor & GetConstRef() const
RSharedDescriptorGuard(RSharedDescriptorGuard &&other)
RSharedDescriptorGuard & operator=(const RSharedDescriptorGuard &)=delete
const ROOT::RNTupleDescriptor * operator->() const
RSharedDescriptorGuard(const ROOT::RNTupleDescriptor &desc, std::shared_mutex &lock)
RSharedDescriptorGuard & operator=(RSharedDescriptorGuard &&other)
Abstract interface to read data from an ntuple.
ROOT::Internal::RClusterPool fClusterPool
The cluster pool asynchronously preloads the next few clusters.
const std::unordered_set< ROOT::DescriptorId_t > & GetPinnedClusters() const
RPageSource & operator=(RPageSource &&)=delete
ROOT::Experimental::Detail::RNTupleMetrics fMetrics
RPageSource & operator=(const RPageSource &)=delete
RExclDescriptorGuard GetExclDescriptorGuard()
Note that the underlying lock is not recursive. See GetSharedDescriptorGuard() for further informatio...
ROOT::RNTupleReadOptions fOptions
virtual void LoadPageListImpl(const RNTupleLocator &locator, unsigned char *buffer)=0
REntryRange GetEntryRange() const
std::map< ROOT::NTupleSize_t, ROOT::DescriptorId_t > fPreloadedClusters
Clusters from where pages got preloaded in UnzipCluster(), ordered by first entry number of the clust...
const std::string GetNTupleName() const
RSharedDescriptorGuard GetSharedDescriptorGuard() const
Takes the read lock for the descriptor.
REntryRange fEntryRange
Used by the cluster pool to prevent reading beyond the given range.
RStructureBuffer fStructureBuffer
Populated by LoadStructureImpl(), reset at the end of Attach()
std::string fNTupleName
Initially empty if the page source is created from an anchor.
virtual std::unique_ptr< RPageSource > CloneImpl() const =0
Returns a new, unattached page source for the same data set.
RPageAllocatorHeap fPageAllocator
virtual void LoadSealedPageImpl(const RNTupleLocator &locator, RSealedPage &sealedPage)=0
std::unique_ptr< RCounters > fCounters
std::unordered_set< ROOT::DescriptorId_t > fPinnedClusters
Pinned clusters and their $2 * (cluster bunch size) - 1$ successors will not be evicted from the clus...
virtual void LoadStructureImpl()=0
Fills fStructureBuffer with the compressed header and footer.
virtual ROOT::RNTupleDescriptor AttachImpl()=0
LoadStructureImpl() has been called before AttachImpl() is called
ROOT::RNTupleDescriptor fDescriptor
ROOT::Internal::RPagePool fPagePool
Pages that are unzipped with IMT are staged into the page pool.
std::vector< NTupleSize_t > fCumulativeClusterCounts
This vector is aligned with the cluster groups in the descriptor.
std::shared_mutex fDescriptorLock
ROOT::Experimental::Detail::RNTupleMetrics & GetMetrics()
std::map< ROOT::DescriptorId_t, std::size_t > fPinnedClusterGroups
Reference counted map of pinned cluster groups.
virtual std::vector< std::unique_ptr< ROOT::Internal::RCluster > > LoadClusters(std::span< ROOT::Internal::RCluster::RKey > clusterKeys)=0
Populates all the pages of the given cluster ids and columns; it is possible that some columns do not...
RPageSource(RPageSource &&)=delete
virtual std::unique_ptr< RPageSource > OpenWithDifferentAnchor(const ROOT::Internal::RNTupleLink &anchorLink, const ROOT::RNTupleReadOptions &options={})=0
Creates a new PageSource using the same underlying file as this but referring to a different RNTuple,...
RPageSource(const RPageSource &)=delete
const ROOT::RNTupleReadOptions & GetReadOptions() const
void SetTaskScheduler(RNTupleTaskScheduler *taskScheduler)
RActivePhysicalColumns fActivePhysicalColumns
The active columns are implicitly defined by the model fields or views.
std::deque< ROOT::DescriptorId_t > fClusterGroupAccessSequence
List of loaded cluster groups, ordered by last access.
A page is a slice of a column that is mapped into memory.
Definition RPage.hxx:43
Helper to maintain a memory budget for the write pages of a set of columns.
std::size_t fCurrentAllocatedBytes
Sum of all the write page sizes (their capacity) of the columns in fColumnsSortedByPageSize
std::size_t fMaxAllocatedBytes
Maximum allowed value for fCurrentAllocatedBytes, set from RNTupleWriteOptions::fPageBufferBudget.
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...
RWritePageMemoryManager(std::size_t maxAllocatedBytes)
std::set< RColumnInfo, std::greater< RColumnInfo > > fColumnsSortedByPageSize
All columns that called ReservePage() (hence TryUpdate()) at least once, sorted by their current writ...
bool TryUpdate(ROOT::Internal::RWriteColumn &column, std::size_t newWritePageSize)
Try to register the new write page size for the given column.
Records the partition of data into pages for a particular column in a particular cluster.
Metadata for RNTuple clusters.
Base class for all ROOT issued exceptions.
Definition RError.hxx:78
Field specific extra type information from the header / extenstion header.
Metadata stored for every field of an RNTuple.
The on-storage metadata of an RNTuple.
Addresses a column element or field item relative to a particular cluster, instead of a global NTuple...
Generic information about the physical location of data.
The RNTupleModel encapulates the schema of an RNTuple.
Common user-tunable settings for reading RNTuples.
Common user-tunable settings for storing RNTuples.
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
std::uint64_t DescriptorId_t
Distriniguishes elements of the same type within a descriptor, e.g. different fields.
constexpr NTupleSize_t kInvalidNTupleIndex
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
Every concrete RColumnElement type is identified by its on-disk type (column type) and the in-memory ...
The incremental changes to a RNTupleModel
Default I/O performance counters that get registered in fMetrics.
ROOT::Experimental::Detail::RNTupleAtomicCounter & fSzWritePayload
ROOT::Experimental::Detail::RNTupleTickCounter< ROOT::Experimental::Detail::RNTupleAtomicCounter > & fTimeCpuWrite
ROOT::Experimental::Detail::RNTupleAtomicCounter & fTimeWallWrite
ROOT::Experimental::Detail::RNTupleTickCounter< ROOT::Experimental::Detail::RNTupleAtomicCounter > & fTimeCpuZip
ROOT::Experimental::Detail::RNTupleAtomicCounter & fTimeWallZip
ROOT::Experimental::Detail::RNTupleAtomicCounter & fSzZip
ROOT::Experimental::Detail::RNTupleAtomicCounter & fNPageCommitted
Set of optional features supported by the persistent sink.
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.
ROOT::RClusterDescriptor::RPageRange fPageRange
Cluster that was staged, but not yet logically appended to the RNTuple.
std::vector< RColumnInfo > fColumnInfos
ROOT::Internal::RColumnElementBase::RIdentifier fElementId
Default I/O performance counters that get registered in fMetrics
ROOT::Experimental::Detail::RNTupleAtomicCounter & fNPageUnsealed
ROOT::Experimental::Detail::RNTupleAtomicCounter & fNRead
ROOT::Experimental::Detail::RNTupleAtomicCounter & fTimeWallRead
ROOT::Experimental::Detail::RNTupleAtomicCounter & fSzReadOverhead
ROOT::Experimental::Detail::RNTupleCalcPerf & fCompressionRatio
ROOT::Experimental::Detail::RNTupleCalcPerf & fFractionReadOverhead
ROOT::Experimental::Detail::RNTupleAtomicCounter & fNReadV
ROOT::Experimental::Detail::RNTupleAtomicCounter & fNClusterLoaded
ROOT::Experimental::Detail::RNTupleAtomicCounter & fTimeWallUnzip
ROOT::Experimental::Detail::RNTupleAtomicCounter & fNPageRead
ROOT::Experimental::Detail::RNTupleAtomicCounter & fSzReadPayload
ROOT::Experimental::Detail::RNTupleCalcPerf & fBandwidthReadCompressed
ROOT::Experimental::Detail::RNTupleTickCounter< ROOT::Experimental::Detail::RNTupleAtomicCounter > & fTimeCpuUnzip
ROOT::Experimental::Detail::RNTupleTickCounter< ROOT::Experimental::Detail::RNTupleAtomicCounter > & fTimeCpuRead
ROOT::Experimental::Detail::RNTupleCalcPerf & fBandwidthReadUncompressed
ROOT::Experimental::Detail::RNTupleCalcPerf & fBandwidthUnzip
ROOT::Experimental::Detail::RNTupleAtomicCounter & fSzUnzip
Used in SetEntryRange / GetEntryRange.
Summarizes meta-data necessary to load a certain page. Used by LoadPageFromSummary().
ROOT::RClusterDescriptor::RPageInfoExtended fPageInfo
Location of the page on disk.
Holds the uncompressed header and footer.
void Reset()
Called at the end of Attach(), i.e. when the header and footer are processed.
std::unique_ptr< unsigned char[]> fBuffer
single buffer for both header and footer
A sealed page contains the bytes of a page as written to storage (packed & compressed).
bool operator>(const RColumnInfo &other) const
Additional information about a page in an in-memory RPageRange.
Information about a single page in the context of a cluster's page range.