Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RPageSinkBuf.cxx
Go to the documentation of this file.
1/// \file RPageSinkBuf.cxx
2/// \author Jakob Blomer <jblomer@cern.ch>
3/// \author Max Orok <maxwellorok@gmail.com>
4/// \author Javier Lopez-Gomez <javier.lopez.gomez@cern.ch>
5/// \date 2021-03-17
6
7/*************************************************************************
8 * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. *
9 * All rights reserved. *
10 * *
11 * For the licensing terms see $ROOTSYS/LICENSE. *
12 * For the list of contributors see $ROOTSYS/README/CREDITS. *
13 *************************************************************************/
14
15#include <ROOT/RNTupleModel.hxx>
16#include <ROOT/RNTupleUtils.hxx>
18#include <ROOT/RNTupleZip.hxx>
19#include <ROOT/RPageSinkBuf.hxx>
20
21#include <algorithm>
22#include <memory>
23
30
37
39{
40 fBufferedPages.clear();
41 // Each RSealedPage points to the same region as `fBuf` for some element in `fBufferedPages`; thus, no further
42 // clean-up is required
43 fSealedPages.clear();
44}
45
46ROOT::Internal::RPageSinkBuf::RPageSinkBuf(std::unique_ptr<RPageSink> inner)
47 : RPageSink(inner->GetNTupleName(), inner->GetWriteOptions()), fInnerSink(std::move(inner))
48{
49 fMetrics = RNTupleMetrics("RPageSinkBuf");
50 fCounters = std::make_unique<RCounters>(
51 RCounters{*fMetrics.MakeCounter<RNTuplePlainCounter *>("ParallelZip", "", "compressing pages in parallel"),
52 *fMetrics.MakeCounter<RNTupleAtomicCounter *>("timeWallZip", "ns", "wall clock time spent compressing"),
53 *fMetrics.MakeCounter<RNTuplePlainCounter *>("timeWallCriticalSection", "ns",
54 "wall clock time spent in critical sections"),
56 "CPU time spent compressing"),
58 "timeCpuCriticalSection", "ns", "CPU time spent in critical section")});
59 fMetrics.ObserveMetrics(fInnerSink->GetMetrics());
60}
61
63{
64 // Wait for unterminated tasks, if any, as they may still hold a reference to `this`.
65 WaitForAllTasks();
66}
67
72
73void ROOT::Internal::RPageSinkBuf::ConnectFields(const std::vector<ROOT::RFieldBase *> &fields,
74 ROOT::NTupleSize_t firstEntry)
75{
76 auto connectField = [&](ROOT::RFieldBase &f) {
77 // Field Zero would have id 0.
78 ++fNFields;
79 f.SetOnDiskId(fNFields);
80 CallConnectPageSinkOnField(f, *this, firstEntry); // issues in turn calls to `AddColumn()`
81 };
82 for (auto *f : fields) {
83 connectField(*f);
84 for (auto &descendant : *f) {
85 connectField(descendant);
86 }
87 }
88 fBufferedColumns.resize(fNColumns);
89}
90
92{
93 return fInnerSink->GetDescriptor();
94}
95
97{
98 ConnectFields(GetFieldZeroOfModel(model).GetMutableSubfields(), 0U);
99
100 fInnerModel = model.Clone();
101 fInnerSink->Init(*fInnerModel);
102}
103
105 ROOT::NTupleSize_t firstEntry)
106{
107 ConnectFields(changeset.fAddedFields, firstEntry);
108
109 // The buffered page sink maintains a copy of the RNTupleModel for the inner sink; replicate the changes there
110 // TODO(jalopezg): we should be able, in general, to simplify the buffered sink.
111 auto cloneAddField = [&](const ROOT::RFieldBase *field) {
112 auto cloned = field->Clone(field->GetFieldName());
113 auto p = &(*cloned);
114
115 auto parent = field->GetParent();
116 assert(parent);
117 if (typeid(*parent) != typeid(RFieldZero)) {
118 auto &innerParent = fInnerModel->GetMutableField(parent->GetQualifiedFieldName());
119 assert(dynamic_cast<RRecordField *>(&innerParent));
120 AddItemToRecord(static_cast<RRecordField &>(innerParent), std::move(cloned));
121 } else {
122 fInnerModel->AddField(std::move(cloned));
123 }
124 return p;
125 };
126 auto cloneAddProjectedField = [&](ROOT::RFieldBase *field) {
127 auto cloned = field->Clone(field->GetFieldName());
128 auto p = &(*cloned);
129 auto &projectedFields = GetProjectedFieldsOfModel(changeset.fModel);
131 fieldMap[p] = &fInnerModel->GetConstField(projectedFields.GetSourceField(field)->GetQualifiedFieldName());
132 auto targetIt = cloned->begin();
133 for (auto &f : *field)
134 fieldMap[&(*targetIt++)] =
135 &fInnerModel->GetConstField(projectedFields.GetSourceField(&f)->GetQualifiedFieldName());
136 GetProjectedFieldsOfModel(*fInnerModel).Add(std::move(cloned), fieldMap);
137 return p;
138 };
139 RNTupleModelChangeset innerChangeset{*fInnerModel};
140 fInnerModel->Unfreeze();
141 std::transform(changeset.fAddedFields.cbegin(), changeset.fAddedFields.cend(),
142 std::back_inserter(innerChangeset.fAddedFields), cloneAddField);
143 std::transform(changeset.fAddedProjectedFields.cbegin(), changeset.fAddedProjectedFields.cend(),
144 std::back_inserter(innerChangeset.fAddedProjectedFields), cloneAddProjectedField);
145 fInnerModel->Freeze();
146 fInnerSink->UpdateSchema(innerChangeset, firstEntry);
147}
148
150{
151 RPageSink::RSinkGuard g(fInnerSink->GetSinkGuard());
152 RNTuplePlainTimer timer(fCounters->fTimeWallCriticalSection, fCounters->fTimeCpuCriticalSection);
153 fInnerSink->UpdateExtraTypeInfo(extraTypeInfo);
154}
155
157{
158 fSuppressedColumns.emplace_back(physicalColumnId);
159}
160
162 const RPage &page)
163{
164 // Safety: References are guaranteed to be valid until the element is destroyed. In other words, all buffered page
165 // elements are valid until DropBufferedPages().
166 auto &zipItem = fBufferedColumns.at(physicalColumnId).BufferPage();
167 std::size_t maxSealedPageBytes =
168 page.GetNBytes() + GetWriteOptions().GetEnablePageChecksums() * RSealedPage::kNBytesPageChecksum;
169 // Do not allocate the buffer yet, in case of IMT we only need it once the task is started.
170 auto &sealedPage = fBufferedColumns.at(physicalColumnId).RegisterSealedPage();
171
172 auto allocateBuf = [&zipItem, maxSealedPageBytes]() {
173 zipItem.fBuf = MakeUninitArray<unsigned char>(maxSealedPageBytes);
174 R__ASSERT(zipItem.fBuf);
175 };
176 auto shrinkSealedPage = [&zipItem, maxSealedPageBytes, &sealedPage]() {
177 // If the sealed page is smaller than the maximum size (with compression), allocate what is needed and copy the
178 // sealed page content to save memory.
179 auto sealedBufferSize = sealedPage.GetBufferSize();
180 if (sealedBufferSize < maxSealedPageBytes) {
181 auto buf = MakeUninitArray<unsigned char>(sealedBufferSize);
182 memcpy(buf.get(), sealedPage.GetBuffer(), sealedBufferSize);
183 zipItem.fBuf = std::move(buf);
184 sealedPage.SetBuffer(zipItem.fBuf.get());
185 }
186 };
187
188 // If we already buffer more uncompressed bytes than the approximate zipped cluster size, we assume there is enough
189 // work for other threads to pick up. This limits the buffer usage when sealing / compression tasks are not processed
190 // fast enough, and heuristically reduces the memory usage, especially for big compression factors.
191 std::size_t bufferedUncompressed = fBufferedUncompressed.load();
192 bool enoughWork = bufferedUncompressed > GetWriteOptions().GetApproxZippedClusterSize();
193
194 if (!fTaskScheduler || enoughWork) {
195 allocateBuf();
196 // Seal the page right now, avoiding the allocation and copy, but making sure that the page buffer is not aliased.
197 RSealPageConfig config;
198 config.fPage = &page;
199 config.fElement = &elem;
200 config.fCompressionSettings = GetWriteOptions().GetCompression();
201 config.fWriteChecksum = GetWriteOptions().GetEnablePageChecksums();
202 config.fAllowAlias = false;
203 config.fBuffer = zipItem.fBuf.get();
204 {
205 RNTupleAtomicTimer timer(fCounters->fTimeWallZip, fCounters->fTimeCpuZip);
206 sealedPage = SealPage(config);
207 }
208 shrinkSealedPage();
209 zipItem.fSealedPage = &sealedPage;
210 return;
211 }
212
213 // We will buffer the uncompressed page. Unless work is consumed fast enough, the next page might be compressed
214 // directly.
215 fBufferedUncompressed += page.GetNBytes();
216
217 // TODO avoid frequent (de)allocations by holding on to allocated buffers in RColumnBuf
218 zipItem.fPage = fPageAllocator.NewPage(page.GetElementSize(), page.GetNElements());
219 // make sure the page is aware of how many elements it will have
220 zipItem.fPage.GrowUnchecked(page.GetNElements());
221 assert(zipItem.fPage.GetNBytes() == page.GetNBytes());
222 memcpy(zipItem.fPage.GetBuffer(), page.GetBuffer(), page.GetNBytes());
223
224 fCounters->fParallelZip.SetValue(1);
225 // Thread safety: Each thread works on a distinct zipItem which owns its
226 // compression buffer.
227 fTaskScheduler->AddTask([this, &zipItem, &sealedPage, &elem, allocateBuf, shrinkSealedPage] {
228 // The task will consume the uncompressed page. Decrease the atomic counter early so that more work has arrived
229 // when we are done.
230 fBufferedUncompressed -= zipItem.fPage.GetNBytes();
231
232 allocateBuf();
233 RSealPageConfig config;
234 config.fPage = &zipItem.fPage;
235 config.fElement = &elem;
236 config.fCompressionSettings = GetWriteOptions().GetCompression();
237 config.fWriteChecksum = GetWriteOptions().GetEnablePageChecksums();
238 // Make sure the page buffer is not aliased so that we can free the uncompressed page.
239 config.fAllowAlias = false;
240 config.fBuffer = zipItem.fBuf.get();
241 // TODO: Somehow expose the time spent in zipping via the metrics. Wall time is tricky because the tasks run
242 // in parallel...
243 sealedPage = SealPage(config);
244 shrinkSealedPage();
245 zipItem.fSealedPage = &sealedPage;
246 // Release the uncompressed page. This works because the "page allocator must be thread-safe."
247 zipItem.fPage = RPage();
248 });
249}
250
252 const RSealedPage & /*sealedPage*/)
253{
254 throw RException(R__FAIL("should never commit sealed pages to RPageSinkBuf"));
255}
256
257void ROOT::Internal::RPageSinkBuf::CommitSealedPageV(std::span<ROOT::Internal::RSealedPageGroup> /*ranges*/)
258{
259 throw RException(R__FAIL("should never commit sealed pages to RPageSinkBuf"));
260}
261
262// We implement both StageCluster() and CommitCluster() because we can call CommitCluster() on the inner sink more
263// efficiently in a single critical section. For parallel writing, it also guarantees that we produce a fully sequential
264// file.
265void ROOT::Internal::RPageSinkBuf::FlushClusterImpl(const std::function<void(void)> &FlushClusterFn)
266{
267 WaitForAllTasks();
268 assert(fBufferedUncompressed == 0 && "all buffered pages should have been processed");
269
270 std::vector<RSealedPageGroup> toCommit;
271 toCommit.reserve(fBufferedColumns.size());
272 for (std::size_t physicalColumnId = 0; physicalColumnId < fBufferedColumns.size(); ++physicalColumnId) {
273 R__ASSERT(fBufferedColumns[physicalColumnId].HasSealedPagesOnly());
274 const auto &sealedPages = fBufferedColumns[physicalColumnId].GetSealedPages();
275 toCommit.emplace_back(physicalColumnId, sealedPages.cbegin(), sealedPages.cend());
276 }
277
278 {
279 RPageSink::RSinkGuard g(fInnerSink->GetSinkGuard());
280 RNTuplePlainTimer timer(fCounters->fTimeWallCriticalSection, fCounters->fTimeCpuCriticalSection);
281 fInnerSink->CommitSealedPageV(toCommit);
282
283 for (auto physicalColumnId : fSuppressedColumns)
284 fInnerSink->CommitSuppressedColumn(physicalColumnId);
285 fSuppressedColumns.clear();
286
287 FlushClusterFn();
288 }
289
290 for (auto &bufColumn : fBufferedColumns)
291 bufColumn.DropBufferedPages();
292}
293
295{
296 std::uint64_t nbytes;
297 FlushClusterImpl([&] { nbytes = fInnerSink->CommitCluster(nNewEntries); });
298 return nbytes;
299}
300
302{
303 RPageSink::RStagedCluster stagedCluster;
304 FlushClusterImpl([&] { stagedCluster = fInnerSink->StageCluster(nNewEntries); });
305 return stagedCluster;
306}
307
308void ROOT::Internal::RPageSinkBuf::CommitStagedClusters(std::span<RStagedCluster> clusters)
309{
310 RPageSink::RSinkGuard g(fInnerSink->GetSinkGuard());
311 RNTuplePlainTimer timer(fCounters->fTimeWallCriticalSection, fCounters->fTimeCpuCriticalSection);
312 fInnerSink->CommitStagedClusters(clusters);
313}
314
316{
317 RPageSink::RSinkGuard g(fInnerSink->GetSinkGuard());
318 RNTuplePlainTimer timer(fCounters->fTimeWallCriticalSection, fCounters->fTimeCpuCriticalSection);
319 fInnerSink->CommitClusterGroup();
320}
321
323{
324 RPageSink::RSinkGuard g(fInnerSink->GetSinkGuard());
325 RNTuplePlainTimer timer(fCounters->fTimeWallCriticalSection, fCounters->fTimeCpuCriticalSection);
326 return fInnerSink->CommitDataset();
327}
328
330{
331 return fInnerSink->ReservePage(column, nElements);
332}
333
334std::unique_ptr<ROOT::Internal::RPageSink>
336{
337 return fInnerSink->CloneAsHidden(name, opts);
338}
339
340void ROOT::Internal::RPageSinkBuf::CommitAttributeSet(std::string_view attrSetName, const RNTupleLink &attrAnchorInfo)
341{
342 fInnerSink->CommitAttributeSet(attrSetName, attrAnchorInfo);
343}
#define R__FAIL(msg)
Short-hand to return an RResult<T> in an error state; the RError is implicitly converted into RResult...
Definition RError.hxx:322
#define f(i)
Definition RSha256.hxx:104
#define g(i)
Definition RSha256.hxx:105
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:139
winID h TVirtualViewer3D TVirtualGLPainter p
char name[80]
Definition TGX11.cxx:142
A thread-safe integral performance counter.
A collection of Counter objects with a name, a unit, and a description.
void ObserveMetrics(RNTupleMetrics &observee)
CounterPtrT MakeCounter(const std::string &name, Args &&... args)
A non thread-safe integral performance counter.
Record wall time and CPU time between construction and destruction.
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
virtual void Wait()=0
Blocks until all scheduled tasks finished.
std::unique_ptr< RPageSink > CloneAsHidden(std::string_view name, const RNTupleWriteOptions &opts) const final
Creates a new sink with the same underlying storage as this but writing to a different RNTuple named ...
void CommitStagedClusters(std::span< RStagedCluster > clusters) final
Commit staged clusters, logically appending them to the ntuple descriptor.
std::unique_ptr< RCounters > fCounters
std::uint64_t CommitCluster(ROOT::NTupleSize_t nNewEntries) final
Finalize the current cluster and create a new one for the following data.
void UpdateSchema(const RNTupleModelChangeset &changeset, ROOT::NTupleSize_t firstEntry) final
Incorporate incremental changes to the model into the ntuple descriptor.
void FlushClusterImpl(const std::function< void(void)> &FlushClusterFn)
RNTupleTaskScheduler * fTaskScheduler
For parallel page compression.
void CommitSealedPage(ROOT::DescriptorId_t physicalColumnId, const RSealedPage &sealedPage) final
Write a preprocessed page to storage. The column must have been added before.
RPageSinkBuf(std::unique_ptr< RPageSink > inner)
void CommitPage(DescriptorId_t physicalColumnId, const RColumnElementBase &elem, const RPage &page) final
Write a page to the storage. The column must have been added before.
void CommitSuppressedColumn(DescriptorId_t physicalColumnId) final
Commits a suppressed column for the current cluster.
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...
RNTupleLink CommitDatasetImpl() final
const ROOT::RNTupleDescriptor & GetDescriptor() const final
Return the RNTupleDescriptor being constructed.
RPage ReservePage(RWriteColumn &column, std::size_t nElements) final
Get a new, empty page for the given column that can be filled with up to nElements; nElements must be...
void UpdateExtraTypeInfo(const ROOT::RExtraTypeInfoDescriptor &extraTypeInfo) final
Adds an extra type information record to schema.
DescriptorId_t AddColumn(ROOT::DescriptorId_t fieldId, const RColumn &column) final
Add a column belonging to a certain field to the descriptor and return its on-disk ID.
RStagedCluster StageCluster(ROOT::NTupleSize_t nNewEntries) final
Stage the current cluster and create a new one for the following data.
void CommitClusterGroup() final
Write out the page locations (page list envelope) for all the committed clusters since the last call ...
void InitImpl(ROOT::RNTupleModel &model) final
void CommitSealedPageV(std::span< RSealedPageGroup > ranges) final
Write a vector of preprocessed pages to storage. The corresponding columns must have been added befor...
std::unique_ptr< RPageSink > fInnerSink
The inner sink, responsible for actually performing I/O.
void ConnectFields(const std::vector< ROOT::RFieldBase * > &fields, ROOT::NTupleSize_t firstEntry)
An RAII wrapper used to synchronize a page sink. See GetSinkGuard().
Abstract interface to write data into an ntuple.
ROOT::Experimental::Detail::RNTupleMetrics fMetrics
A page is a slice of a column that is mapped into memory.
Definition RPage.hxx:43
std::uint32_t GetNElements() const
Definition RPage.hxx:120
std::size_t GetNBytes() const
The space taken by column elements in the buffer.
Definition RPage.hxx:111
void * GetBuffer() const
Definition RPage.hxx:142
std::uint32_t GetElementSize() const
Definition RPage.hxx:119
std::unordered_map< const ROOT::RFieldBase *, const ROOT::RFieldBase * > FieldMap_t
The map keys are the projected target fields, the map values are the backing source fields Note that ...
RResult< void > Add(std::unique_ptr< ROOT::RFieldBase > field, const FieldMap_t &fieldMap)
Adds a new projected field.
Base class for all ROOT issued exceptions.
Definition RError.hxx:78
Field specific extra type information from the header / extenstion header.
A field translates read and write calls from/to underlying columns to/from tree values.
The container field for an ntuple model, which itself has no physical representation.
Definition RField.hxx:58
The on-storage metadata of an RNTuple.
The RNTupleModel encapulates the schema of an RNTuple.
Common user-tunable settings for storing RNTuples.
The field for an untyped record.
virtual TObject * Clone(const char *newname="") const
Make a clone of an object using the Streamer facility.
Definition TObject.cxx:242
ROOT::RFieldZero & GetFieldZeroOfModel(RNTupleModel &model)
void AddItemToRecord(RRecordField &record, std::unique_ptr< RFieldBase > newItem)
Definition RField.cxx:647
RProjectedFields & GetProjectedFieldsOfModel(RNTupleModel &model)
void CallConnectPageSinkOnField(RFieldBase &, ROOT::Internal::RPageSink &, ROOT::NTupleSize_t firstEntry=0)
std::uint64_t DescriptorId_t
Distriniguishes elements of the same type within a descriptor, e.g. different fields.
std::uint64_t NTupleSize_t
Integer type long enough to hold the maximum number of entries in a column.
The incremental changes to a RNTupleModel
std::vector< ROOT::RFieldBase * > fAddedProjectedFields
Points to the projected fields in fModel that were added as part of an updater transaction.
std::vector< ROOT::RFieldBase * > fAddedFields
Points to the fields in fModel that were added as part of an updater transaction.
I/O performance counters that get registered in fMetrics.
Parameters for the SealPage() method.
bool fWriteChecksum
Adds a 8 byte little-endian xxhash3 checksum to the page payload.
std::uint32_t fCompressionSettings
Compression algorithm and level to apply.
void * fBuffer
Location for sealed output. The memory buffer has to be large enough.
const ROOT::Internal::RPage * fPage
Input page to be sealed.
bool fAllowAlias
If false, the output buffer must not point to the input page buffer, which would otherwise be an opti...
const ROOT::Internal::RColumnElementBase * fElement
Corresponds to the page's elements, for size calculation etc.
Cluster that was staged, but not yet logically appended to the RNTuple.
A sealed page contains the bytes of a page as written to storage (packed & compressed).
static constexpr std::size_t kNBytesPageChecksum
The page checksum is a 64bit xxhash3.