Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RClusterPool.cxx
Go to the documentation of this file.
1/// \file RClusterPool.cxx
2/// \ingroup NTuple
3/// \author Jakob Blomer <jblomer@cern.ch>
4/// \date 2020-03-11
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-2020, 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#include <ROOT/RClusterPool.hxx>
18#include <ROOT/RPageStorage.hxx>
19
20#include <TError.h>
21
22#include <algorithm>
23#include <chrono>
24#include <future>
25#include <iostream>
26#include <iterator>
27#include <map>
28#include <memory>
29#include <mutex>
30#include <set>
31#include <utility>
32
34{
35 if (fClusterKey.fClusterId == other.fClusterKey.fClusterId) {
36 if (fClusterKey.fPhysicalColumnSet.size() == other.fClusterKey.fPhysicalColumnSet.size()) {
37 for (auto itr1 = fClusterKey.fPhysicalColumnSet.begin(), itr2 = other.fClusterKey.fPhysicalColumnSet.begin();
39 if (*itr1 == *itr2)
40 continue;
41 return *itr1 < *itr2;
42 }
43 // *this == other
44 return false;
45 }
46 return fClusterKey.fPhysicalColumnSet.size() < other.fClusterKey.fPhysicalColumnSet.size();
47 }
48 return fClusterKey.fClusterId < other.fClusterKey.fClusterId;
49}
50
59
61{
62 {
63 // Controlled shutdown of the I/O thread
64 std::unique_lock<std::mutex> lock(fLockWorkQueue);
65 fReadQueue.emplace_back(RReadItem());
66 fCvHasReadWork.notify_one();
67 }
68 fThreadIo.join();
69}
70
72{
73 std::deque<RReadItem> readItems;
74 while (true) {
75 {
76 std::unique_lock<std::mutex> lock(fLockWorkQueue);
77 fCvHasReadWork.wait(lock, [&]{ return !fReadQueue.empty(); });
78 std::swap(readItems, fReadQueue);
79 }
80
81 while (!readItems.empty()) {
82 std::vector<RCluster::RKey> clusterKeys;
83 std::int64_t bunchId = -1;
84 for (unsigned i = 0; i < readItems.size(); ++i) {
85 const auto &item = readItems[i];
86 // `kInvalidDescriptorId` is used as a marker for thread cancellation. Such item causes the
87 // thread to terminate; thus, it must appear last in the queue.
88 if (R__unlikely(item.fClusterKey.fClusterId == ROOT::kInvalidDescriptorId)) {
89 R__ASSERT(i == (readItems.size() - 1));
90 return;
91 }
92 if ((bunchId >= 0) && (item.fBunchId != bunchId))
93 break;
94 bunchId = item.fBunchId;
95 clusterKeys.emplace_back(item.fClusterKey);
96 }
97
98 auto clusters = fPageSource.LoadClusters(clusterKeys);
99 for (std::size_t i = 0; i < clusters.size(); ++i) {
100 readItems[i].fPromise.set_value(std::move(clusters[i]));
101 }
102 readItems.erase(readItems.begin(), readItems.begin() + clusters.size());
103 }
104 } // while (true)
105}
106
108{
109 for (const auto &cptr : fPool) {
110 if (cptr && (cptr->GetId() == clusterId))
111 return cptr.get();
112 }
113 return nullptr;
114}
115
117{
118 auto N = fPool.size();
119 for (unsigned i = 0; i < N; ++i) {
120 if (!fPool[i])
121 return i;
122 }
123
124 R__ASSERT(false);
125 return N;
126}
127
128
129namespace {
130
131/// Helper class for the (cluster, column list) pairs that should be loaded in the background
132class RProvides {
134 using ColumnSet_t = ROOT::Internal::RCluster::ColumnSet_t;
135
136public:
137 struct RInfo {
138 std::int64_t fBunchId = -1;
139 std::int64_t fFlags = 0;
140 ColumnSet_t fPhysicalColumnSet;
141 };
142
143 static constexpr std::int64_t kFlagRequired = 0x01;
144 static constexpr std::int64_t kFlagLast = 0x02;
145
146private:
147 std::map<DescriptorId_t, RInfo> fMap;
148
149public:
150 void Insert(DescriptorId_t clusterId, const RInfo &info)
151 {
152 fMap.emplace(clusterId, info);
153 }
154
155 bool Contains(DescriptorId_t clusterId) {
156 return fMap.count(clusterId) > 0;
157 }
158
159 std::size_t GetSize() const { return fMap.size(); }
160
161 void Erase(DescriptorId_t clusterId, const ColumnSet_t &physicalColumns)
162 {
163 auto itr = fMap.find(clusterId);
164 if (itr == fMap.end())
165 return;
166 ColumnSet_t d;
167 std::copy_if(itr->second.fPhysicalColumnSet.begin(), itr->second.fPhysicalColumnSet.end(),
168 std::inserter(d, d.end()),
169 [&physicalColumns](DescriptorId_t needle) { return physicalColumns.count(needle) == 0; });
170 if (d.empty()) {
171 fMap.erase(itr);
172 } else {
173 itr->second.fPhysicalColumnSet = d;
174 }
175 }
176
177 decltype(fMap)::iterator begin() { return fMap.begin(); }
178 decltype(fMap)::iterator end() { return fMap.end(); }
179};
180
181} // anonymous namespace
182
185{
186 std::set<ROOT::DescriptorId_t> keep;
187 RProvides provide;
188 {
189 auto descriptorGuard = fPageSource.GetSharedDescriptorGuard();
190
191 // Determine previous cluster ids that we keep if they happen to be in the pool
192 auto prev = clusterId;
193 for (unsigned int i = 0; i < fWindowPre; ++i) {
194 prev = descriptorGuard->FindPrevClusterId(prev);
195 if (prev == ROOT::kInvalidDescriptorId)
196 break;
197 keep.insert(prev);
198 }
199
200 // Determine following cluster ids and the column ids that we want to make available
201 RProvides::RInfo provideInfo;
202 provideInfo.fPhysicalColumnSet = physicalColumns;
203 provideInfo.fBunchId = fBunchId;
204 provideInfo.fFlags = RProvides::kFlagRequired;
205 for (ROOT::DescriptorId_t i = 0, next = clusterId; i < 2 * fClusterBunchSize; ++i) {
206 if (i == fClusterBunchSize)
207 provideInfo.fBunchId = ++fBunchId;
208
209 auto cid = next;
210 next = descriptorGuard->FindNextClusterId(cid);
211 if (next != ROOT::kInvalidNTupleIndex) {
212 if (!fPageSource.GetEntryRange().IntersectsWith(descriptorGuard->GetClusterDescriptor(next)))
214 }
215 if (next == ROOT::kInvalidDescriptorId)
216 provideInfo.fFlags |= RProvides::kFlagLast;
217
218 provide.Insert(cid, provideInfo);
219
220 if (next == ROOT::kInvalidDescriptorId)
221 break;
222 provideInfo.fFlags = 0;
223 }
224 } // descriptorGuard
225
226 // Clear the cache from clusters not the in the look-ahead or the look-back window
227 for (auto &cptr : fPool) {
228 if (!cptr)
229 continue;
230 if (provide.Contains(cptr->GetId()) > 0)
231 continue;
232 if (keep.count(cptr->GetId()) > 0)
233 continue;
234 cptr.reset();
235 }
236
237 // Move clusters that meanwhile arrived into cache pool
238 {
239 // This lock is held during iteration over several data structures: the collection of in-flight clusters,
240 // the current pool of cached clusters, and the set of cluster ids to be preloaded.
241 // All three collections are expected to be small (certainly < 100, more likely < 10). All operations
242 // are non-blocking and moving around small items (pointers, ids, etc). Thus the overall locking time should
243 // still be reasonably small and the lock is rarely taken (usually once per cluster).
244 std::lock_guard<std::mutex> lockGuard(fLockWorkQueue);
245
246 for (auto itr = fInFlightClusters.begin(); itr != fInFlightClusters.end(); ) {
247 R__ASSERT(itr->fFuture.valid());
248 if (itr->fFuture.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {
249 // Remove the set of columns that are already scheduled for being loaded
250 provide.Erase(itr->fClusterKey.fClusterId, itr->fClusterKey.fPhysicalColumnSet);
251 ++itr;
252 continue;
253 }
254
255 auto cptr = itr->fFuture.get();
257
258 const bool isExpired =
259 !provide.Contains(itr->fClusterKey.fClusterId) && (keep.count(itr->fClusterKey.fClusterId) == 0);
260 if (isExpired) {
261 cptr.reset();
262 itr = fInFlightClusters.erase(itr);
263 continue;
264 }
265
266 // Noop unless the page source has a task scheduler
267 fPageSource.UnzipCluster(cptr.get());
268
269 // We either put a fresh cluster into a free slot or we merge the cluster with an existing one
270 auto existingCluster = FindInPool(cptr->GetId());
271 if (existingCluster) {
272 existingCluster->Adopt(std::move(*cptr));
273 } else {
274 auto idxFreeSlot = FindFreeSlot();
275 fPool[idxFreeSlot] = std::move(cptr);
276 }
277 itr = fInFlightClusters.erase(itr);
278 }
279
280 // Determine clusters which get triggered for background loading
281 for (auto &cptr : fPool) {
282 if (!cptr)
283 continue;
284 provide.Erase(cptr->GetId(), cptr->GetAvailPhysicalColumns());
285 }
286
287 // Figure out if enough work accumulated to justify I/O calls
288 bool skipPrefetch = false;
289 if (provide.GetSize() < fClusterBunchSize) {
290 skipPrefetch = true;
291 for (const auto &kv : provide) {
292 if ((kv.second.fFlags & (RProvides::kFlagRequired | RProvides::kFlagLast)) == 0)
293 continue;
294 skipPrefetch = false;
295 break;
296 }
297 }
298
299 // Update the work queue and the in-flight cluster list with new requests. We already hold the work queue
300 // mutex
301 // TODO(jblomer): we should ensure that clusterId is given first to the I/O thread. That is usually the
302 // case but it's not ensured by the code
303 if (!skipPrefetch) {
304 for (const auto &kv : provide) {
305 R__ASSERT(!kv.second.fPhysicalColumnSet.empty());
306
308 readItem.fClusterKey.fClusterId = kv.first;
309 readItem.fBunchId = kv.second.fBunchId;
310 readItem.fClusterKey.fPhysicalColumnSet = kv.second.fPhysicalColumnSet;
311
313 inFlightCluster.fClusterKey.fClusterId = kv.first;
314 inFlightCluster.fClusterKey.fPhysicalColumnSet = kv.second.fPhysicalColumnSet;
315 inFlightCluster.fFuture = readItem.fPromise.get_future();
316 fInFlightClusters.emplace_back(std::move(inFlightCluster));
317
318 fReadQueue.emplace_back(std::move(readItem));
319 }
320 if (!fReadQueue.empty())
321 fCvHasReadWork.notify_one();
322 }
323 } // work queue lock guard
324
325 return WaitFor(clusterId, physicalColumns);
326}
327
330{
331 while (true) {
332 // Fast exit: the cluster happens to be already present in the cache pool
333 auto result = FindInPool(clusterId);
334 if (result) {
335 bool hasMissingColumn = false;
336 for (auto cid : physicalColumns) {
337 if (result->ContainsColumn(cid))
338 continue;
339
340 hasMissingColumn = true;
341 break;
342 }
343 if (!hasMissingColumn)
344 return result;
345 }
346
347 // Otherwise the missing data must have been triggered for loading by now, so block and wait
348 decltype(fInFlightClusters)::iterator itr;
349 {
350 std::lock_guard<std::mutex> lockGuardInFlightClusters(fLockWorkQueue);
351 itr = fInFlightClusters.begin();
352 for (; itr != fInFlightClusters.end(); ++itr) {
353 if (itr->fClusterKey.fClusterId == clusterId)
354 break;
355 }
356 R__ASSERT(itr != fInFlightClusters.end());
357 // Note that the fInFlightClusters is accessed concurrently only by the I/O thread. The I/O thread
358 // never changes the structure of the in-flight clusters array (it does not add, remove, or swap elements).
359 // Therefore, it is safe to access the element pointed to by itr here even after fLockWorkQueue
360 // is released. We need to release the lock before potentially blocking on the cluster future.
361 }
362
363 auto cptr = itr->fFuture.get();
364 // We were blocked waiting for the cluster, so assume that nobody discarded it.
365 R__ASSERT(cptr != nullptr);
366
367 // Noop unless the page source has a task scheduler
368 fPageSource.UnzipCluster(cptr.get());
369
370 if (result) {
371 result->Adopt(std::move(*cptr));
372 } else {
373 auto idxFreeSlot = FindFreeSlot();
374 fPool[idxFreeSlot] = std::move(cptr);
375 }
376
377 std::lock_guard<std::mutex> lockGuardInFlightClusters(fLockWorkQueue);
378 fInFlightClusters.erase(itr);
379 }
380}
381
383{
384 while (true) {
385 decltype(fInFlightClusters)::iterator itr;
386 {
387 std::lock_guard<std::mutex> lockGuardInFlightClusters(fLockWorkQueue);
388 itr = fInFlightClusters.begin();
389 if (itr == fInFlightClusters.end())
390 return;
391 }
392
393 itr->fFuture.wait();
394
395 std::lock_guard<std::mutex> lockGuardInFlightClusters(fLockWorkQueue);
396 fInFlightClusters.erase(itr);
397 }
398}
#define R__unlikely(expr)
Definition RConfig.hxx:599
std::ios_base::fmtflags fFlags
#define d(i)
Definition RSha256.hxx:102
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:125
#define N
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Managed a set of clusters containing compressed and packed pages.
RCluster * WaitFor(ROOT::DescriptorId_t clusterId, const RCluster::ColumnSet_t &physicalColumns)
Returns the given cluster from the pool, which needs to contain at least the columns physicalColumns.
unsigned int fClusterBunchSize
The number of clusters that are being read in a single vector read.
void WaitForInFlightClusters()
Used by the unit tests to drain the queue of clusters to be preloaded.
std::vector< std::unique_ptr< RCluster > > fPool
The cache of clusters around the currently active cluster.
RCluster * FindInPool(ROOT::DescriptorId_t clusterId) const
Every cluster id has at most one corresponding RCluster pointer in the pool.
void ExecReadClusters()
The I/O thread routine, there is exactly one I/O thread in-flight for every cluster pool.
RCluster * GetCluster(ROOT::DescriptorId_t clusterId, const RCluster::ColumnSet_t &physicalColumns)
Returns the requested cluster either from the pool or, in case of a cache miss, lets the I/O thread l...
RClusterPool(ROOT::Internal::RPageSource &pageSource, unsigned int clusterBunchSize)
size_t FindFreeSlot() const
Returns an index of an unused element in fPool; callers of this function (GetCluster() and WaitFor())...
ROOT::Internal::RPageSource & fPageSource
Every cluster pool is responsible for exactly one page source that triggers loading of the clusters (...
std::thread fThreadIo
The I/O thread calls RPageSource::LoadClusters() asynchronously.
An in-memory subset of the packed and compressed pages of a cluster.
Definition RCluster.hxx:148
std::unordered_set< ROOT::DescriptorId_t > ColumnSet_t
Definition RCluster.hxx:150
Abstract interface to read data from an ntuple.
const_iterator begin() const
const_iterator end() const
void Erase(const T &that, std::vector< T > &v)
Erase that element from vector v
Definition Utils.hxx:192
std::uint64_t DescriptorId_t
Distriniguishes elements of the same type within a descriptor, e.g. different fields.
constexpr NTupleSize_t kInvalidNTupleIndex
constexpr DescriptorId_t kInvalidDescriptorId
Clusters that are currently being processed by the pipeline.
bool operator<(const RInFlightCluster &other) const
First order by cluster id, then by number of columns, than by the column ids in fColumns.
Request to load a subset of the columns of a particular cluster.
ROOT::DescriptorId_t fClusterId
Definition RCluster.hxx:153