Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RPageStorage.hxx
Go to the documentation of this file.
1/// \file ROOT/RPageStorage.hxx
2/// \ingroup NTuple ROOT7
3/// \author Jakob Blomer <jblomer@cern.ch>
4/// \date 2018-07-19
5/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback
6/// is welcome!
7
8/*************************************************************************
9 * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
10 * All rights reserved. *
11 * *
12 * For the licensing terms see $ROOTSYS/LICENSE. *
13 * For the list of contributors see $ROOTSYS/README/CREDITS. *
14 *************************************************************************/
15
16#ifndef ROOT7_RPageStorage
17#define ROOT7_RPageStorage
18
19#include <ROOT/RError.hxx>
20#include <ROOT/RCluster.hxx>
27#include <ROOT/RNTupleUtil.hxx>
28#include <ROOT/RPage.hxx>
29#include <ROOT/RPagePool.hxx>
30#include <ROOT/RSpan.hxx>
31#include <string_view>
32
33#include <atomic>
34#include <cassert>
35#include <cstddef>
36#include <deque>
37#include <functional>
38#include <map>
39#include <memory>
40#include <mutex>
41#include <set>
42#include <shared_mutex>
43#include <unordered_map>
44#include <unordered_set>
45#include <vector>
46
47namespace ROOT {
48namespace Experimental {
49
50class RNTupleModel;
51
52namespace Internal {
53class RColumn;
54class RNTupleCompressor;
55struct RNTupleModelChangeset;
56class RPageAllocator;
57
58enum class EPageStorageType {
59 kSink,
60 kSource,
61};
62
63// clang-format off
64/**
65\class ROOT::Experimental::Internal::RPageStorage
66\ingroup NTuple
67\brief Common functionality of an ntuple storage for both reading and writing
68
69The RPageStore provides access to a storage container that keeps the bits of pages and clusters comprising
70an ntuple. Concrete implementations can use a TFile, a raw file, an object store, and so on.
71*/
72// clang-format on
74public:
75 /// The page checksum is a 64bit xxhash3
76 static constexpr std::size_t kNBytesPageChecksum = sizeof(std::uint64_t);
77
78 /// The interface of a task scheduler to schedule page (de)compression tasks
80 public:
81 virtual ~RTaskScheduler() = default;
82 /// Take a callable that represents a task
83 virtual void AddTask(const std::function<void(void)> &taskFunc) = 0;
84 /// Blocks until all scheduled tasks finished
85 virtual void Wait() = 0;
86 };
87
88 /// A sealed page contains the bytes of a page as written to storage (packed & compressed). It is used
89 /// as an input to UnsealPages() as well as to transfer pages between different storage media.
90 /// RSealedPage does _not_ own the buffer it is pointing to in order to not interfere with the memory management
91 /// of concrete page sink and page source implementations.
92 struct RSealedPage {
93 private:
94 const void *fBuffer = nullptr;
95 std::size_t fBufferSize = 0; ///< Size of the page payload and the trailing checksum (if available)
96 std::uint32_t fNElements = 0;
97 bool fHasChecksum = false; ///< If set, the last 8 bytes of the buffer are the xxhash of the rest of the buffer
98
99 public:
100 RSealedPage() = default;
101 RSealedPage(const void *buffer, std::size_t bufferSize, std::uint32_t nElements, bool hasChecksum = false)
103 {
104 }
105 RSealedPage(const RSealedPage &other) = default;
109
110 const void *GetBuffer() const { return fBuffer; }
111 void SetBuffer(const void *buffer) { fBuffer = buffer; }
112
118 std::size_t GetBufferSize() const { return fBufferSize; }
119 void SetBufferSize(std::size_t bufferSize) { fBufferSize = bufferSize; }
120
121 std::uint32_t GetNElements() const { return fNElements; }
122 void SetNElements(std::uint32_t nElements) { fNElements = nElements; }
123
124 bool GetHasChecksum() const { return fHasChecksum; }
126
127 void ChecksumIfEnabled();
129 /// Returns a failure if the sealed page has no checksum
131 };
132
133 using SealedPageSequence_t = std::deque<RSealedPage>;
134 /// A range of sealed pages referring to the same column that can be used for vector commit
137 SealedPageSequence_t::const_iterator fFirst;
138 SealedPageSequence_t::const_iterator fLast;
139
140 RSealedPageGroup() = default;
141 RSealedPageGroup(ROOT::DescriptorId_t d, SealedPageSequence_t::const_iterator b,
142 SealedPageSequence_t::const_iterator e)
144 {
145 }
146 };
147
148protected:
150
151 /// For the time being, we will use the heap allocator for all sources and sinks. This may change in the future.
152 std::unique_ptr<RPageAllocator> fPageAllocator;
153
154 std::string fNTupleName;
157 {
158 if (!fTaskScheduler)
159 return;
161 }
162
163public:
164 explicit RPageStorage(std::string_view name);
169 virtual ~RPageStorage();
170
171 /// Whether the concrete implementation is a sink or a source
173
176 RColumn *fColumn = nullptr;
177
178 /// Returns true for a valid column handle; fColumn and fPhysicalId should always either both
179 /// be valid or both be invalid.
180 explicit operator bool() const { return fPhysicalId != ROOT::kInvalidDescriptorId && fColumn; }
181 };
182 /// The column handle identifies a column with the current open page storage
184
185 /// Register a new column. When reading, the column must exist in the ntuple on disk corresponding to the meta-data.
186 /// When writing, every column can only be attached once.
188 /// Unregisters a column. A page source decreases the reference counter for the corresponding active column.
189 /// For a page sink, dropping columns is currently a no-op.
192
193 /// Returns the default metrics object. Subclasses might alternatively provide their own metrics object by
194 /// overriding this.
196
197 /// Returns the NTuple name.
198 const std::string &GetNTupleName() const { return fNTupleName; }
199
201}; // class RPageStorage
202
203// clang-format off
204/**
205\class ROOT::Experimental::Internal::RWritePageMemoryManager
206\ingroup NTuple
207\brief Helper to maintain a memory budget for the write pages of a set of columns
208
209The memory manager keeps track of the sum of bytes used by the write pages of a set of columns.
210It will flush (and shrink) large pages of other columns on the attempt to expand a page.
211*/
212// clang-format on
214private:
215 struct RColumnInfo {
216 RColumn *fColumn = nullptr;
217 std::size_t fCurrentPageSize = 0;
218 std::size_t fInitialPageSize = 0;
219
220 bool operator>(const RColumnInfo &other) const;
221 };
222
223 /// Sum of all the write page sizes (their capacity) of the columns in `fColumnsSortedByPageSize`
224 std::size_t fCurrentAllocatedBytes = 0;
225 /// Maximum allowed value for `fCurrentAllocatedBytes`, set from RNTupleWriteOptions::fPageBufferBudget
226 std::size_t fMaxAllocatedBytes = 0;
227 /// All columns that called `ReservePage()` (hence `TryUpdate()`) at least once,
228 /// sorted by their current write page size from large to small
229 std::set<RColumnInfo, std::greater<RColumnInfo>> fColumnsSortedByPageSize;
230
231 /// Flush columns in order of allocated write page size until the sum of all write page allocations
232 /// leaves space for at least targetAvailableSize bytes. Only use columns with a write page size larger
233 /// than pageSizeLimit.
234 bool TryEvict(std::size_t targetAvailableSize, std::size_t pageSizeLimit);
235
236public:
238
239 /// Try to register the new write page size for the given column. Flush large columns to make space, if necessary.
240 /// If not enough space is available after all (sum of write pages would be larger than fMaxAllocatedBytes),
241 /// return false.
242 bool TryUpdate(RColumn &column, std::size_t newWritePageSize);
243};
244
245// clang-format off
246/**
247\class ROOT::Experimental::Internal::RPageSink
248\ingroup NTuple
249\brief Abstract interface to write data into an ntuple
250
251The page sink takes the list of columns and afterwards a series of page commits and cluster commits.
252The user is responsible to commit clusters at a consistent point, i.e. when all pages corresponding to data
253up to the given entry number are committed.
254
255An object of this class may either be a wrapper (for example a RPageSinkBuf) or a "persistent" sink,
256inheriting from RPagePersistentSink.
257*/
258// clang-format on
259class RPageSink : public RPageStorage {
260public:
261 using Callback_t = std::function<void(RPageSink &)>;
262
263 /// Cluster that was staged, but not yet logically appended to the RNTuple
277
278protected:
279 std::unique_ptr<RNTupleWriteOptions> fOptions;
280
281 /// Helper to zip pages and header/footer; includes a 16MB (kMAXZIPBUF) zip buffer.
282 /// There could be concrete page sinks that don't need a compressor. Therefore, and in order to stay consistent
283 /// with the page source, we leave it up to the derived class whether or not the compressor gets constructed.
284 std::unique_ptr<RNTupleCompressor> fCompressor;
285
286 /// Flag if sink was initialized
287 bool fIsInitialized = false;
288
289 /// Helper for streaming a page. This is commonly used in derived, concrete page sinks. Note that if
290 /// compressionSetting is 0 (uncompressed) and the page is mappable and not checksummed, the returned sealed page
291 /// will point directly to the input page buffer. Otherwise, the sealed page references an internal buffer
292 /// of fCompressor. Thus, the buffer pointed to by the RSealedPage should never be freed.
293 /// Usage of this method requires construction of fCompressor.
295
296private:
297 std::vector<Callback_t> fOnDatasetCommitCallbacks;
298 std::vector<unsigned char> fSealPageBuffer; ///< Used as destination buffer in the simple SealPage overload
299
300 /// Used in ReservePage to maintain the page buffer budget
302
303public:
304 RPageSink(std::string_view ntupleName, const RNTupleWriteOptions &options);
305
306 RPageSink(const RPageSink &) = delete;
307 RPageSink &operator=(const RPageSink &) = delete;
308 RPageSink(RPageSink &&) = default;
310 ~RPageSink() override;
311
313 /// Returns the sink's write options.
314 const RNTupleWriteOptions &GetWriteOptions() const { return *fOptions; }
315
316 void DropColumn(ColumnHandle_t /*columnHandle*/) final {}
317
318 bool IsInitialized() const { return fIsInitialized; }
319
320 /// Return the RNTupleDescriptor being constructed.
321 virtual const RNTupleDescriptor &GetDescriptor() const = 0;
322
323 virtual ROOT::NTupleSize_t GetNEntries() const = 0;
324
325 /// Physically creates the storage container to hold the ntuple (e.g., a keys a TFile or an S3 bucket)
326 /// Init() associates column handles to the columns referenced by the model
327 void Init(RNTupleModel &model)
328 {
329 if (fIsInitialized) {
330 throw RException(R__FAIL("already initialized"));
331 }
332 fIsInitialized = true;
333 InitImpl(model);
334 }
335
336protected:
337 virtual void InitImpl(RNTupleModel &model) = 0;
338 virtual void CommitDatasetImpl() = 0;
339
340public:
341 /// Parameters for the SealPage() method
343 const RPage *fPage = nullptr; ///< Input page to be sealed
344 const RColumnElementBase *fElement = nullptr; ///< Corresponds to the page's elements, for size calculation etc.
345 int fCompressionSetting = 0; ///< Compression algorithm and level to apply
346 /// Adds a 8 byte little-endian xxhash3 checksum to the page payload. The buffer has to be large enough to
347 /// to store the additional 8 bytes.
348 bool fWriteChecksum = true;
349 /// If false, the output buffer must not point to the input page buffer, which would otherwise be an option
350 /// if the page is mappable and should not be compressed
351 bool fAllowAlias = false;
352 /// Location for sealed output. The memory buffer has to be large enough.
353 void *fBuffer = nullptr;
354 };
355
356 /// Seal a page using the provided info.
357 static RSealedPage SealPage(const RSealPageConfig &config);
358
359 /// Incorporate incremental changes to the model into the ntuple descriptor. This happens, e.g. if new fields were
360 /// added after the initial call to `RPageSink::Init(RNTupleModel &)`.
361 /// `firstEntry` specifies the global index for the first stored element in the added columns.
363 /// Adds an extra type information record to schema. The extra type information will be written to the
364 /// extension header. The information in the record will be merged with the existing information, e.g.
365 /// duplicate streamer info records will be removed. This method is called by the "on commit dataset" callback
366 /// registered by specific fields (e.g., streamer field) and during merging.
368
369 /// Commits a suppressed column for the current cluster. Can be called anytime before CommitCluster().
370 /// For any given column and cluster, there must be no calls to both CommitSuppressedColumn() and page commits.
372 /// Write a page to the storage. The column must have been added before.
374 /// Write a preprocessed page to storage. The column must have been added before.
375 virtual void
377 /// Write a vector of preprocessed pages to storage. The corresponding columns must have been added before.
378 virtual void CommitSealedPageV(std::span<RPageStorage::RSealedPageGroup> ranges) = 0;
379 /// Stage the current cluster and create a new one for the following data.
380 /// Returns the object that must be passed to CommitStagedClusters to logically append the staged cluster to the
381 /// ntuple descriptor.
383 /// Commit staged clusters, logically appending them to the ntuple descriptor.
384 virtual void CommitStagedClusters(std::span<RStagedCluster> clusters) = 0;
385 /// Finalize the current cluster and create a new one for the following data.
386 /// Returns the number of bytes written to storage (excluding meta-data).
393 /// Write out the page locations (page list envelope) for all the committed clusters since the last call of
394 /// CommitClusterGroup (or the beginning of writing).
395 virtual void CommitClusterGroup() = 0;
396
397 /// The registered callback is executed at the beginning of CommitDataset();
399 /// Run the registered callbacks and finalize the current cluster and the entrire data set.
400 void CommitDataset();
401
402 /// Get a new, empty page for the given column that can be filled with up to nElements;
403 /// nElements must be larger than zero.
405
406 /// An RAII wrapper used to synchronize a page sink. See GetSinkGuard().
408 std::mutex *fLock;
409
410 public:
411 explicit RSinkGuard(std::mutex *lock) : fLock(lock)
412 {
413 if (fLock != nullptr) {
414 fLock->lock();
415 }
416 }
417 RSinkGuard(const RSinkGuard &) = delete;
418 RSinkGuard &operator=(const RSinkGuard &) = delete;
419 RSinkGuard(RSinkGuard &&) = delete;
422 {
423 if (fLock != nullptr) {
424 fLock->unlock();
425 }
426 }
427 };
428
430 {
431 // By default, there is no lock and the guard does nothing.
432 return RSinkGuard(nullptr);
433 }
434}; // class RPageSink
435
436// clang-format off
437/**
438\class ROOT::Experimental::Internal::RPagePersistentSink
439\ingroup NTuple
440\brief Base class for a sink with a physical storage backend
441*/
442// clang-format on
444private:
445 /// Used to map the IDs of the descriptor to the physical IDs issued during header/footer serialization
447
448 /// Remembers the starting cluster id for the next cluster group
449 std::uint64_t fNextClusterInGroup = 0;
450 /// Used to calculate the number of entries in the current cluster
452 /// Keeps track of the number of elements in the currently open cluster. Indexed by column id.
453 std::vector<RClusterDescriptor::RColumnRange> fOpenColumnRanges;
454 /// Keeps track of the written pages in the currently open cluster. Indexed by column id.
455 std::vector<RClusterDescriptor::RPageRange> fOpenPageRanges;
456
457 /// Union of the streamer info records that are sent from streamer fields to the sink before committing the dataset.
459
460protected:
461 /// Set of optional features supported by the persistent sink
462 struct RFeatures {
463 bool fCanMergePages = false;
464 };
465
468
469 /// Default I/O performance counters that get registered in fMetrics
479 std::unique_ptr<RCounters> fCounters;
480
481 virtual void InitImpl(unsigned char *serializedHeader, std::uint32_t length) = 0;
482
484 virtual RNTupleLocator
486 /// Vector commit of preprocessed pages. The `ranges` array specifies a range of sealed pages to be
487 /// committed for each column. The returned vector contains, in order, the RNTupleLocator for each
488 /// page on each range in `ranges`, i.e. the first N entries refer to the N pages in `ranges[0]`,
489 /// followed by M entries that refer to the M pages in `ranges[1]`, etc.
490 /// The mask allows to skip writing out certain pages. The vector has the size of all the pages.
491 /// For every `false` value in the mask, the corresponding locator is skipped (missing) in the output vector.
492 /// The default is to call `CommitSealedPageImpl` for each page; derived classes may provide an
493 /// optimized implementation though.
494 virtual std::vector<RNTupleLocator>
495 CommitSealedPageVImpl(std::span<RPageStorage::RSealedPageGroup> ranges, const std::vector<bool> &mask);
496 /// Returns the number of bytes written to storage (excluding metadata)
497 virtual std::uint64_t StageClusterImpl() = 0;
498 /// Returns the locator of the page list envelope of the given buffer that contains the serialized page list.
499 /// Typically, the implementation takes care of compressing and writing the provided buffer.
500 virtual RNTupleLocator CommitClusterGroupImpl(unsigned char *serializedPageList, std::uint32_t length) = 0;
501 virtual void CommitDatasetImpl(unsigned char *serializedFooter, std::uint32_t length) = 0;
502
503 /// Enables the default set of metrics provided by RPageSink. `prefix` will be used as the prefix for
504 /// the counters registered in the internal RNTupleMetrics object.
505 /// This set of counters can be extended by a subclass by calling `fMetrics.MakeCounter<...>()`.
506 ///
507 /// A subclass using the default set of metrics is always responsible for updating the counters
508 /// appropriately, e.g. `fCounters->fNPageCommited.Inc()`
509 void EnableDefaultMetrics(const std::string &prefix);
510
511public:
512 RPagePersistentSink(std::string_view ntupleName, const RNTupleWriteOptions &options);
513
518 ~RPagePersistentSink() override;
519
520 /// Guess the concrete derived page source from the location
521 static std::unique_ptr<RPageSink> Create(std::string_view ntupleName, std::string_view location,
522 const RNTupleWriteOptions &options = RNTupleWriteOptions());
523
525
527
529
530 /// Updates the descriptor and calls InitImpl() that handles the backend-specific details (file, DAOS, etc.)
531 void InitImpl(RNTupleModel &model) final;
534
535 /// Initialize sink based on an existing descriptor and fill into the descriptor builder.
536 /// \return The model created from the new sink's descriptor. This model should be kept alive
537 /// for at least as long as the sink.
538 [[nodiscard]] std::unique_ptr<RNTupleModel> InitFromDescriptor(const RNTupleDescriptor &descriptor);
539
541 void CommitPage(ColumnHandle_t columnHandle, const RPage &page) final;
543 void CommitSealedPageV(std::span<RPageStorage::RSealedPageGroup> ranges) final;
544 RStagedCluster StageCluster(ROOT::NTupleSize_t nNewEntries) final;
545 void CommitStagedClusters(std::span<RStagedCluster> clusters) final;
548}; // class RPagePersistentSink
549
550// clang-format off
551/**
552\class ROOT::Experimental::Internal::RPageSource
553\ingroup NTuple
554\brief Abstract interface to read data from an ntuple
555
556The page source is initialized with the columns of interest. Alias columns from projected fields are mapped to the
557corresponding physical columns. Pages from the columns of interest can then be mapped into memory.
558The page source also gives access to the ntuple's meta-data.
559*/
560// clang-format on
562public:
563 /// Used in SetEntryRange / GetEntryRange
564 struct REntryRange {
566 ROOT::NTupleSize_t fNEntries = 0;
567
568 /// Returns true if the given cluster has entries within the entry range
569 bool IntersectsWith(const RClusterDescriptor &clusterDesc) const;
570 };
571
572 /// An RAII wrapper used for the read-only access to `RPageSource::fDescriptor`. See `GetExclDescriptorGuard()``.
575 std::shared_mutex &fLock;
576
577 public:
578 RSharedDescriptorGuard(const RNTupleDescriptor &desc, std::shared_mutex &lock) : fDescriptor(desc), fLock(lock)
579 {
580 fLock.lock_shared();
581 }
586 ~RSharedDescriptorGuard() { fLock.unlock_shared(); }
587 const RNTupleDescriptor *operator->() const { return &fDescriptor; }
588 const RNTupleDescriptor &GetRef() const { return fDescriptor; }
589 };
590
591 /// An RAII wrapper used for the writable access to `RPageSource::fDescriptor`. See `GetSharedDescriptorGuard()`.
594 std::shared_mutex &fLock;
595
596 public:
597 RExclDescriptorGuard(RNTupleDescriptor &desc, std::shared_mutex &lock) : fDescriptor(desc), fLock(lock)
598 {
599 fLock.lock();
600 }
606 {
607 fDescriptor.IncGeneration();
608 fLock.unlock();
609 }
610 RNTupleDescriptor *operator->() const { return &fDescriptor; }
611 void MoveIn(RNTupleDescriptor desc) { fDescriptor = std::move(desc); }
612 };
613
614private:
616 mutable std::shared_mutex fDescriptorLock;
617 REntryRange fEntryRange; ///< Used by the cluster pool to prevent reading beyond the given range
618 bool fHasStructure = false; ///< Set to true once `LoadStructure()` is called
619 bool fIsAttached = false; ///< Set to true once `Attach()` is called
620
621 /// Remembers the last cluster id from which a page was requested
623 /// Clusters from where pages got preloaded in UnzipClusterImpl(), ordered by first entry number
624 /// of the clusters. If the last used cluster changes in LoadPage(), all unused pages from
625 /// previous clusters are evicted from the page pool.
626 std::map<ROOT::NTupleSize_t, ROOT::DescriptorId_t> fPreloadedClusters;
627
628 /// Does nothing if fLastUsedCluster == clusterId. Otherwise, updated fLastUsedCluster
629 /// and evict unused paged from the page pool of all previous clusters.
630 /// Must not be called when the descriptor guard is taken.
631 void UpdateLastUsedCluster(ROOT::DescriptorId_t clusterId);
632
633protected:
634 /// Default I/O performance counters that get registered in `fMetrics`
654
655 /// Keeps track of the requested physical column IDs and their in-memory target type via a column element identifier.
656 /// When using alias columns (projected fields), physical columns may be requested multiple times.
658 public:
659 struct RColumnInfo {
661 std::size_t fRefCounter = 0;
662 };
663
664 private:
665 /// Maps physical column IDs to all the requested in-memory representations.
666 /// A pair of physical column ID and in-memory representation can be requested multiple times, which is
667 /// indicated by the reference counter.
668 /// We can only have a handful of possible in-memory representations for a given column,
669 /// so it is fine to search them linearly.
670 std::unordered_map<ROOT::DescriptorId_t, std::vector<RColumnInfo>> fColumnInfos;
671
672 public:
675 RCluster::ColumnSet_t ToColumnSet() const;
677 {
678 return fColumnInfos.count(physicalColumnId) > 0;
679 }
680 const std::vector<RColumnInfo> &GetColumnInfos(ROOT::DescriptorId_t physicalColumnId) const
681 {
682 return fColumnInfos.at(physicalColumnId);
683 }
684 };
685
686 /// Summarizes cluster-level information that are necessary to load a certain page.
687 /// Used by LoadPageImpl().
689 ROOT::DescriptorId_t fClusterId = 0;
690 /// Location of the page on disk
692 /// The first element number of the page's column in the given cluster
693 std::uint64_t fColumnOffset = 0;
694 };
695
696 std::unique_ptr<RCounters> fCounters;
697
699 /// The active columns are implicitly defined by the model fields or views
701
702 /// Pages that are unzipped with IMT are staged into the page pool
704
705 virtual void LoadStructureImpl() = 0;
706 /// `LoadStructureImpl()` has been called before `AttachImpl()` is called
708 /// Returns a new, unattached page source for the same data set
709 virtual std::unique_ptr<RPageSource> CloneImpl() const = 0;
710 // Only called if a task scheduler is set. No-op be default.
711 virtual void UnzipClusterImpl(RCluster *cluster);
712 // Returns a page from storage if not found in the page pool. Should be able to handle zero page locators.
713 virtual RPageRef
715
716 /// Prepare a page range read for the column set in `clusterKey`. Specifically, pages referencing the
717 /// `kTypePageZero` locator are filled in `pageZeroMap`; otherwise, `perPageFunc` is called for each page. This is
718 /// commonly used as part of `LoadClusters()` in derived classes.
719 void PrepareLoadCluster(
723
724 /// Enables the default set of metrics provided by RPageSource. `prefix` will be used as the prefix for
725 /// the counters registered in the internal RNTupleMetrics object.
726 /// A subclass using the default set of metrics is responsible for updating the counters
727 /// appropriately, e.g. `fCounters->fNRead.Inc()`
728 /// Alternatively, a subclass might provide its own RNTupleMetrics object by overriding the
729 /// `GetMetrics()` member function.
730 void EnableDefaultMetrics(const std::string &prefix);
731
732 /// Note that the underlying lock is not recursive. See `GetSharedDescriptorGuard()` for further information.
733 RExclDescriptorGuard GetExclDescriptorGuard() { return RExclDescriptorGuard(fDescriptor, fDescriptorLock); }
734
735public:
736 RPageSource(std::string_view ntupleName, const RNTupleReadOptions &fOptions);
737 RPageSource(const RPageSource &) = delete;
741 ~RPageSource() override;
742 /// Guess the concrete derived page source from the file name (location)
743 static std::unique_ptr<RPageSource> Create(std::string_view ntupleName, std::string_view location,
744 const RNTupleReadOptions &options = RNTupleReadOptions());
745 /// Open the same storage multiple time, e.g. for reading in multiple threads.
746 /// If the source is already attached, the clone will be attached, too. The clone will use, however,
747 /// it's own connection to the underlying storage (e.g., file descriptor, XRootD handle, etc.)
748 std::unique_ptr<RPageSource> Clone() const;
749
750 /// Helper for unstreaming a page. This is commonly used in derived, concrete page sources. The implementation
751 /// currently always makes a memory copy, even if the sealed page is uncompressed and in the final memory layout.
752 /// The optimization of directly mapping pages is left to the concrete page source implementations.
753 RResult<RPage> static UnsealPage(const RSealedPage &sealedPage, const RColumnElementBase &element,
755
757 const RNTupleReadOptions &GetReadOptions() const { return fOptions; }
758
759 /// Takes the read lock for the descriptor. Multiple threads can take the lock concurrently.
760 /// The underlying `std::shared_mutex`, however, is neither read nor write recursive:
761 /// within one thread, only one lock (shared or exclusive) must be acquired at the same time. This requires special
762 /// care in sections protected by `GetSharedDescriptorGuard()` and `GetExclDescriptorGuard()` especially to avoid
763 /// that the locks are acquired indirectly (e.g. by a call to `GetNEntries()`). As a general guideline, no other
764 /// method of the page source should be called (directly or indirectly) in a guarded section.
766 {
767 return RSharedDescriptorGuard(fDescriptor, fDescriptorLock);
768 }
769
772
773 /// Loads header and footer without decompressing or deserializing them. This can be used to asynchronously open
774 /// a file in the background. The method is idempotent and it is called as a first step in `Attach()`.
775 /// Pages sources may or may not make use of splitting loading and processing meta-data.
776 /// Therefore, `LoadStructure()` may do nothing and defer loading the meta-data to `Attach()`.
777 void LoadStructure();
778 /// Open the physical storage container and deserialize header and footer
779 void Attach(
783
784 /// Promise to only read from the given entry range. If set, prevents the cluster pool from reading-ahead beyond
785 /// the given range. The range needs to be within `[0, GetNEntries())`.
786 void SetEntryRange(const REntryRange &range);
787 REntryRange GetEntryRange() const { return fEntryRange; }
788
789 /// Allocates and fills a page that contains the index-th element. The default implementation searches
790 /// the page and calls LoadPageImpl(). Returns a default-constructed RPage for suppressed columns.
792 /// Another version of `LoadPage` that allows to specify cluster-relative indexes.
793 /// Returns a default-constructed RPage for suppressed columns.
795
796 /// Read the packed and compressed bytes of a page into the memory buffer provided by `sealedPage`. The sealed page
797 /// can be used subsequently in a call to `RPageSink::CommitSealedPage`.
798 /// The `fSize` and `fNElements` member of the sealedPage parameters are always set. If `sealedPage.fBuffer` is
799 /// `nullptr`, no data will be copied but the returned size information can be used by the caller to allocate a large
800 /// enough buffer and call `LoadSealedPage` again.
801 virtual void
803
804 /// Populates all the pages of the given cluster ids and columns; it is possible that some columns do not
805 /// contain any pages. The page source may load more columns than the minimal necessary set from `columns`.
806 /// To indicate which columns have been loaded, `LoadClusters()`` must mark them with `SetColumnAvailable()`.
807 /// That includes the ones from the `columns` that don't have pages; otherwise subsequent requests
808 /// for the cluster would assume an incomplete cluster and trigger loading again.
809 /// `LoadClusters()` is typically called from the I/O thread of a cluster pool, i.e. the method runs
810 /// concurrently to other methods of the page source.
811 virtual std::vector<std::unique_ptr<RCluster>> LoadClusters(std::span<RCluster::RKey> clusterKeys) = 0;
812
813 /// Parallel decompression and unpacking of the pages in the given cluster. The unzipped pages are supposed
814 /// to be preloaded in a page pool attached to the source. The method is triggered by the cluster pool's
815 /// unzip thread. It is an optional optimization, the method can safely do nothing. In particular, the
816 /// actual implementation will only run if a task scheduler is set. In practice, a task scheduler is set
817 /// if implicit multi-threading is turned on.
818 void UnzipCluster(RCluster *cluster);
819
820 // TODO(gparolini): for symmetry with SealPage(), we should either make this private or SealPage() public.
822}; // class RPageSource
823
824} // namespace Internal
825
826} // namespace Experimental
827} // namespace ROOT
828
829#endif
#define R__FAIL(msg)
Short-hand to return an RResult<T> in an error state; the RError is implicitly converted into RResult...
Definition RError.hxx:299
#define d(i)
Definition RSha256.hxx:102
#define b(i)
Definition RSha256.hxx:100
#define e(i)
Definition RSha256.hxx:103
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t mask
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h length
Option_t Option_t TPoint TPoint const char mode
char name[80]
Definition TGX11.cxx:110
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.
An either thread-safe or non thread safe counter for CPU ticks.
An in-memory subset of the packed and compressed pages of a cluster.
Definition RCluster.hxx:152
std::unordered_set< ROOT::DescriptorId_t > ColumnSet_t
Definition RCluster.hxx:154
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.
@ kForReading
Deserializes the descriptor and performs fixup on the suppressed column ranges and on clusters,...
std::map< Int_t, TVirtualStreamerInfo * > StreamerInfoMap_t
A memory region that contains packed and compressed pages.
Definition RCluster.hxx:103
Abstract interface to allocate and release pages.
Base class for a sink with a physical storage backend.
RPagePersistentSink(const RPagePersistentSink &)=delete
RPagePersistentSink(RPagePersistentSink &&)=default
std::uint64_t fNextClusterInGroup
Remembers the starting cluster id for the next cluster group.
virtual std::uint64_t StageClusterImpl()=0
Returns the number of bytes written to storage (excluding metadata)
RPagePersistentSink & operator=(RPagePersistentSink &&)=default
virtual void InitImpl(unsigned char *serializedHeader, std::uint32_t length)=0
ROOT::NTupleSize_t GetNEntries() const final
RNTupleSerializer::RContext fSerializationContext
Used to map the IDs of the descriptor to the physical IDs issued during header/footer serialization.
void CommitSealedPage(ROOT::DescriptorId_t physicalColumnId, const RPageStorage::RSealedPage &sealedPage) final
Write a preprocessed page to storage. The column must have been added before.
virtual RNTupleLocator CommitPageImpl(ColumnHandle_t columnHandle, const RPage &page)=0
RStagedCluster StageCluster(ROOT::NTupleSize_t nNewEntries) final
Stage the current cluster and create a new one for the following data.
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...
std::vector< RClusterDescriptor::RPageRange > fOpenPageRanges
Keeps track of the written pages in the currently open cluster. Indexed by column id.
const RNTupleDescriptor & GetDescriptor() const final
Return the RNTupleDescriptor being constructed.
void CommitPage(ColumnHandle_t columnHandle, const RPage &page) final
Write a page to the storage. The column must have been added before.
virtual void CommitDatasetImpl(unsigned char *serializedFooter, std::uint32_t length)=0
void UpdateSchema(const RNTupleModelChangeset &changeset, ROOT::NTupleSize_t firstEntry) final
Incorporate incremental changes to the model into the ntuple descriptor.
RPagePersistentSink & operator=(const RPagePersistentSink &)=delete
static std::unique_ptr< RPageSink > Create(std::string_view ntupleName, std::string_view location, const RNTupleWriteOptions &options=RNTupleWriteOptions())
Guess the concrete derived page source from the location.
RPagePersistentSink(std::string_view ntupleName, const RNTupleWriteOptions &options)
virtual RNTupleLocator CommitSealedPageImpl(ROOT::DescriptorId_t physicalColumnId, const RPageStorage::RSealedPage &sealedPage)=0
Internal::RNTupleDescriptorBuilder fDescriptorBuilder
virtual std::vector< RNTupleLocator > CommitSealedPageVImpl(std::span< RPageStorage::RSealedPageGroup > ranges, const std::vector< bool > &mask)
Vector commit of preprocessed pages.
std::unique_ptr< RNTupleModel > InitFromDescriptor(const RNTupleDescriptor &descriptor)
Initialize sink based on an existing descriptor and fill into the descriptor builder.
RNTupleSerializer::StreamerInfoMap_t fStreamerInfos
Union of the streamer info records that are sent from streamer fields to the sink before committing t...
void CommitClusterGroup() final
Write out the page locations (page list envelope) for all the committed clusters since the last call ...
std::vector< RClusterDescriptor::RColumnRange > fOpenColumnRanges
Keeps track of the number of elements in the currently open cluster. Indexed by column id.
void CommitSealedPageV(std::span< RPageStorage::RSealedPageGroup > ranges) final
Write a vector of preprocessed pages to storage. The corresponding columns must have been added befor...
void CommitSuppressedColumn(ColumnHandle_t columnHandle) final
Commits a suppressed column for the current cluster.
void CommitStagedClusters(std::span< RStagedCluster > clusters) final
Commit staged clusters, logically appending them to the ntuple descriptor.
void EnableDefaultMetrics(const std::string &prefix)
Enables the default set of metrics provided by RPageSink.
void UpdateExtraTypeInfo(const RExtraTypeInfoDescriptor &extraTypeInfo) final
Adds an extra type information record to schema.
ROOT::NTupleSize_t fPrevClusterNEntries
Used to calculate the number of entries in the current cluster.
ColumnHandle_t AddColumn(ROOT::DescriptorId_t fieldId, RColumn &column) final
Register a new column.
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
Abstract interface to write data into an ntuple.
std::vector< unsigned char > fSealPageBuffer
Used as destination buffer in the simple SealPage overload.
std::vector< Callback_t > fOnDatasetCommitCallbacks
RPageSink & operator=(RPageSink &&)=default
RPageSink(std::string_view ntupleName, const RNTupleWriteOptions &options)
bool fIsInitialized
Flag if sink was initialized.
virtual void UpdateExtraTypeInfo(const RExtraTypeInfoDescriptor &extraTypeInfo)=0
Adds an extra type information record to schema.
void CommitDataset()
Run the registered callbacks and finalize the current cluster and the entrire data set.
virtual void CommitSuppressedColumn(ColumnHandle_t columnHandle)=0
Commits a suppressed column for the current cluster.
virtual const RNTupleDescriptor & GetDescriptor() const =0
Return the RNTupleDescriptor being constructed.
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 RPage ReservePage(ColumnHandle_t columnHandle, 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.
RWritePageMemoryManager fWritePageMemoryManager
Used in ReservePage to maintain the page buffer budget.
virtual void CommitPage(ColumnHandle_t columnHandle, const RPage &page)=0
Write a page to the storage. The column must have been added before.
const RNTupleWriteOptions & GetWriteOptions() const
Returns the sink's write options.
virtual void UpdateSchema(const RNTupleModelChangeset &changeset, ROOT::NTupleSize_t firstEntry)=0
Incorporate incremental changes to the model into the ntuple descriptor.
RPageSink & operator=(const RPageSink &)=delete
virtual void CommitClusterGroup()=0
Write out the page locations (page list envelope) for all the committed clusters since the last call ...
virtual void CommitSealedPage(ROOT::DescriptorId_t physicalColumnId, const RPageStorage::RSealedPage &sealedPage)=0
Write a preprocessed page to storage. The column must have been added before.
void RegisterOnCommitDatasetCallback(Callback_t callback)
The registered callback is executed at the beginning of CommitDataset();.
RPageSink(const RPageSink &)=delete
std::function< void(RPageSink &)> Callback_t
virtual void CommitStagedClusters(std::span< RStagedCluster > clusters)=0
Commit staged clusters, logically appending them to the ntuple descriptor.
virtual void InitImpl(RNTupleModel &model)=0
void DropColumn(ColumnHandle_t) final
Unregisters a column.
EPageStorageType GetType() final
Whether the concrete implementation is a sink or a source.
std::unique_ptr< RNTupleCompressor > fCompressor
Helper to zip pages and header/footer; includes a 16MB (kMAXZIPBUF) zip buffer.
virtual ROOT::NTupleSize_t GetNEntries() const =0
virtual RStagedCluster StageCluster(ROOT::NTupleSize_t nNewEntries)=0
Stage the current cluster and create a new one for the following data.
virtual void CommitSealedPageV(std::span< RPageStorage::RSealedPageGroup > ranges)=0
Write a vector of preprocessed pages to storage. The corresponding columns must have been added befor...
std::unique_ptr< RNTupleWriteOptions > fOptions
RSealedPage SealPage(const RPage &page, const RColumnElementBase &element)
Helper for streaming a page.
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
An RAII wrapper used for the writable access to RPageSource::fDescriptor. See GetSharedDescriptorGuar...
RExclDescriptorGuard(RNTupleDescriptor &desc, std::shared_mutex &lock)
RExclDescriptorGuard(const RExclDescriptorGuard &)=delete
RExclDescriptorGuard & operator=(RExclDescriptorGuard &&)=delete
RExclDescriptorGuard & operator=(const RExclDescriptorGuard &)=delete
An RAII wrapper used for the read-only access to RPageSource::fDescriptor. See GetExclDescriptorGuard...
RSharedDescriptorGuard & operator=(RSharedDescriptorGuard &&)=delete
RSharedDescriptorGuard(const RSharedDescriptorGuard &)=delete
RSharedDescriptorGuard(const RNTupleDescriptor &desc, std::shared_mutex &lock)
RSharedDescriptorGuard & operator=(const RSharedDescriptorGuard &)=delete
Abstract interface to read data from an ntuple.
std::map< ROOT::NTupleSize_t, ROOT::DescriptorId_t > fPreloadedClusters
Clusters from where pages got preloaded in UnzipClusterImpl(), ordered by first entry number of the c...
RPagePool fPagePool
Pages that are unzipped with IMT are staged into the page pool.
EPageStorageType GetType() final
Whether the concrete implementation is a sink or a source.
RPageSource(const RPageSource &)=delete
RPageSource & operator=(RPageSource &&)=delete
virtual RNTupleDescriptor AttachImpl(RNTupleSerializer::EDescriptorDeserializeMode mode)=0
LoadStructureImpl() has been called before AttachImpl() is called
std::unique_ptr< RCounters > fCounters
RExclDescriptorGuard GetExclDescriptorGuard()
Note that the underlying lock is not recursive. See GetSharedDescriptorGuard() for further informatio...
RActivePhysicalColumns fActivePhysicalColumns
The active columns are implicitly defined by the model fields or views.
RPageSource & operator=(const RPageSource &)=delete
const RNTupleReadOptions & GetReadOptions() const
virtual std::vector< std::unique_ptr< RCluster > > LoadClusters(std::span< RCluster::RKey > clusterKeys)=0
Populates all the pages of the given cluster ids and columns; it is possible that some columns do not...
REntryRange fEntryRange
Used by the cluster pool to prevent reading beyond the given range.
virtual std::unique_ptr< RPageSource > CloneImpl() const =0
Returns a new, unattached page source for the same data set.
virtual RPageRef LoadPageImpl(ColumnHandle_t columnHandle, const RClusterInfo &clusterInfo, ROOT::NTupleSize_t idxInCluster)=0
virtual void LoadSealedPage(ROOT::DescriptorId_t physicalColumnId, RNTupleLocalIndex localIndex, RSealedPage &sealedPage)=0
Read the packed and compressed bytes of a page into the memory buffer provided by sealedPage.
const RSharedDescriptorGuard GetSharedDescriptorGuard() const
Takes the read lock for the descriptor.
The interface of a task scheduler to schedule page (de)compression tasks.
virtual void Wait()=0
Blocks until all scheduled tasks finished.
virtual void AddTask(const std::function< void(void)> &taskFunc)=0
Take a callable that represents a task.
Common functionality of an ntuple storage for both reading and writing.
std::deque< RSealedPage > SealedPageSequence_t
std::unique_ptr< RPageAllocator > fPageAllocator
For the time being, we will use the heap allocator for all sources and sinks. This may change in the ...
static constexpr std::size_t kNBytesPageChecksum
The page checksum is a 64bit xxhash3.
virtual void DropColumn(ColumnHandle_t columnHandle)=0
Unregisters a column.
virtual Detail::RNTupleMetrics & GetMetrics()
Returns the default metrics object.
const std::string & GetNTupleName() const
Returns the NTuple name.
virtual EPageStorageType GetType()=0
Whether the concrete implementation is a sink or a source.
RPageStorage & operator=(RPageStorage &&other)=default
RPageStorage & operator=(const RPageStorage &other)=delete
RPageStorage(const RPageStorage &other)=delete
virtual ColumnHandle_t AddColumn(ROOT::DescriptorId_t fieldId, RColumn &column)=0
Register a new column.
RPageStorage(RPageStorage &&other)=default
void SetTaskScheduler(RTaskScheduler *taskScheduler)
RColumnHandle ColumnHandle_t
The column handle identifies a column with the current open page storage.
ROOT::DescriptorId_t GetColumnId(ColumnHandle_t columnHandle) const
A page is a slice of a column that is mapped into memory.
Definition RPage.hxx:47
Helper to maintain a memory budget for the write pages of a set of columns.
bool TryUpdate(RColumn &column, std::size_t newWritePageSize)
Try to register the new write page size for the given column.
std::size_t fCurrentAllocatedBytes
Sum of all the write page sizes (their capacity) of the columns in fColumnsSortedByPageSize
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...
std::size_t fMaxAllocatedBytes
Maximum allowed value for fCurrentAllocatedBytes, set from RNTupleWriteOptions::fPageBufferBudget.
std::set< RColumnInfo, std::greater< RColumnInfo > > fColumnsSortedByPageSize
All columns that called ReservePage() (hence TryUpdate()) at least once, sorted by their current writ...
Records the partition of data into pages for a particular column in a particular cluster.
Meta-data for a set of ntuple clusters.
Field specific extra type information from the header / extenstion header.
The on-storage meta-data of an ntuple.
The RNTupleModel encapulates the schema of an ntuple.
Common user-tunable settings for reading ntuples.
Common user-tunable settings for storing ntuples.
Base class for all ROOT issued exceptions.
Definition RError.hxx:79
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.
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
std::uint64_t DescriptorId_t
Distriniguishes elements of the same type within a descriptor, e.g. different fields.
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:156
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.
Detail::RNTupleTickCounter< Detail::RNTupleAtomicCounter > & fTimeCpuZip
Detail::RNTupleTickCounter< Detail::RNTupleAtomicCounter > & fTimeCpuWrite
Set of optional features supported by the persistent sink.
const RColumnElementBase * fElement
Corresponds to the page's elements, for size calculation etc.
void * fBuffer
Location for sealed output. The memory buffer has to be large enough.
bool fAllowAlias
If false, the output buffer must not point to the input page buffer, which would otherwise be an opti...
int fCompressionSetting
Compression algorithm and level to apply.
bool fWriteChecksum
Adds a 8 byte little-endian xxhash3 checksum to the page payload.
Cluster that was staged, but not yet logically appended to the RNTuple.
Summarizes cluster-level information that are necessary to load a certain page.
RClusterDescriptor::RPageRange::RPageInfoExtended fPageInfo
Location of the page on disk.
Default I/O performance counters that get registered in fMetrics
Detail::RNTupleTickCounter< Detail::RNTupleAtomicCounter > & fTimeCpuUnzip
Detail::RNTupleTickCounter< Detail::RNTupleAtomicCounter > & fTimeCpuRead
A range of sealed pages referring to the same column that can be used for vector commit.
RSealedPageGroup(ROOT::DescriptorId_t d, SealedPageSequence_t::const_iterator b, SealedPageSequence_t::const_iterator e)
A sealed page contains the bytes of a page as written to storage (packed & compressed).
bool fHasChecksum
If set, the last 8 bytes of the buffer are the xxhash of the rest of the buffer.
std::size_t fBufferSize
Size of the page payload and the trailing checksum (if available)
RResult< std::uint64_t > GetChecksum() const
Returns a failure if the sealed page has no checksum.
RSealedPage(const void *buffer, std::size_t bufferSize, std::uint32_t nElements, bool hasChecksum=false)
RSealedPage & operator=(const RSealedPage &other)=default
RSealedPage & operator=(RSealedPage &&other)=default
We do not need to store the element size / uncompressed page size because we know to which column the...