From b3582e919b8a12c1645b893d0173b243f8a944e3 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 3 Dec 2026 11:42:06 +0100 Subject: [PATCH 01/26] DPL Analysis: use sentinel for end iterator in grouped combinations --- .../include/Framework/GroupedCombinations.h | 26 +++-- Framework/Core/test/benchmark_EventMixing.cxx | 109 ++++++++++++++++-- 2 files changed, 118 insertions(+), 17 deletions(-) diff --git a/Framework/Core/include/Framework/GroupedCombinations.h b/Framework/Core/include/Framework/GroupedCombinations.h index d8c6aea44f31d..104e88114cb77 100644 --- a/Framework/Core/include/Framework/GroupedCombinations.h +++ b/Framework/Core/include/Framework/GroupedCombinations.h @@ -56,6 +56,10 @@ struct GroupedCombinationsGenerator { using GroupedIteratorType = pack_to_tuple_t, pack>>; + /// End-of-iteration marker: the iterator itself knows when it is exhausted + struct GroupedSentinel { + }; + struct GroupedIterator : public GroupingPolicy { public: using reference = GroupedIteratorType&; @@ -149,6 +153,10 @@ struct GroupedCombinationsGenerator { { return !(*this == rh); } + bool operator==(GroupedSentinel) const + { + return this->mIsEnd; + } private: std::tuple getAssociatedTables() @@ -191,27 +199,27 @@ struct GroupedCombinationsGenerator { using iterator = GroupedIterator; using const_iterator = GroupedIterator; + using sentinel = GroupedSentinel; inline iterator begin() { return iterator(mBegin); } - inline iterator end() + inline sentinel end() { - return iterator(mEnd); + return {}; } inline const_iterator begin() const { return iterator(mBegin); } - inline const_iterator end() const + inline sentinel end() const { - return iterator(mEnd); + return {}; } GroupedCombinationsGenerator(const BP& binningPolicy, int catNeighbours, const T1& outsider, SliceCache* cache) - : mBegin(GroupingPolicy(binningPolicy, catNeighbours, outsider), cache), - mEnd(GroupingPolicy(binningPolicy, catNeighbours, outsider), cache) {} + : mBegin(GroupingPolicy(binningPolicy, catNeighbours, outsider), cache) {} template GroupedCombinationsGenerator(const BP& binningPolicy, int catNeighbours, const T1& outsider, const G& grouping, const std::tuple& associated, SliceCache* cache) : GroupedCombinationsGenerator(binningPolicy, catNeighbours, outsider, cache) @@ -226,13 +234,10 @@ struct GroupedCombinationsGenerator { void setTables(const G& grouping, const std::tuple& associated) { mBegin.setTables(grouping, associated); - mEnd.setTables(grouping, associated); - mEnd.moveToEnd(); } private: iterator mBegin; - iterator mEnd; }; template @@ -240,7 +245,8 @@ concept is_combinations_generator = requires(T t, typename T::g_t const& g, pack typename T::GroupedIterator; t.setTables(g, a); { t.begin() } -> std::same_as; - { t.end() } -> std::same_as; + { t.end() } -> std::same_as; + { t.begin() != t.end() } -> std::convertible_to; }; // Aliases for 2-particle correlations diff --git a/Framework/Core/test/benchmark_EventMixing.cxx b/Framework/Core/test/benchmark_EventMixing.cxx index 0e7e6839ee35e..986b7e756048b 100644 --- a/Framework/Core/test/benchmark_EventMixing.cxx +++ b/Framework/Core/test/benchmark_EventMixing.cxx @@ -14,6 +14,7 @@ #include "Framework/TableBuilder.h" #include "Framework/AnalysisDataModel.h" #include +#include #include #include #include @@ -66,11 +67,18 @@ static void BM_EventMixingTraditional(benchmark::State& state) } auto tableCol = colBuilder.finalize(); o2::aod::Collisions collisions{tableCol}; - std::uniform_int_distribution uniform_dist_col_ind(0, collisions.size()); + std::uniform_int_distribution uniform_dist_col_ind(0, collisions.size() - 1); + + // the slice cache requires tracks sorted by collision index + std::vector colIndices(numTracksPerEvent * state.range(0)); + for (auto& colIndex : colIndices) { + colIndex = uniform_dist_col_ind(e1); + } + std::sort(colIndices.begin(), colIndices.end()); auto rowWriterTrack = trackBuilder.cursor(); - for (auto i = 0; i < numTracksPerEvent * state.range(0); ++i) { - rowWriterTrack(0, uniform_dist_col_ind(e1), 0, + for (auto colIndex : colIndices) { + rowWriterTrack(0, colIndex, 0, uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1)); @@ -158,11 +166,18 @@ static void BM_EventMixingCombinations(benchmark::State& state) } auto tableCol = colBuilder.finalize(); o2::aod::Collisions collisions{tableCol}; - std::uniform_int_distribution uniform_dist_col_ind(0, collisions.size()); + std::uniform_int_distribution uniform_dist_col_ind(0, collisions.size() - 1); + + // the slice cache requires tracks sorted by collision index + std::vector colIndices(numTracksPerEvent * state.range(0)); + for (auto& colIndex : colIndices) { + colIndex = uniform_dist_col_ind(e1); + } + std::sort(colIndices.begin(), colIndices.end()); auto rowWriterTrack = trackBuilder.cursor(); - for (auto i = 0; i < numTracksPerEvent * state.range(0); ++i) { - rowWriterTrack(0, uniform_dist_col_ind(e1), 0, + for (auto colIndex : colIndices) { + rowWriterTrack(0, colIndex, 0, uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1)); @@ -172,7 +187,7 @@ static void BM_EventMixingCombinations(benchmark::State& state) int64_t count = 0; int64_t colCount = 0; - std::string key = "fIndex" + getLabelFromType(); + std::string key = "fIndex" + cutString(getLabelFromType()); ArrowTableSlicingCache atscache{{{getLabelFromType(), getMatcherFromTypeForKey(key), key}}}; auto s = atscache.updateCacheEntry(0, tableTrack); SliceCache cache{&atscache}; @@ -200,4 +215,84 @@ static void BM_EventMixingCombinations(benchmark::State& state) BENCHMARK(BM_EventMixingCombinations)->RangeMultiplier(2)->Range(4, 8 << maxPairsRange); +// Overhead of the grouped generator alone: many collisions, few tracks and no +// track pairs, so that setTables() and the per-step iterator cost dominate. +// ExplicitLoop compares against end() on every step, as many analyses do. +template +static void BM_EventMixingGeneratorOnly(benchmark::State& state) +{ + constexpr int numTracksPerEventSmall = 2; + std::default_random_engine e1(1234567891); + std::uniform_real_distribution uniform_dist(0.f, 1.f); + std::uniform_real_distribution uniform_dist_x(-0.065f, 0.073f); + std::uniform_real_distribution uniform_dist_y(-0.320f, 0.360f); + std::uniform_int_distribution uniform_dist_int(0, 5); + + std::vector xBins{VARIABLE_WIDTH, -0.064, -0.062, -0.060, 0.066, 0.068, 0.070, 0.072}; + std::vector yBins{VARIABLE_WIDTH, -0.320, -0.301, -0.300, 0.330, 0.340, 0.350, 0.360}; + using BinningType = ColumnBinningPolicy; + BinningType binningOnPositions{{xBins, yBins}, true}; + + TableBuilder colBuilder, trackBuilder; + auto rowWriterCol = colBuilder.cursor(); + for (auto i = 0; i < state.range(0); ++i) { + float x = uniform_dist_x(e1); + float y = uniform_dist_y(e1); + rowWriterCol(0, uniform_dist_int(e1), + x, y, uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist_int(e1), uniform_dist(e1), + uniform_dist_int(e1), + uniform_dist(e1), uniform_dist(e1)); + } + auto tableCol = colBuilder.finalize(); + o2::aod::Collisions collisions{tableCol}; + + auto rowWriterTrack = trackBuilder.cursor(); + for (auto colIndex = 0; colIndex < collisions.size(); ++colIndex) { + for (auto j = 0; j < numTracksPerEventSmall; ++j) { + rowWriterTrack(0, colIndex, 0, + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1)); + } + } + auto tableTrack = trackBuilder.finalize(); + o2::aod::StoredTracks tracks{tableTrack}; + + std::string key = "fIndex" + cutString(getLabelFromType()); + ArrowTableSlicingCache atscache{{{getLabelFromType(), getMatcherFromTypeForKey(key), key}}}; + auto s = atscache.updateCacheEntry(0, tableTrack); + SliceCache cache{&atscache}; + + int64_t colCount = 0; + int64_t trackCount = 0; + for (auto _ : state) { + colCount = 0; + trackCount = 0; + auto tracksTuple = std::make_tuple(tracks); + SameKindPair pair{binningOnPositions, numEventsToMix - 1, -1, collisions, tracksTuple, &cache}; + if constexpr (ExplicitLoop) { + for (auto it = pair.begin(); it != pair.end(); ++it) { + auto& [c1, tracks1, c2, tracks2] = *it; + trackCount += tracks1.size() + tracks2.size(); + colCount++; + } + } else { + for (auto& [c1, tracks1, c2, tracks2] : pair) { + trackCount += tracks1.size() + tracks2.size(); + colCount++; + } + } + benchmark::DoNotOptimize(colCount); + benchmark::DoNotOptimize(trackCount); + } + state.counters["Mixed collision pairs"] = colCount; + state.counters["Pairs/s"] = benchmark::Counter(static_cast(colCount) * state.iterations(), benchmark::Counter::kIsRate); +} + +BENCHMARK_TEMPLATE(BM_EventMixingGeneratorOnly, false)->RangeMultiplier(4)->Range(256, 4096); +BENCHMARK_TEMPLATE(BM_EventMixingGeneratorOnly, true)->RangeMultiplier(4)->Range(256, 4096); + BENCHMARK_MAIN(); From 4241a07de96ef2b397f86590f869ecdf01579c1d Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 3 Dec 2026 13:06:19 +0100 Subject: [PATCH 02/26] DPL Analysis: use sentinel for end iterator in combinations --- .../Core/include/Framework/ASoAHelpers.h | 23 ++++++---- Framework/Core/test/test_ASoAHelpers.cxx | 42 ++++++++++++++++--- 2 files changed, 50 insertions(+), 15 deletions(-) diff --git a/Framework/Core/include/Framework/ASoAHelpers.h b/Framework/Core/include/Framework/ASoAHelpers.h index 0449bdfdc2a0c..2ff7b19dedd84 100644 --- a/Framework/Core/include/Framework/ASoAHelpers.h +++ b/Framework/Core/include/Framework/ASoAHelpers.h @@ -1156,6 +1156,10 @@ struct CombinationsGenerator { using CombinationType = typename P::CombinationType; public: + /// End-of-iteration marker: the iterator itself knows when it is exhausted + struct CombinationsSentinel { + }; + struct CombinationsIterator : public P { public: using reference = CombinationType&; @@ -1195,38 +1199,39 @@ struct CombinationsGenerator { { return (lh.mIsEnd && rh.mIsEnd) || (lh.mCurrent == rh.mCurrent); } + bool operator==(CombinationsSentinel) const + { + return this->mIsEnd; + } }; using iterator = CombinationsIterator; using const_iterator = CombinationsIterator; + using sentinel = CombinationsSentinel; inline iterator begin() { return iterator(mBegin); } - inline iterator end() + inline sentinel end() { - return iterator(mEnd); + return {}; } inline const_iterator begin() const { return iterator(mBegin); } - inline const_iterator end() const + inline sentinel end() const { - return iterator(mEnd); + return {}; } CombinationsGenerator() = delete; - CombinationsGenerator(const P& policy) : mBegin(policy), mEnd(policy) - { - mEnd.moveToEnd(); - } + CombinationsGenerator(const P& policy) : mBegin(policy) {} ~CombinationsGenerator() = default; private: iterator mBegin; - iterator mEnd; }; template diff --git a/Framework/Core/test/test_ASoAHelpers.cxx b/Framework/Core/test/test_ASoAHelpers.cxx index 701dc0bbced50..5fdecedbfc1a8 100644 --- a/Framework/Core/test/test_ASoAHelpers.cxx +++ b/Framework/Core/test/test_ASoAHelpers.cxx @@ -154,7 +154,12 @@ TEST_CASE("CombinationsGeneratorConstruction") REQUIRE(!(comb2.begin() == comb2.end())); - auto endCombination = *(comb2.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endIt = comb2.begin(); + endIt.moveToEnd(); + REQUIRE(endIt == comb2.end()); + auto endCombination = *endIt; REQUIRE(!(static_cast(std::get<0>(endCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endCombination)).getIterator().mCurrentPos) == 8); REQUIRE(static_cast(std::get<0>(endCombination)).getIterator().mCurrentChunk == 0); @@ -189,7 +194,12 @@ TEST_CASE("CombinationsGeneratorConstruction") REQUIRE(!(comb2Filter.begin() == comb2Filter.end())); - auto endFilterCombination = *(comb2Filter.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endFilterIt = comb2Filter.begin(); + endFilterIt.moveToEnd(); + REQUIRE(endFilterIt == comb2Filter.end()); + auto endFilterCombination = *endFilterIt; REQUIRE(!(static_cast(std::get<0>(endFilterCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endFilterCombination)).getIterator().mCurrentPos) == -1); REQUIRE(static_cast(std::get<0>(endFilterCombination)).getIterator().mCurrentChunk == 0); @@ -214,7 +224,12 @@ TEST_CASE("CombinationsGeneratorConstruction") // Looks that mCurrentChunk is reset to 0 if an iterator goes too far // (the iterators before the end() have correct chunk numbers) - auto endConcatCombination = *(comb2Concat.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endConcatIt = comb2Concat.begin(); + endConcatIt.moveToEnd(); + REQUIRE(endConcatIt == comb2Concat.end()); + auto endConcatCombination = *endConcatIt; REQUIRE(!(static_cast(std::get<0>(endConcatCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endConcatCombination)).getIterator().mCurrentPos) == 12); REQUIRE(static_cast(std::get<0>(endConcatCombination)).getIterator().mCurrentChunk == 0); @@ -237,7 +252,12 @@ TEST_CASE("CombinationsGeneratorConstruction") REQUIRE(!(comb2Diff.begin() == comb2Diff.end())); - auto endDiffCombination = *(comb2Diff.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endDiffIt = comb2Diff.begin(); + endDiffIt.moveToEnd(); + REQUIRE(endDiffIt == comb2Diff.end()); + auto endDiffCombination = *endDiffIt; REQUIRE(!(static_cast(std::get<0>(endDiffCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endDiffCombination)).getIterator().mCurrentPos) == 8); REQUIRE(static_cast(std::get<0>(endDiffCombination)).getIterator().mCurrentChunk == 0); @@ -270,7 +290,12 @@ TEST_CASE("CombinationsGeneratorConstruction") // REQUIRE(comb2Bad.begin() == comb2Bad.end());; - auto endBadCombination = *(comb2Bad.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endBadIt = comb2Bad.begin(); + endBadIt.moveToEnd(); + REQUIRE(endBadIt == comb2Bad.end()); + auto endBadCombination = *endBadIt; REQUIRE(!(static_cast(std::get<0>(endBadCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endBadCombination)).getIterator().mCurrentPos) == 4); REQUIRE(static_cast(std::get<0>(endBadCombination)).getIterator().mCurrentChunk == 0); @@ -302,7 +327,12 @@ TEST_CASE("CombinationsGeneratorConstruction") REQUIRE(!(combBlock.begin() == combBlock.end())); - auto endBlockCombination = *(combBlock.end()); + // Tested below: a normal iterator moved to the end with moveToEnd(), not end(). + // end() returns a sentinel, which carries no row positions and cannot be dereferenced. + auto endBlockIt = combBlock.begin(); + endBlockIt.moveToEnd(); + REQUIRE(endBlockIt == combBlock.end()); + auto endBlockCombination = *endBlockIt; REQUIRE(!(static_cast(std::get<0>(endBlockCombination)).getIterator().mCurrentPos == nullptr)); REQUIRE(*(static_cast(std::get<0>(endBlockCombination)).getIterator().mCurrentPos) == 8); REQUIRE(static_cast(std::get<0>(endBlockCombination)).getIterator().mCurrentChunk == 0); From 19cd187cbacf22e4bab934d1f0facfd8bdfd7b76 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 3 Dec 2026 16:03:37 +0100 Subject: [PATCH 03/26] DPL Analysis: reuse column map when constructing tables and their slices --- Framework/Core/CMakeLists.txt | 1 + Framework/Core/include/Framework/ASoA.h | 179 +++++++++++++++--- .../Core/include/Framework/AnalysisHelpers.h | 9 +- .../Core/include/Framework/GroupSlicer.h | 4 +- .../include/Framework/GroupedCombinations.h | 9 +- Framework/Core/src/ASoA.cxx | 28 ++- 6 files changed, 183 insertions(+), 47 deletions(-) diff --git a/Framework/Core/CMakeLists.txt b/Framework/Core/CMakeLists.txt index b31e951bb7ec1..a356a9d4e0372 100644 --- a/Framework/Core/CMakeLists.txt +++ b/Framework/Core/CMakeLists.txt @@ -367,6 +367,7 @@ foreach(b ASoA ASoAHelpers EventMixing + SparseSlicing HistogramRegistry ExternalFairMQDeviceProxies ) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 05247000527c9..45740f8a76f5a 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -63,6 +63,8 @@ void accessingInvalidIndexFor(const char* getter); void dereferenceWithWrongType(const char* getter, const char* target); void missingFilterDeclaration(int hash, int ai); void notBoundTable(const char* tableName); +void parentTableMismatch(const char* tableName); +void incompatibleFilteredRanges(const char* tableName); void* extractCCDBPayload(char* payload, size_t size, TClass const* cl, const char* what); // ASCII-only lowercase. Column labels are plain identifiers, so we deliberately @@ -73,6 +75,16 @@ constexpr inline char asciiToLower(char c) return (c >= 'A' && c <= 'Z') ? static_cast(c + 32) : c; } +// Whether a column label names an arrow field: exactly (the common case: a +// length check and a memcmp) or ignoring the case. +inline bool labelMatches(std::string_view label, std::string_view name) +{ + return label == name || + std::ranges::equal(label, name, [](char c1, char c2) { + return asciiToLower(c1) == asciiToLower(c2); + }); +} + template auto createFieldsFromColumns(framework::pack) { @@ -1522,6 +1534,34 @@ static consteval auto extractBindings(framework::pack) SelectionVector selectionToVector(gandiva::Selection const& sel); +/// Whether the columns of Prefix are the first columns of Full, in the same order +template +consteval bool isColumnPrefix() +{ + if constexpr (framework::pack_size(Prefix{}) > framework::pack_size(Full{})) { + return false; + } else { + return [](std::index_sequence) { + return (std::same_as, framework::pack_element_t> && ...); + }(std::make_index_sequence{}); + } +} + +/// Make a table of type R on (a range of) the arrow table of parent. When the +/// columns of R start with the columns of parent, R reuses the column pointers +/// parent has already resolved; otherwise R resolves them from the arrow schema. +template +R makeTableOn(ArrowTableRef ref, P const& parent, Args&&... args) +{ + if constexpr (std::constructible_from) { + return R(ref, parent, std::forward(args)...); + } else if constexpr (std::constructible_from) { + return R(ref, std::forward(args)...); + } else { + return R(std::vector{ref}, std::forward(args)...); + } +} + template requires std::same_as && (o2::soa::is_binding_compatible_v()) auto doSliceBy(T const* table, o2::framework::PresliceBase const& container, int value) @@ -1532,7 +1572,7 @@ auto doSliceBy(T const* table, o2::framework::PresliceBase const } } auto out = container.getSliceFor(value, table->asArrowTableRef()); - auto t = typename T::self_t({out}); + auto t = makeTableOn(out, *table); if (t.tableSize() != 0) { table->copyIndexBindings(t); t.bindInternalIndicesTo(table); @@ -1543,7 +1583,7 @@ auto doSliceBy(T const* table, o2::framework::PresliceBase const template auto doSliceByHelper(T const* table, std::span const& selection) { - auto t = soa::Filtered({table->asArrowTableRef()}, selection); + auto t = makeTableOn>(table->asArrowTableRef(), *table, selection); if (t.tableSize() != 0) { table->copyIndexBindings(t); t.bindInternalIndicesTo(table); @@ -1556,7 +1596,7 @@ template requires(!soa::is_filtered_table) auto doSliceByHelper(T const* table, std::span const& selection) { - auto t = soa::Filtered({table->asArrowTableRef()}, selection); + auto t = makeTableOn>(table->asArrowTableRef(), *table, selection); if (t.tableSize() != 0) { table->copyIndexBindings(t); t.bindInternalIndicesTo(table); @@ -1583,14 +1623,14 @@ template auto prepareFilteredSlice(T const* table, o2::soa::ArrowTableRef slice) { if (slice.range.offset >= static_cast(table->tableSize())) { - Filtered fresult{{slice}, SelectionVector{}}; + auto fresult = makeTableOn>(slice, *table, SelectionVector{}); if (fresult.tableSize() != 0) { table->copyIndexBindings(fresult); } return fresult; } auto slicedSelection = sliceSelection(table->getSelectedRows(), slice.range.size, slice.range.offset); - Filtered fresult{{slice}, std::move(slicedSelection)}; + auto fresult = makeTableOn>(slice, *table, std::move(slicedSelection)); if (fresult.tableSize() != 0) { table->copyIndexBindings(fresult); } @@ -1618,7 +1658,7 @@ auto doSliceByCached(T const* table, framework::expressions::BindingNode const& auto localCache = cache.ptr->getCacheFor({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), node.name}); auto [offset, count] = localCache.getSliceFor(value); - auto t = typename T::self_t({table->asArrowTableRef().slice({static_cast(offset), count})}); + auto t = makeTableOn(table->asArrowTableRef().slice({static_cast(offset), count}), *table); if (t.tableSize() != 0) { table->copyIndexBindings(t); } @@ -1640,14 +1680,14 @@ auto doSliceByCachedUnsorted(T const* table, framework::expressions::BindingNode auto localCache = cache.ptr->getCacheUnsortedFor({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), node.name}); if constexpr (soa::is_filtered_table) { - auto t = typename T::self_t({table->asArrowTableRef()}, localCache.getSliceFor(value)); + auto t = makeTableOn(table->asArrowTableRef(), *table, localCache.getSliceFor(value)); if (t.tableSize() != 0) { t.intersectWithSelection(table->getSelectedRows()); table->copyIndexBindings(t); } return t; } else { - auto t = Filtered({table->asArrowTableRef()}, localCache.getSliceFor(value)); + auto t = makeTableOn>(table->asArrowTableRef(), *table, localCache.getSliceFor(value)); if (t.tableSize() != 0) { table->copyIndexBindings(t); } @@ -1658,10 +1698,11 @@ auto doSliceByCachedUnsorted(T const* table, framework::expressions::BindingNode template auto select(T const& t, framework::expressions::Filter const& f) { - return Filtered({t.asArrowTableRef()}, selectionToVector(framework::expressions::createSelection(t.asArrowTable(), f))); + return makeTableOn>(t.asArrowTableRef(), t, selectionToVector(framework::expressions::createSelection(t.asArrowTable(), f))); } arrow::ChunkedArray* getIndexFromLabel(arrow::Table* table, std::string_view label); +int getPositionFromLabel(arrow::Table* table, std::string_view label); template consteval auto base_iter(framework::pack&&) -> TableIterator @@ -1758,6 +1799,9 @@ class Table } using columns_t = decltype(getColumns()); + /// Columns in the order of the resolved column pointers (getColumnChunks()), + /// kept here because derived tables may redefine columns_t + using chunk_columns_t = columns_t; static constexpr auto column_hashes = [](framework::pack) consteval { auto hashes = std::array{C::hash...}; @@ -1967,6 +2011,29 @@ class Table } } + /// Construct on (a range of) the arrow table of a parent table whose columns + /// are the first columns of this one, reusing the column pointers the parent + /// has already resolved instead of looking them up by label. Columns past the + /// parent's (e.g. dynamic columns added by Attach) have no backing array. + template + requires(isColumnPrefix()) + Table(o2::soa::ArrowTableRef tableRef, P const& parent) + : mArrowTableRef(tableRef), + mEnd{tableRef.range.size} + { + if (O2_BUILTIN_UNLIKELY(tableRef.tablePtr != parent.asArrowTableRef().tablePtr)) { + parentTableMismatch(o2::aod::label()); + } + auto inheritedEnd = std::ranges::copy(parent.getColumnChunks(), std::begin(mColumnChunks)).out; + std::fill(inheritedEnd, std::end(mColumnChunks), nullptr); + if (mArrowTableRef.tablePtr->num_rows() == 0) { + mBegin = mEnd; + } else { + mBegin = unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}}; + mBegin.bindInternalIndices(this); + } + } + Table(std::shared_ptr table) : Table(o2::soa::ArrowTableRef{table}) { @@ -2082,6 +2149,12 @@ class Table { return mArrowTableRef; } + + /// Column pointers resolved for the arrow table, in the order of chunk_columns_t + [[nodiscard]] std::span getColumnChunks() const + { + return std::span{mColumnChunks}; + } /// Return offset auto offset() const { @@ -2176,12 +2249,12 @@ class Table auto rawSlice(uint64_t start, uint64_t end) const { - return self_t{mArrowTableRef.slice({start, static_cast(end - start + 1)})}; + return makeTableOn(mArrowTableRef.slice({start, static_cast(end - start + 1)}), *this); } auto emptySlice() const { - return self_t{mArrowTableRef.makeEmpty()}; + return makeTableOn(mArrowTableRef.makeEmpty(), *this); } void setPointerReconstructor(framework::PointerReconstructor const& pointerReconstructor) @@ -2199,7 +2272,15 @@ class Table template arrow::ChunkedArray* lookupColumn() { - return getIndexFromLabel(mArrowTableRef.tablePtr.get(), T::columnLabel()); + // Schemas do not change during a run: try the position the column had in + // the last arrow table this type was made from, and look it up by label + // only when the field there has a different name. + static thread_local int position = -1; + auto* table = mArrowTableRef.tablePtr.get(); + if (position < 0 || position >= table->num_columns() || !labelMatches(T::columnLabel(), table->schema()->field(position)->name())) { + position = getPositionFromLabel(table, T::columnLabel()); + } + return table->column(position).get(); } ArrowTableRef mArrowTableRef; @@ -3416,6 +3497,16 @@ struct Join : Table, o2::aod::Hash<"JOIN/0"_h>, o2::aod: } } + template + requires(std::constructible_from) + Join(ArrowTableRef table, P const& parent) + : base{table, parent} + { + if (this->tableSize() != 0) { + bindInternalIndicesTo(this); + } + } + using base::bindExternalIndices; using base::bindInternalIndicesTo; static constexpr const uint32_t binding_origin = base::binding_origin; @@ -3485,12 +3576,12 @@ struct Join : Table, o2::aod::Hash<"JOIN/0"_h>, o2::aod: auto rawSlice(uint64_t start, uint64_t end) const { - return self_t{{this->asArrowTableRef().slice({start, static_cast(end - start + 1)})}}; + return makeTableOn(this->asArrowTableRef().slice({start, static_cast(end - start + 1)}), *this); } auto emptySlice() const { - return self_t{{this->asArrowTableRef().slice({0, 0})}}; + return makeTableOn(this->asArrowTableRef().slice({0, 0}), *this); } template @@ -3603,6 +3694,19 @@ class FilteredBase : public T mFilteredBegin.bindInternalIndices(this); } + template + requires(std::constructible_from) + FilteredBase(ArrowTableRef table, P const& parent, is_a_selection auto selection) + : T{table, parent} + { + adoptSelection(selection); + if (this->tableSize() != 0) { + mFilteredBegin = table_t::filtered_begin(mSelectedRows); + } + resetRanges(); + mFilteredBegin.bindInternalIndices(this); + } + iterator begin() { return iterator(mFilteredBegin); @@ -3660,12 +3764,12 @@ class FilteredBase : public T SelectionVector newSelection; newSelection.resize(static_cast(end - start + 1)); std::iota(newSelection.begin(), newSelection.end(), start); - return self_t{{this->asArrowTableRef()}, std::move(newSelection)}; + return makeTableOn(this->asArrowTableRef(), *this, std::move(newSelection)); } auto emptySlice() const { - return self_t{{this->asArrowTableRef()}, SelectionVector{}}; + return makeTableOn(this->asArrowTableRef(), *this, SelectionVector{}); } static inline auto getSpan(gandiva::Selection const& sel) @@ -3855,6 +3959,11 @@ class Filtered : public FilteredBase Filtered(std::vector&& tables, is_a_selection auto selection) : FilteredBase{std::move(tables), std::forward(selection)} {} + template + requires(std::constructible_from) + Filtered(ArrowTableRef table, P const& parent, is_a_selection auto selection) + : FilteredBase{table, parent, std::forward(selection)} {} + Filtered operator+(is_a_selection auto selection) { Filtered copy(*this); @@ -3915,12 +4024,12 @@ class Filtered : public FilteredBase SelectionVector newSelection; newSelection.resize(static_cast(end - start + 1)); std::iota(newSelection.begin(), newSelection.end(), start); - return self_t{{this->asArrowTableRef()}, std::move(newSelection)}; + return makeTableOn(this->asArrowTableRef(), *this, std::move(newSelection)); } auto emptySlice() const { - return self_t{{this->asArrowTableRef()}, SelectionVector{}}; + return makeTableOn(this->asArrowTableRef(), *this, SelectionVector{}); } template @@ -3982,14 +4091,21 @@ class Filtered> : public FilteredBase return const_iterator(this->cached_begin()); } + /// The result is the rows of the first table that pass the selections of + /// all the tables, so it reuses the columns the first table has resolved. Filtered(std::vector>&& tables, is_a_selection auto selection) - : FilteredBase(std::move(extractTablesFromFiltered(tables)), std::forward(selection)) + : FilteredBase(commonTable(tables), tables.front(), std::forward(selection)) { for (auto& table : tables) { *this *= table; } } + template + requires(std::constructible_from) + Filtered(ArrowTableRef table, P const& parent, is_a_selection auto selection) + : FilteredBase{table, parent, std::forward(selection)} {} + Filtered> operator+(is_a_selection auto selection) { Filtered> copy(*this); @@ -4048,12 +4164,12 @@ class Filtered> : public FilteredBase SelectionVector newSelection; newSelection.resize(static_cast(end - start + 1)); std::iota(newSelection.begin(), newSelection.end(), start); - return self_t{{this->asArrowTableRef()}, std::move(newSelection)}; + return makeTableOn(this->asArrowTableRef(), *this, std::move(newSelection)); } auto emptySlice() const { - return self_t{{this->asArrowTableRef()}, SelectionVector{}}; + return makeTableOn(this->asArrowTableRef(), *this, SelectionVector{}); } auto sliceByCached(framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) const @@ -4079,13 +4195,17 @@ class Filtered> : public FilteredBase } private: - std::vector extractTablesFromFiltered(std::vector>& tables) - { - std::vector outTables; - for (auto& table : tables) { - outTables.push_back(table.asArrowTableRef()); + /// The arrow table of the first table, which all the tables have to share + /// the range of for their selections to be combined + static ArrowTableRef commonTable(std::vector> const& tables) + { + auto ref = tables.front().asArrowTableRef(); + for (auto const& table : tables) { + if (table.asArrowTableRef().range != ref.range) { + incompatibleFilteredRanges(o2::aod::label()); + } } - return outTables; + return ref; } }; @@ -4145,6 +4265,11 @@ struct SmallGroupsBase : public Filtered { SmallGroupsBase(std::vector&& tables, is_a_selection auto selection) : Filtered(std::move(tables), selection) {} + + template + requires(std::constructible_from) + SmallGroupsBase(ArrowTableRef table, P const& parent, is_a_selection auto selection) + : Filtered(table, parent, selection) {} }; template diff --git a/Framework/Core/include/Framework/AnalysisHelpers.h b/Framework/Core/include/Framework/AnalysisHelpers.h index 6071e8291e387..44b370ed56860 100644 --- a/Framework/Core/include/Framework/AnalysisHelpers.h +++ b/Framework/Core/include/Framework/AnalysisHelpers.h @@ -964,7 +964,7 @@ auto getTableFromFilter(soa::is_filtered_table auto const& table, soa::Selection auto getTableFromFilter(soa::is_not_filtered_table auto const& table, soa::SelectionVector&& selection) { - return std::make_unique>>(std::vector{table.asArrowTableRef()}, std::forward(selection)); + return std::make_unique>>(o2::soa::makeTableOn>>(table.asArrowTableRef(), table, std::forward(selection))); } void initializePartitionCaches(std::span hashes, std::shared_ptr const& schema, expressions::Filter const& filter, gandiva::NodePtr& tree, gandiva::FilterPtr& gfilter); @@ -1104,12 +1104,15 @@ auto Extend(T const& table) } /// Template function to attach dynamic columns on-the-fly (e.g. inside -/// process() function). Dynamic columns need to be compatible with the table. +/// process() function). Dynamic columns need to be compatible with the table +/// and must not be in it already. The result reuses the columns the table has +/// resolved, as the attached columns follow them and have no backing arrays. template + requires((!framework::has_type_v && ...)) auto Attach(T const& table) { using output_t = Join, o2::aod::Hash<"JOIN/0"_h>, o2::aod::Hash<"JOIN"_h>, Cs...>>; - return output_t{{table.asArrowTableRef()}}; + return output_t{table.asArrowTableRef(), table}; } } // namespace o2::soa diff --git a/Framework/Core/include/Framework/GroupSlicer.h b/Framework/Core/include/Framework/GroupSlicer.h index f06cd6a0cd916..6309daf0f874f 100644 --- a/Framework/Core/include/Framework/GroupSlicer.h +++ b/Framework/Core/include/Framework/GroupSlicer.h @@ -194,7 +194,7 @@ struct GroupSlicer { } } } - std::decay_t typedTable{{originalTable.asArrowTableRef()}, std::move(s)}; + auto typedTable = soa::makeTableOn>(originalTable.asArrowTableRef(), originalTable, std::move(s)); typedTable.bindInternalIndicesTo(&originalTable); return typedTable; } @@ -230,7 +230,7 @@ struct GroupSlicer { return idx - static_cast(offset); }); - std::decay_t typedTable{{groupedElementsTable}, std::move(slicedSelection)}; + auto typedTable = soa::makeTableOn>(groupedElementsTable, originalTable, std::move(slicedSelection)); typedTable.bindInternalIndicesTo(&originalTable); return typedTable; } diff --git a/Framework/Core/include/Framework/GroupedCombinations.h b/Framework/Core/include/Framework/GroupedCombinations.h index 104e88114cb77..072181b153842 100644 --- a/Framework/Core/include/Framework/GroupedCombinations.h +++ b/Framework/Core/include/Framework/GroupedCombinations.h @@ -74,15 +74,14 @@ struct GroupedCombinationsGenerator { template GroupedIterator(const GroupingPolicy& groupingPolicy, const G& grouping, const std::tuple& associated, SliceCache* cache_) : GroupingPolicy(groupingPolicy), - mGrouping{std::make_shared(std::vector{grouping.asArrowTableRef()})}, mAssociated{std::make_shared>(std::make_tuple(std::get(pack{})>(associated)...))}, mIndexColumns{getMatchingIndexNode()...}, cache{cache_} { if constexpr (soa::is_filtered_table>) { - mGrouping = std::make_shared(std::vector{grouping.asArrowTableRef()}, grouping.getSelectedRows()); + mGrouping = std::make_shared(soa::makeTableOn(grouping.asArrowTableRef(), grouping, grouping.getSelectedRows())); } else { - mGrouping = std::make_shared(std::vector{grouping.asArrowTableRef()}); + mGrouping = std::make_shared(soa::makeTableOn(grouping.asArrowTableRef(), grouping)); } setMultipleGroupingTables(grouping); if (!this->mIsEnd) { @@ -98,9 +97,9 @@ struct GroupedCombinationsGenerator { void setTables(const G& grouping, const std::tuple& associated) { if constexpr (soa::is_filtered_table>) { - mGrouping = std::make_shared(std::vector{grouping.asArrowTableRef()}, grouping.getSelectedRows()); + mGrouping = std::make_shared(soa::makeTableOn(grouping.asArrowTableRef(), grouping, grouping.getSelectedRows())); } else { - mGrouping = std::make_shared(std::vector{grouping.asArrowTableRef()}); + mGrouping = std::make_shared(soa::makeTableOn(grouping.asArrowTableRef(), grouping)); } mAssociated = std::make_shared>(std::make_tuple(std::get(pack{})>(associated)...)); setMultipleGroupingTables(grouping); diff --git a/Framework/Core/src/ASoA.cxx b/Framework/Core/src/ASoA.cxx index 9c0821dbd0462..558d1a496d80b 100644 --- a/Framework/Core/src/ASoA.cxx +++ b/Framework/Core/src/ASoA.cxx @@ -216,22 +216,30 @@ o2::soa::ArrowTableRef ArrowHelpers::concatTables(std::vector(resultFields), columns)}; } -arrow::ChunkedArray* getIndexFromLabel(arrow::Table* table, std::string_view label) +int getPositionFromLabel(arrow::Table* table, std::string_view label) { - // Take the exact-match common case first (string_view comparison checks length - // then memcmp), and fall back to a case-insensitive scan only when the labels - // differ in case. auto field = std::ranges::find_if(table->schema()->fields(), [label](std::shared_ptr const& f) { - std::string_view name = f->name(); - return label == name || - std::ranges::equal(label, name, [](char c1, char c2) { - return asciiToLower(c1) == asciiToLower(c2); - }); + return labelMatches(label, f->name()); }); if (field == table->schema()->fields().end()) { o2::framework::throw_error(o2::framework::runtime_error_f("Unable to find column with label %s.", label)); } - return table->column(std::distance(table->schema()->fields().begin(), field)).get(); + return static_cast(std::distance(table->schema()->fields().begin(), field)); +} + +arrow::ChunkedArray* getIndexFromLabel(arrow::Table* table, std::string_view label) +{ + return table->column(getPositionFromLabel(table, label)).get(); +} + +void parentTableMismatch(const char* tableName) +{ + throw o2::framework::runtime_error_f("Table %s can only reuse the columns of a parent table that refers to the same arrow table.", tableName); +} + +void incompatibleFilteredRanges(const char* tableName) +{ + throw o2::framework::runtime_error_f("Filtered %s tables cover different row ranges and their selections cannot be combined.", tableName); } void notBoundTable(const char* tableName) From e1d17df8d3bb4952325202c87a8c41fd5e7d9842 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 3 Dec 2026 19:27:19 +0100 Subject: [PATCH 04/26] DPL Analysis: reuse column iterators when constructing table slices --- Framework/Core/include/Framework/ASoA.h | 66 +++++++++++++++++++++++-- 1 file changed, 63 insertions(+), 3 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 45740f8a76f5a..43bbe9480e40f 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -1074,6 +1074,23 @@ struct TableIterator : IP, C... { this->limitRange(this->rangeStart(), this->rangeEnd()); } + /// Construct with a new index policy, copying the column iterators of + /// another, already constructed, iterator on the same arrow table instead + /// of creating them from the ChunkedArrays. Columns the other iterator does + /// not have (e.g. dynamic columns added by Attach) are made from columnData. + template + TableIterator(arrow::ChunkedArray* columnData[sizeof...(C)], IP&& policy, Other const& other) + : IP{policy}, + C(columnFrom(columnData, other))... + { + if (this->size() != 0) { + bind(); + } + if constexpr (has_index) { + this->limitRange(this->rangeStart(), this->rangeEnd()); + } + } + TableIterator() = default; TableIterator(self_t const& other) : IP{static_cast(other)}, @@ -1222,6 +1239,16 @@ struct TableIterator : IP, C... { } private: + template + static CC columnFrom(arrow::ChunkedArray* columnData[sizeof...(C)], Other const& other) + { + if constexpr (std::is_base_of_v) { + return static_cast(other); + } else { + return CC(columnData[framework::has_type_at_v(all_columns{})]); + } + } + /// Helper to move at the end of columns which actually have an iterator. template void doMoveToEnd(framework::pack) @@ -1833,6 +1860,12 @@ class Table { } + template + TableIteratorBase(arrow::ChunkedArray* columnData[framework::pack_size(columns_t{})], IP&& policy, Other const& other) + : base_iterator(columnData, std::forward(policy), other) + { + } + template TableIteratorBase& operator=(TableIteratorBase other) requires(P::ref.desc_hash == Parent::ref.desc_hash) @@ -2006,8 +2039,13 @@ class Table for (size_t ci = 0; ci < framework::pack_size(columns_t{}); ++ci) { mColumnChunks[ci] = lookups[ci]; } - mBegin = unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}}; - mBegin.bindInternalIndices(this); + if (mEnd.index == 0) { + // empty range: nothing to iterate, begin is already at the end + mBegin = mEnd; + } else { + mBegin = unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}}; + mBegin.bindInternalIndices(this); + } } } @@ -2026,8 +2064,13 @@ class Table } auto inheritedEnd = std::ranges::copy(parent.getColumnChunks(), std::begin(mColumnChunks)).out; std::fill(inheritedEnd, std::end(mColumnChunks), nullptr); - if (mArrowTableRef.tablePtr->num_rows() == 0) { + if (mEnd.index == 0) { + // empty range: nothing to iterate, begin is already at the end mBegin = mEnd; + } else if (parent.hasCachedBegin()) { + // copy the parent's column iterators and only position the copy on the range + mBegin = unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}, parent.cachedUnfilteredBegin()}; + mBegin.bindInternalIndices(this); } else { mBegin = unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}}; mBegin.bindInternalIndices(this); @@ -2109,9 +2152,26 @@ class Table // is held by the table, so we are safe passing the bare pointer. If it does it // means that the iterator on a table is outliving the table itself, which is // a bad idea. + if (hasCachedBegin()) { + return filtered_iterator(mColumnChunks, {selection, mArrowTableRef.tablePtr->num_rows(), mArrowTableRef.range.offset}, mBegin); + } return filtered_iterator(mColumnChunks, {selection, mArrowTableRef.tablePtr->num_rows(), mArrowTableRef.range.offset}); } + /// Whether the cached begin iterator holds constructed column iterators, + /// which is the case for every table with a non-empty range + [[nodiscard]] bool hasCachedBegin() const + { + return mEnd.index != 0; + } + + /// The cached begin iterator over all rows of the range, also for filtered + /// tables, which override cached_begin() + [[nodiscard]] auto const& cachedUnfilteredBegin() const + { + return mBegin; + } + iterator iteratorAt(uint64_t i) const { return rawIteratorAt(i); From 485120cb55a4059197e0ea898a75265e2d766166 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 3 Dec 2026 20:38:38 +0100 Subject: [PATCH 05/26] DPL Analysis: avoid copies in GroupSlicer process arguments return --- .../Core/include/Framework/AnalysisTask.h | 35 +++++++---------- .../Core/include/Framework/GroupSlicer.h | 21 ++++------ Framework/Core/test/test_GroupSlicer.cxx | 38 +++++++------------ 3 files changed, 35 insertions(+), 59 deletions(-) diff --git a/Framework/Core/include/Framework/AnalysisTask.h b/Framework/Core/include/Framework/AnalysisTask.h index bfd67a03ecbc1..90527315a8cf8 100644 --- a/Framework/Core/include/Framework/AnalysisTask.h +++ b/Framework/Core/include/Framework/AnalysisTask.h @@ -398,29 +398,22 @@ struct AnalysisDataProcessorBuilder { if constexpr (soa::is_iterator) { auto slicer = GroupSlicer(groupingTable, associatedTables, slices, newOrigin); for (auto& slice : slicer) { - auto associatedSlices = slice.associatedTables(); - std::apply([&pointerReconstructor](auto&... table) { - (table.setPointerReconstructor(pointerReconstructor), ...); - }, - associatedSlices); - - overwriteInternalIndices(associatedSlices, associatedTables); - std::apply( - [&binder](auto&... x) mutable { - (binder(x), ...); + // the slices are passed as prvalues and bound to the parameters + // directly, so that they are not copied on their way to the process function + [&](auto&&... associatedSlices) { + (associatedSlices.setPointerReconstructor(pointerReconstructor), ...); + (associatedSlices.bindInternalIndicesTo(&std::get>(associatedTables)), ...); + (binder(associatedSlices), ...); + + // bind partitions and grouping table + homogeneous_apply_refs_sized([&groupingTable](auto& x) { + analysis_task_parsers::bindExternalIndicesPartition(x, &groupingTable); + return true; }, - associatedSlices); - - // bind partitions and grouping table - homogeneous_apply_refs_sized([&groupingTable](auto& x) { - analysis_task_parsers::bindExternalIndicesPartition(x, &groupingTable); - return true; - }, - task); + task); - [](Task& task, void (Task::*processingFunction)(Grouping, Associated...), Grouping g, std::tuple...>& at) { - std::invoke(processingFunction, task, g, std::get>(at)...); - }(task, processingFunction, slice.groupingElement(), associatedSlices); + std::invoke(processingFunction, task, slice.groupingElement(), associatedSlices...); + }(slice.template prepareArgument>()...); } } else { // bind partitions and grouping table diff --git a/Framework/Core/include/Framework/GroupSlicer.h b/Framework/Core/include/Framework/GroupSlicer.h index 6309daf0f874f..a12791555501b 100644 --- a/Framework/Core/include/Framework/GroupSlicer.h +++ b/Framework/Core/include/Framework/GroupSlicer.h @@ -160,11 +160,10 @@ struct GroupSlicer { return *this; } - auto associatedTables() - { - return std::make_tuple(prepareArgument()...); - } - + /// The associated table A1 for the current grouping element: a slice for + /// tables related to the grouping table, otherwise the full table. Slices are + /// returned as prvalues, so that the caller can bind them without a copy; + /// their internal indices still need to be bound to the full table. template requires(o2::soa::relatedByIndex, std::decay_t>() && soa::is_filtered_table) auto prepareArgument() @@ -194,9 +193,7 @@ struct GroupSlicer { } } } - auto typedTable = soa::makeTableOn>(originalTable.asArrowTableRef(), originalTable, std::move(s)); - typedTable.bindInternalIndicesTo(&originalTable); - return typedTable; + return soa::makeTableOn>(originalTable.asArrowTableRef(), originalTable, std::move(s)); } template @@ -230,9 +227,7 @@ struct GroupSlicer { return idx - static_cast(offset); }); - auto typedTable = soa::makeTableOn>(groupedElementsTable, originalTable, std::move(slicedSelection)); - typedTable.bindInternalIndicesTo(&originalTable); - return typedTable; + return soa::makeTableOn>(groupedElementsTable, originalTable, std::move(slicedSelection)); } template @@ -252,9 +247,7 @@ struct GroupSlicer { } // optimized split auto [offset, count] = sliceInfos[index].getSliceFor(pos); - auto groupedElementsTable = originalTable.rawSlice(offset, offset + count - 1); - groupedElementsTable.bindInternalIndicesTo(&originalTable); - return groupedElementsTable; + return soa::makeTableOn>(originalTable.asArrowTableRef().slice({static_cast(offset), static_cast(count)}), originalTable); } template diff --git a/Framework/Core/test/test_GroupSlicer.cxx b/Framework/Core/test/test_GroupSlicer.cxx index c81acb6c7c85c..c8c420dca4870 100644 --- a/Framework/Core/test/test_GroupSlicer.cxx +++ b/Framework/Core/test/test_GroupSlicer.cxx @@ -123,10 +123,9 @@ TEST_CASE("GroupSlicerOneAssociated") auto count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == count); - auto trks = std::get(as); + auto trks = slice.prepareArgument(); REQUIRE(trks.size() == 10); for (auto& trk : trks) { REQUIRE(trk.eventId() == count); @@ -202,14 +201,13 @@ TEST_CASE("GroupSlicerSeveralAssociated") auto count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == count); - auto trksx = std::get(as); - auto trksy = std::get(as); - auto trksz = std::get(as); + auto trksx = slice.prepareArgument(); + auto trksy = slice.prepareArgument(); + auto trksz = slice.prepareArgument(); - auto trksu = std::get(as); + auto trksu = slice.prepareArgument(); REQUIRE(trksx.size() == 10); REQUIRE(trksy.size() == 20); @@ -263,10 +261,9 @@ TEST_CASE("GroupSlicerMismatchedGroups") o2::framework::GroupSlicer g(e, tt, slices); for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == (int64_t)slice.position); - auto trks = std::get(as); + auto trks = slice.prepareArgument(); if (slice.position == 3 || slice.position == 10 || slice.position == 12 || slice.position == 16 || slice.position == 19) { REQUIRE(trks.size() == 0); } else { @@ -321,10 +318,9 @@ TEST_CASE("GroupSlicerMismatchedUnassignedGroups") auto count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == count); - auto trks = std::get(as); + auto trks = slice.prepareArgument(); if (count == 3 || count == 10 || count == 12 || count == 16 || count == 19) { REQUIRE(trks.size() == 0); } else { @@ -373,10 +369,9 @@ TEST_CASE("GroupSlicerMismatchedFilteredGroups") auto count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == rows[count]); - auto trks = std::get(as); + auto trks = slice.prepareArgument(); if (rows[count] == 3 || rows[count] == 10 || rows[count] == 12 || rows[count] == 16) { REQUIRE(trks.size() == 0); } else { @@ -435,10 +430,9 @@ TEST_CASE("GroupSlicerMismatchedUnsortedFilteredGroups") unsigned int count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == rows[count]); - auto trks = std::get>(as); + auto trks = slice.prepareArgument>(); if (rows[count] == 3 || rows[count] == 10 || rows[count] == 12 || rows[count] == 16) { REQUIRE(trks.size() == 0); } else { @@ -457,10 +451,9 @@ TEST_CASE("GroupSlicerMismatchedUnsortedFilteredGroups") count = 0; for (auto& slice : ge) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == rows[count]); - auto trks = std::get>(as); + auto trks = slice.prepareArgument>(); REQUIRE(trks.size() == 0); ++count; } @@ -471,10 +464,9 @@ TEST_CASE("GroupSlicerMismatchedUnsortedFilteredGroups") count = 0; for (auto& slice : gu) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); REQUIRE(gg.globalIndex() == rows[count]); - auto trks = std::get>(as); + auto trks = slice.prepareArgument>(); if (rows[count] == 3 || rows[count] == 10 || rows[count] == 12 || rows[count] == 16) { REQUIRE(trks.size() == 0); } else { @@ -563,10 +555,9 @@ TEST_CASE("GroupSlicerMismatchedUnsortedFilteredGroupsWithSelfIndex") // For a grouped case, the recursive access of a slice-self index of a filtered table should have consistent types for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); - overwriteInternalIndices(as, associatedTuple); - auto& ts = std::get<1>(as); + auto ts = slice.prepareArgument(); + ts.bindInternalIndicesTo(&std::get(associatedTuple)); ts.bindExternalIndices(&e, &std::get<0>(associatedTuple)); for (auto& thing : ts) { if (thing.has_part()) { @@ -620,9 +611,8 @@ TEST_CASE("EmptySliceables") unsigned int count = 0; for (auto& slice : g) { - auto as = slice.associatedTables(); auto gg = slice.groupingElement(); - auto trks = std::get(as); + auto trks = slice.prepareArgument(); REQUIRE(gg.globalIndex() == count); REQUIRE(trks.size() == 0); ++count; From 625d19513ee383959502d5deb1197a351f21c53d Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 3 Dec 2026 20:57:59 +0100 Subject: [PATCH 06/26] DPL Analysis: cache slice info in GroupedCombinationsGenerator --- Framework/Core/include/Framework/ASoA.h | 36 ++++++++++++++----- .../include/Framework/GroupedCombinations.h | 18 +++++++++- 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 43bbe9480e40f..22a993cd886b7 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -1679,12 +1679,22 @@ auto doFilteredSliceBy(T const* table, o2::framework::PresliceBase originReplacement(header::DataOrigin newOrigin); +/// The sorted slicing cache entry of table T for the index column node. The +/// entry stays valid until the cache is updated, so that it can be looked up +/// once and reused for many slices. template -auto doSliceByCached(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) +framework::SliceInfoPtr getSliceInfoFor(framework::expressions::BindingNode const& node, o2::framework::SliceCache& cache) { - auto localCache = cache.ptr->getCacheFor({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), - node.name}); - auto [offset, count] = localCache.getSliceFor(value); + return cache.ptr->getCacheFor({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), + node.name}); +} + +/// Slice of table for the group value, using an already looked up cache entry +template + requires(!soa::is_filtered_table) +auto doSliceByCached(T const* table, framework::SliceInfoPtr const& sliceInfo, int value) +{ + auto [offset, count] = sliceInfo.getSliceFor(value); auto t = makeTableOn(table->asArrowTableRef().slice({static_cast(offset), count}), *table); if (t.tableSize() != 0) { table->copyIndexBindings(t); @@ -1693,14 +1703,24 @@ auto doSliceByCached(T const* table, framework::expressions::BindingNode const& } template -auto doFilteredSliceByCached(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) +auto doSliceByCached(T const* table, framework::SliceInfoPtr const& sliceInfo, int value) { - auto localCache = cache.ptr->getCacheFor({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), - node.name}); - auto [offset, count] = localCache.getSliceFor(value); + auto [offset, count] = sliceInfo.getSliceFor(value); return prepareFilteredSlice(table, table->asArrowTableRef().slice({static_cast(offset), count})); } +template +auto doSliceByCached(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) +{ + return doSliceByCached(table, getSliceInfoFor(node, cache), value); +} + +template +auto doFilteredSliceByCached(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) +{ + return doSliceByCached(table, getSliceInfoFor(node, cache), value); +} + template auto doSliceByCachedUnsorted(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) { diff --git a/Framework/Core/include/Framework/GroupedCombinations.h b/Framework/Core/include/Framework/GroupedCombinations.h index 072181b153842..18e9ea41ee778 100644 --- a/Framework/Core/include/Framework/GroupedCombinations.h +++ b/Framework/Core/include/Framework/GroupedCombinations.h @@ -84,6 +84,7 @@ struct GroupedCombinationsGenerator { mGrouping = std::make_shared(soa::makeTableOn(grouping.asArrowTableRef(), grouping)); } setMultipleGroupingTables(grouping); + updateSliceInfos(std::make_index_sequence()); if (!this->mIsEnd) { setCurrentGroupedCombination(); } @@ -103,6 +104,7 @@ struct GroupedCombinationsGenerator { } mAssociated = std::make_shared>(std::make_tuple(std::get(pack{})>(associated)...)); setMultipleGroupingTables(grouping); + updateSliceInfos(std::make_index_sequence()); if (!this->mIsEnd) { setCurrentGroupedCombination(); } @@ -158,6 +160,19 @@ struct GroupedCombinationsGenerator { } private: + /// Look up the slicing cache entries of the associated tables once per + /// set of tables, instead of once per slice + template + void updateSliceInfos(std::index_sequence) + { + ([this]() { + if (std::get(*mAssociated).size() != 0) { + mSliceInfos[Is] = soa::getSliceInfoFor>>>(mIndexColumns[Is], *cache); + } + }(), + ...); + } + std::tuple getAssociatedTables() { return doGetAssociatedTables(std::make_index_sequence()); @@ -176,7 +191,7 @@ struct GroupedCombinationsGenerator { if (std::get(*mAssociated).size() == 0) { return std::get(*mAssociated); } - return std::get(*mAssociated).sliceByCached(mIndexColumns[I], ind, *cache); + return soa::doSliceByCached(&std::get(*mAssociated), mSliceInfos[I], ind); } void setCurrentGroupedCombination() @@ -189,6 +204,7 @@ struct GroupedCombinationsGenerator { } std::array mIndexColumns; + std::array mSliceInfos; std::shared_ptr mGrouping; std::shared_ptr> mAssociated; std::optional> mSlices; From 8b834438a4b9464fef180f9a346d8ff878aa0aee Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 3 Dec 2026 21:38:56 +0100 Subject: [PATCH 07/26] DPL Analysis: avoid temporary tuple and its copy in GroupedCombinationsGenerator --- .../include/Framework/GroupedCombinations.h | 40 ++++++------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/Framework/Core/include/Framework/GroupedCombinations.h b/Framework/Core/include/Framework/GroupedCombinations.h index 18e9ea41ee778..d8f63b85ff0ba 100644 --- a/Framework/Core/include/Framework/GroupedCombinations.h +++ b/Framework/Core/include/Framework/GroupedCombinations.h @@ -21,19 +21,6 @@ namespace o2::framework { -// Create an instance of a tuple interleaved from given tuples -template -auto interleaveTuplesImpl(std::tuple& t1, std::tuple& t2, std::index_sequence) -{ - return std::tuple_cat(std::make_tuple(std::get(t1), std::get(t2))...); -} - -template -auto interleaveTuples(std::tuple& t1, std::tuple& t2) -{ - return interleaveTuplesImpl(t1, t2, std::index_sequence_for()); -} - template using is_index_to_g_t = typename std::conditional(), std::true_type, std::false_type>::type; @@ -173,17 +160,6 @@ struct GroupedCombinationsGenerator { ...); } - std::tuple getAssociatedTables() - { - return doGetAssociatedTables(std::make_index_sequence()); - } - - template - std::tuple doGetAssociatedTables(std::index_sequence) - { - return std::make_tuple(getAssociatedTable()...); - } - template auto getAssociatedTable() { @@ -197,17 +173,25 @@ struct GroupedCombinationsGenerator { void setCurrentGroupedCombination() { if (!this->mIsEnd) { - auto& currentGrouping = GroupingPolicy::mCurrent; - mSlices.emplace(getAssociatedTables()); - mCurrentGrouped.emplace(interleaveTuples(currentGrouping, *mSlices)); + emplaceCurrentGrouped(std::make_index_sequence()); } } + /// Make the current combination: the grouping elements interleaved with the + /// slices of the associated tables. The slices are made as temporaries + /// referenced by a tuple of references, so that each of them is moved once, + /// directly into the combination. + template + void emplaceCurrentGrouped(std::index_sequence) + { + std::apply([this](auto&&... elements) { mCurrentGrouped.emplace(std::forward(elements)...); }, + std::tuple_cat(std::forward_as_tuple(std::get(GroupingPolicy::mCurrent), getAssociatedTable())...)); + } + std::array mIndexColumns; std::array mSliceInfos; std::shared_ptr mGrouping; std::shared_ptr> mAssociated; - std::optional> mSlices; std::optional mCurrentGrouped; SliceCache* cache = nullptr; }; From 492e763af68e93621c8ddcc8d96d97bb9ac89d38 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 3 Dec 2026 22:16:09 +0100 Subject: [PATCH 08/26] DPL Analysis: explicit return types for slices to prevent copies --- Framework/Core/include/Framework/ASoA.h | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 22a993cd886b7..b3b73ae6e05b6 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -1589,9 +1589,12 @@ R makeTableOn(ArrowTableRef ref, P const& parent, Args&&... args) } } +// The slicing helpers below that return a named table have explicit return +// types: clang does not apply the named return value optimization in function +// templates with a deduced return type, and would copy the table on return. template requires std::same_as && (o2::soa::is_binding_compatible_v()) -auto doSliceBy(T const* table, o2::framework::PresliceBase const& container, int value) +typename T::self_t doSliceBy(T const* table, o2::framework::PresliceBase const& container, int value) { if constexpr (OPT) { if (container.isMissing()) { @@ -1608,7 +1611,7 @@ auto doSliceBy(T const* table, o2::framework::PresliceBase const } template -auto doSliceByHelper(T const* table, std::span const& selection) +soa::Filtered doSliceByHelper(T const* table, std::span const& selection) { auto t = makeTableOn>(table->asArrowTableRef(), *table, selection); if (t.tableSize() != 0) { @@ -1621,7 +1624,7 @@ auto doSliceByHelper(T const* table, std::span const& selection) template requires(!soa::is_filtered_table) -auto doSliceByHelper(T const* table, std::span const& selection) +soa::Filtered doSliceByHelper(T const* table, std::span const& selection) { auto t = makeTableOn>(table->asArrowTableRef(), *table, selection); if (t.tableSize() != 0) { @@ -1647,7 +1650,7 @@ auto doSliceBy(T const* table, o2::framework::PresliceBase const SelectionVector sliceSelection(std::span const& mSelectedRows, int64_t nrows, uint64_t offset); template -auto prepareFilteredSlice(T const* table, o2::soa::ArrowTableRef slice) +Filtered prepareFilteredSlice(T const* table, o2::soa::ArrowTableRef slice) { if (slice.range.offset >= static_cast(table->tableSize())) { auto fresult = makeTableOn>(slice, *table, SelectionVector{}); @@ -1692,7 +1695,7 @@ framework::SliceInfoPtr getSliceInfoFor(framework::expressions::BindingNode cons /// Slice of table for the group value, using an already looked up cache entry template requires(!soa::is_filtered_table) -auto doSliceByCached(T const* table, framework::SliceInfoPtr const& sliceInfo, int value) +typename T::self_t doSliceByCached(T const* table, framework::SliceInfoPtr const& sliceInfo, int value) { auto [offset, count] = sliceInfo.getSliceFor(value); auto t = makeTableOn(table->asArrowTableRef().slice({static_cast(offset), count}), *table); @@ -1722,7 +1725,7 @@ auto doFilteredSliceByCached(T const* table, framework::expressions::BindingNode } template -auto doSliceByCachedUnsorted(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) +std::conditional_t, typename T::self_t, Filtered> doSliceByCachedUnsorted(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) { auto localCache = cache.ptr->getCacheUnsortedFor({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), node.name}); From bb636d4afd4a181227ae32ae5e169f49ab30c7e9 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 3 Dec 2026 22:35:13 +0100 Subject: [PATCH 09/26] DPL Analysis: move bindings to the unfiltered iterator, so that a filtered iterator on an empty selection can be skipped --- Framework/Core/include/Framework/ASoA.h | 34 ++++++++++++++++--------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index b3b73ae6e05b6..0ba96af7c2e18 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -3770,9 +3770,7 @@ class FilteredBase : public T : T{std::move(tables)} { adoptSelection(selection); - if (this->tableSize() != 0) { - mFilteredBegin = table_t::filtered_begin(mSelectedRows); - } + T::bindInternalIndicesTo(this); resetRanges(); mFilteredBegin.bindInternalIndices(this); } @@ -3783,9 +3781,7 @@ class FilteredBase : public T : T{table, parent} { adoptSelection(selection); - if (this->tableSize() != 0) { - mFilteredBegin = table_t::filtered_begin(mSelectedRows); - } + T::bindInternalIndicesTo(this); resetRanges(); mFilteredBegin.bindInternalIndices(this); } @@ -3800,9 +3796,11 @@ class FilteredBase : public T return const_iterator(mFilteredBegin); } + /// Access by row number in the range. The unfiltered iterator holds the + /// bindings, so this works also when no row is selected. unfiltered_iterator rawIteratorAt(uint64_t i) const { - auto it = unfiltered_iterator{mFilteredBegin}; + auto it = unfiltered_iterator{this->cachedUnfilteredBegin()}; it.setCursor(i); return it; } @@ -3868,21 +3866,25 @@ class FilteredBase : public T /// Bind the columns which refer to other tables /// to the associated tables. + /// The bindings are held by the unfiltered iterator, from which the filtered + /// one is made, and are also set on the filtered one in case it is built void bindExternalIndicesRaw(std::vector&& ptrs) { - mFilteredBegin.bindExternalIndicesRaw(std::forward>(ptrs)); + mFilteredBegin.bindExternalIndicesRaw(std::vector{ptrs}); + T::bindExternalIndicesRaw(std::forward>(ptrs)); } template void bindInternalIndicesTo(I const* ptr) { + T::bindInternalIndicesTo(ptr); mFilteredBegin.bindInternalIndices(ptr); } template void doCopyIndexBindings(framework::pack, T1& dest) const { - dest.bindExternalIndicesRaw(mFilteredBegin.getIndexBindings()); + dest.bindExternalIndicesRaw(this->cachedUnfilteredBegin().getIndexBindings()); } template @@ -3962,6 +3964,7 @@ class FilteredBase : public T void setPointerReconstructor(framework::PointerReconstructor const& pointerReconstructor) { + T::setPointerReconstructor(pointerReconstructor); mFilteredBegin.setPointerReconstructor(pointerReconstructor); } @@ -3974,9 +3977,14 @@ class FilteredBase : public T mFilteredEnd.reset(new RowViewSentinel{static_cast(mSelectedRows.size())}); if (tableSize() == 0) { mFilteredBegin = *mFilteredEnd; - } else { + } else if (mFilteredBeginBuilt) { mFilteredBegin.resetSelection(mSelectedRows); + } else if (!mSelectedRows.empty()) { + // made from the unfiltered iterator, with its bindings, once rows are selected + mFilteredBegin = table_t::filtered_begin(mSelectedRows); + mFilteredBeginBuilt = true; } + // with no rows selected and no built iterator, begin is already at the end } template @@ -4012,6 +4020,8 @@ class FilteredBase : public T std::span mSelectedRows; SelectionVector mSelectedRowsCache; bool mCached = false; + /// whether mFilteredBegin has been made; it is not while no row is selected + bool mFilteredBeginBuilt = false; iterator mFilteredBegin; std::shared_ptr mFilteredEnd; }; @@ -4095,7 +4105,7 @@ class Filtered : public FilteredBase unfiltered_iterator rawIteratorAt(uint64_t i) const { - auto it = unfiltered_iterator{this->cached_begin()}; + auto it = unfiltered_iterator{this->cachedUnfilteredBegin()}; it.setCursor(i); return it; } @@ -4237,7 +4247,7 @@ class Filtered> : public FilteredBase unfiltered_iterator rawIteratorAt(uint64_t i) const { - auto it = unfiltered_iterator{this->cached_begin()}; + auto it = unfiltered_iterator{this->cachedUnfilteredBegin()}; it.setCursor(i); return it; } From 60f53113749d0616e243eb420bd550a20a6b4b34 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 3 Dec 2026 22:47:20 +0100 Subject: [PATCH 10/26] DPL Analysis: speed up iterator copy; add benchmarks --- Framework/Core/include/Framework/ASoA.h | 44 ++++++--- Framework/Core/test/benchmark_ASoA.cxx | 115 ++++++++++++++++++++++++ 2 files changed, 145 insertions(+), 14 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 0ba96af7c2e18..8caa192dea6d5 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -1101,10 +1101,24 @@ struct TableIterator : IP, C... { } } - TableIterator& operator=(TableIterator other) + /// The columns are assigned directly from other and bound once. A move + /// would do the same: the iterator owns nothing, and the columns have to be + /// bound to the new object in any case. + TableIterator& operator=(self_t const& other) { IP::operator=(static_cast(other)); - (void(static_cast(*this) = static_cast(other)), ...); + (void(static_cast(*this) = static_cast(other)), ...); + if (this->size() != 0) { + bind(); + } + return *this; + } + + TableIterator& operator=(TableIterator const& other) + requires std::same_as + { + IP::operator=(IP{static_cast(other)}); + (void(static_cast(*this) = static_cast(other)), ...); if (this->size() != 0) { bind(); } @@ -1889,60 +1903,62 @@ class Table { } + // The converting assignments and constructors work directly on the base + // iterator of other, without temporary copies of it template - TableIteratorBase& operator=(TableIteratorBase other) + TableIteratorBase& operator=(TableIteratorBase const& other) requires(P::ref.desc_hash == Parent::ref.desc_hash) { - static_cast&>(*this) = static_cast>(other); + static_cast&>(*this) = static_cast const&>(other); return *this; } template - TableIteratorBase& operator=(TableIteratorBase other) + TableIteratorBase& operator=(TableIteratorBase const& other) { - static_cast&>(*this) = static_cast>(other); + static_cast&>(*this) = static_cast const&>(other); return *this; } template - TableIteratorBase& operator=(TableIteratorBase other) + TableIteratorBase& operator=(TableIteratorBase const& other) requires std::same_as { - static_cast&>(*this) = static_cast>(other); + static_cast&>(*this) = static_cast const&>(other); return *this; } template TableIteratorBase(TableIteratorBase const& other) requires(P::ref.desc_hash == Parent::ref.desc_hash) + : base_iterator(static_cast const&>(other)) { - *this = other; } template TableIteratorBase(TableIteratorBase&& other) noexcept requires(P::ref.desc_hash == Parent::ref.desc_hash) + : base_iterator(static_cast const&>(other)) { - *this = other; } template TableIteratorBase(TableIteratorBase const& other) + : base_iterator(static_cast const&>(other)) { - *this = other; } template TableIteratorBase(TableIteratorBase&& other) noexcept + : base_iterator(static_cast const&>(other)) { - *this = other; } template - TableIteratorBase(TableIteratorBase other) + TableIteratorBase(TableIteratorBase const& other) requires std::same_as + : base_iterator(static_cast const&>(other)) { - *this = other; } TableIteratorBase& operator=(RowViewSentinel const& other) diff --git a/Framework/Core/test/benchmark_ASoA.cxx b/Framework/Core/test/benchmark_ASoA.cxx index 4001e2a725a15..c83f7b5829265 100644 --- a/Framework/Core/test/benchmark_ASoA.cxx +++ b/Framework/Core/test/benchmark_ASoA.cxx @@ -15,6 +15,7 @@ #include #include #include +#include using namespace o2::framework; using namespace arrow; @@ -33,6 +34,13 @@ DECLARE_SOA_DYNAMIC_COLUMN(SumFreeArgs, sumFreeArgs, [](float x, float y, float } // namespace test DECLARE_SOA_TABLE(TestTable, "AOD", "TESTTBL", test::X, test::Y, test::Z, test::Sum); + +namespace test +{ +DECLARE_SOA_COLUMN_FULL(W, w, float, "w"); +} // namespace test + +DECLARE_SOA_TABLE(TestTableW, "AOD", "TESTTBLW", test::W); } // namespace o2::aod #ifdef __APPLE__ @@ -377,4 +385,111 @@ static void BM_ASoADynamicColumnCallGetGetterByLabel(benchmark::State& state) } BENCHMARK(BM_ASoADynamicColumnCallGetGetterByLabel)->Range(8, 8 << maxrange); +// Copies of table iterators: a wide table, as each column of an iterator is copied and bound +namespace +{ +std::shared_ptr makeTracks(int64_t n) +{ + std::default_random_engine e1(1234567891); + std::uniform_real_distribution uniform_dist(0, 1); + TableBuilder builder; + auto rowWriter = builder.cursor(); + for (auto i = 0; i < n; ++i) { + rowWriter(0, i, 0, uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1)); + } + return builder.finalize(); +} + +SelectionVector allRows(int64_t n) +{ + SelectionVector rows(n); + std::iota(rows.begin(), rows.end(), 0); + return rows; +} +} // namespace + +// Copy assignment of an iterator +static void BM_ASoAIteratorAssign(benchmark::State& state) +{ + o2::aod::StoredTracks tracks{makeTracks(state.range(0))}; + auto target = tracks.begin(); + auto source = tracks.begin(); + + for (auto _ : state) { + float sum = 0; + for (auto i = 0; i < state.range(0); ++i) { + source.setCursor(i); + target = source; + sum += target.x(); + } + benchmark::DoNotOptimize(sum); + } + state.SetItemsProcessed(state.iterations() * state.range(0)); +} + +BENCHMARK(BM_ASoAIteratorAssign)->Arg(1 << 14); + +// Assignment of a filtered iterator to an unfiltered one +static void BM_ASoAFilteredToUnfilteredAssign(benchmark::State& state) +{ + auto table = makeTracks(state.range(0)); + o2::aod::StoredTracks tracks{table}; + Filtered filtered{{table}, allRows(state.range(0))}; + auto target = tracks.begin(); + + for (auto _ : state) { + float sum = 0; + for (auto const& row : filtered) { + target = row; + sum += target.x(); + } + benchmark::DoNotOptimize(sum); + } + state.SetItemsProcessed(state.iterations() * state.range(0)); +} + +BENCHMARK(BM_ASoAFilteredToUnfilteredAssign)->Arg(1 << 14); + +// Access by row number to a filtered table, as for an index to it +static void BM_ASoAFilteredRawIteratorAt(benchmark::State& state) +{ + auto table = makeTracks(state.range(0)); + Filtered filtered{{table}, allRows(state.range(0))}; + + for (auto _ : state) { + float sum = 0; + for (auto i = 0; i < state.range(0); ++i) { + sum += filtered.rawIteratorAt(i).x(); + } + benchmark::DoNotOptimize(sum); + } + state.SetItemsProcessed(state.iterations() * state.range(0)); +} + +BENCHMARK(BM_ASoAFilteredRawIteratorAt)->Arg(1 << 14); + +// The begin iterator of a join +static void BM_ASoAJoinBegin(benchmark::State& state) +{ + auto table = makeTracks(state.range(0)); + TableBuilder builder; + auto rowWriter = builder.cursor(); + for (auto i = 0; i < state.range(0); ++i) { + rowWriter(0, 1.f); + } + Join joined{{ArrowTableRef{table}, ArrowTableRef{builder.finalize()}}}; + + for (auto _ : state) { + float sum = 0; + for (auto i = 0; i < state.range(0); ++i) { + sum += joined.begin().x(); + } + benchmark::DoNotOptimize(sum); + } + state.SetItemsProcessed(state.iterations() * state.range(0)); +} + +BENCHMARK(BM_ASoAJoinBegin)->Arg(1 << 14); + BENCHMARK_MAIN(); From 2dae82cde4c34f1e91c2c736b640d241db3879b3 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Thu, 3 Dec 2026 23:10:23 +0100 Subject: [PATCH 11/26] DPL Analysis: keep cache location for slices in general case --- Framework/Core/include/Framework/ASoA.h | 38 +++++++++++-- .../Framework/ArrowTableSlicingCache.h | 17 ++++++ Framework/Core/src/ArrowTableSlicingCache.cxx | 53 +++++++++++++++++-- 3 files changed, 99 insertions(+), 9 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 8caa192dea6d5..9ed0d0d68ef3e 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -1696,14 +1696,45 @@ auto doFilteredSliceBy(T const* table, o2::framework::PresliceBase originReplacement(header::DataOrigin newOrigin); +/// Key under which the slicing cache remembers the entry position for table T +/// and the index column node: the type id of T and the column's hash +template +constexpr uint64_t sliceCacheKey(framework::expressions::BindingNode const& node) +{ + return (static_cast(o2::framework::TypeIdHelpers::uniqueId()) << 32) | node.hash; +} + /// The sorted slicing cache entry of table T for the index column node. The /// entry stays valid until the cache is updated, so that it can be looked up /// once and reused for many slices. template framework::SliceInfoPtr getSliceInfoFor(framework::expressions::BindingNode const& node, o2::framework::SliceCache& cache) { - return cache.ptr->getCacheFor({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), - node.name}); + // the cache entry for a table type and index column does not change during the + // run, so its position is looked up by label once and remembered + auto const key = sliceCacheKey(node); + auto pos = node.hash == 0 ? -1 : cache.ptr->knownPosition(key); + if (pos < 0) { + pos = cache.ptr->locateSorted({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), node.name}); + if (node.hash != 0) { + cache.ptr->rememberPosition(key, pos); + } + } + return cache.ptr->getCacheForPos(pos); +} + +template +framework::SliceInfoUnsortedPtr getSliceInfoUnsortedFor(framework::expressions::BindingNode const& node, o2::framework::SliceCache& cache) +{ + auto const key = sliceCacheKey(node); + auto pos = node.hash == 0 ? -1 : cache.ptr->knownPositionUnsorted(key); + if (pos < 0) { + pos = cache.ptr->locateUnsorted({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), node.name}); + if (node.hash != 0) { + cache.ptr->rememberPositionUnsorted(key, pos); + } + } + return cache.ptr->getCacheUnsortedForPos(pos); } /// Slice of table for the group value, using an already looked up cache entry @@ -1741,8 +1772,7 @@ auto doFilteredSliceByCached(T const* table, framework::expressions::BindingNode template std::conditional_t, typename T::self_t, Filtered> doSliceByCachedUnsorted(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) { - auto localCache = cache.ptr->getCacheUnsortedFor({"", originReplacement(cache.ptr->newOrigin)(o2::soa::getMatcherFromTypeForKey(node.name)), - node.name}); + auto localCache = getSliceInfoUnsortedFor(node, cache); if constexpr (soa::is_filtered_table) { auto t = makeTableOn(table->asArrowTableRef(), *table, localCache.getSliceFor(value)); if (t.tableSize() != 0) { diff --git a/Framework/Core/include/Framework/ArrowTableSlicingCache.h b/Framework/Core/include/Framework/ArrowTableSlicingCache.h index 9b27480024674..fd89f61e054c9 100644 --- a/Framework/Core/include/Framework/ArrowTableSlicingCache.h +++ b/Framework/Core/include/Framework/ArrowTableSlicingCache.h @@ -101,6 +101,19 @@ struct ArrowTableSlicingCache { int getCachePosSortedFor(Entry const& bindingKey) const; int getCachePosUnsortedFor(Entry const& bindingKey) const; + // locate an enabled entry of the given kind; throws if the key is in the other + // cache, in neither, or disabled + int locateSorted(Entry const& bindingKey) const; + int locateUnsorted(Entry const& bindingKey) const; + + // positions already located, by a key the caller makes from the table type + // and the index column (see soa::getSliceInfoFor); -1 if not known yet. The + // entry lists only change in setCaches, which forgets them. + int knownPosition(uint64_t key) const; + int knownPositionUnsorted(uint64_t key) const; + void rememberPosition(uint64_t key, int pos) const; + void rememberPositionUnsorted(uint64_t key, int pos) const; + // get slice from cache for a given value SliceInfoPtr getCacheFor(Entry const& bindingKey) const; SliceInfoUnsortedPtr getCacheUnsortedFor(Entry const& bindingKey) const; @@ -114,6 +127,10 @@ struct ArrowTableSlicingCache { std::pair> emptySlice{nullptr, nullptr}; static void validateOrder(Entry const& bindingKey, std::shared_ptr const& input); + + private: + mutable std::vector> mKnownPositions; + mutable std::vector> mKnownPositionsUnsorted; }; } // namespace o2::framework diff --git a/Framework/Core/src/ArrowTableSlicingCache.cxx b/Framework/Core/src/ArrowTableSlicingCache.cxx index 7b96b7c0c0e85..54dcbff8bf1dd 100644 --- a/Framework/Core/src/ArrowTableSlicingCache.cxx +++ b/Framework/Core/src/ArrowTableSlicingCache.cxx @@ -111,6 +111,8 @@ void ArrowTableSlicingCache::setCaches(Cache&& bsks, Cache&& bsksUnsorted) valuesUnsorted.resize(bindingsKeysUnsorted.size()); groups.clear(); groups.resize(bindingsKeysUnsorted.size()); + mKnownPositions.clear(); + mKnownPositionsUnsorted.clear(); } arrow::Status ArrowTableSlicingCache::updateCacheEntry(int pos, std::shared_ptr const& table) @@ -235,7 +237,7 @@ int ArrowTableSlicingCache::getCachePosUnsortedFor(Entry const& bindingKey) cons } return -1; } -SliceInfoPtr ArrowTableSlicingCache::getCacheFor(Entry const& bindingKey) const +int ArrowTableSlicingCache::locateSorted(Entry const& bindingKey) const { auto [p, s] = getCachePos(bindingKey); if (!s) { @@ -244,11 +246,10 @@ SliceInfoPtr ArrowTableSlicingCache::getCacheFor(Entry const& bindingKey) const if (!bindingsKeys[p].enabled) { throw runtime_error_f("Disabled cache %s/%s is requested", bindingKey.binding.c_str(), bindingKey.key.c_str()); } - - return getCacheForPos(p); + return p; } -SliceInfoUnsortedPtr ArrowTableSlicingCache::getCacheUnsortedFor(const Entry& bindingKey) const +int ArrowTableSlicingCache::locateUnsorted(Entry const& bindingKey) const { auto [p, s] = getCachePos(bindingKey); if (s) { @@ -257,8 +258,50 @@ SliceInfoUnsortedPtr ArrowTableSlicingCache::getCacheUnsortedFor(const Entry& bi if (!bindingsKeysUnsorted[p].enabled) { throw runtime_error_f("Disabled unsorted cache (%s) %s/%s is requested", DataSpecUtils::describe(bindingKey.matcher).c_str(), bindingKey.binding.c_str(), bindingKey.key.c_str()); } + return p; +} + +namespace +{ +int findKnown(std::vector> const& known, uint64_t key) +{ + for (auto const& [k, p] : known) { + if (k == key) { + return p; + } + } + return -1; +} +} // namespace + +int ArrowTableSlicingCache::knownPosition(uint64_t key) const +{ + return findKnown(mKnownPositions, key); +} - return getCacheUnsortedForPos(p); +int ArrowTableSlicingCache::knownPositionUnsorted(uint64_t key) const +{ + return findKnown(mKnownPositionsUnsorted, key); +} + +void ArrowTableSlicingCache::rememberPosition(uint64_t key, int pos) const +{ + mKnownPositions.emplace_back(key, pos); +} + +void ArrowTableSlicingCache::rememberPositionUnsorted(uint64_t key, int pos) const +{ + mKnownPositionsUnsorted.emplace_back(key, pos); +} + +SliceInfoPtr ArrowTableSlicingCache::getCacheFor(Entry const& bindingKey) const +{ + return getCacheForPos(locateSorted(bindingKey)); +} + +SliceInfoUnsortedPtr ArrowTableSlicingCache::getCacheUnsortedFor(const Entry& bindingKey) const +{ + return getCacheUnsortedForPos(locateUnsorted(bindingKey)); } SliceInfoPtr ArrowTableSlicingCache::getCacheForPos(int pos) const From 0eb5a344359780771494295b7b8a2bf701854fb8 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 08:52:51 +0100 Subject: [PATCH 12/26] DPL Analysis: GroupSlicer returns full table by reference --- Framework/Core/include/Framework/GroupSlicer.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Framework/Core/include/Framework/GroupSlicer.h b/Framework/Core/include/Framework/GroupSlicer.h index a12791555501b..5cc9d16ed9b31 100644 --- a/Framework/Core/include/Framework/GroupSlicer.h +++ b/Framework/Core/include/Framework/GroupSlicer.h @@ -250,9 +250,11 @@ struct GroupSlicer { return soa::makeTableOn>(originalTable.asArrowTableRef().slice({static_cast(offset), static_cast(count)}), originalTable); } + /// Tables not related to the grouping table are the same for every grouping + /// element, so the full table is returned by reference instead of a copy. template requires(!o2::soa::relatedByIndex, std::decay_t>() && !soa::is_smallgroups) - auto prepareArgument() + A1& prepareArgument() { return std::get(*mAt); } From 6300969a54ba9fc0fb2adaafc7ee8d554d8a2e2e Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 09:07:05 +0100 Subject: [PATCH 13/26] DPL Analysis: give empty filtered slices an empty range to skip construction --- Framework/Core/include/Framework/ASoA.h | 19 +++++++++++++++---- .../Core/include/Framework/GroupSlicer.h | 3 ++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 9ed0d0d68ef3e..e5e0abddf3d84 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -1603,6 +1603,16 @@ R makeTableOn(ArrowTableRef ref, P const& parent, Args&&... args) } } +/// The range of an unsorted slice, which is a selection over the whole table: +/// the full range of ref when the selection has rows, an empty range when it +/// has none, so that an empty slice skips making its iterators, as an empty +/// sorted slice does. An empty unsorted slice therefore has no raw access to +/// the rows of the table. +inline ArrowTableRef unsortedSliceRange(ArrowTableRef const& ref, std::span selection) +{ + return selection.empty() ? ref.makeEmpty() : ref; +} + // The slicing helpers below that return a named table have explicit return // types: clang does not apply the named return value optimization in function // templates with a deduced return type, and would copy the table on return. @@ -1627,7 +1637,7 @@ typename T::self_t doSliceBy(T const* table, o2::framework::PresliceBase soa::Filtered doSliceByHelper(T const* table, std::span const& selection) { - auto t = makeTableOn>(table->asArrowTableRef(), *table, selection); + auto t = makeTableOn>(unsortedSliceRange(table->asArrowTableRef(), selection), *table, selection); if (t.tableSize() != 0) { table->copyIndexBindings(t); t.bindInternalIndicesTo(table); @@ -1640,7 +1650,7 @@ template requires(!soa::is_filtered_table) soa::Filtered doSliceByHelper(T const* table, std::span const& selection) { - auto t = makeTableOn>(table->asArrowTableRef(), *table, selection); + auto t = makeTableOn>(unsortedSliceRange(table->asArrowTableRef(), selection), *table, selection); if (t.tableSize() != 0) { table->copyIndexBindings(t); t.bindInternalIndicesTo(table); @@ -1773,15 +1783,16 @@ template std::conditional_t, typename T::self_t, Filtered> doSliceByCachedUnsorted(T const* table, framework::expressions::BindingNode const& node, int value, o2::framework::SliceCache& cache) { auto localCache = getSliceInfoUnsortedFor(node, cache); + auto selection = localCache.getSliceFor(value); if constexpr (soa::is_filtered_table) { - auto t = makeTableOn(table->asArrowTableRef(), *table, localCache.getSliceFor(value)); + auto t = makeTableOn(unsortedSliceRange(table->asArrowTableRef(), selection), *table, selection); if (t.tableSize() != 0) { t.intersectWithSelection(table->getSelectedRows()); table->copyIndexBindings(t); } return t; } else { - auto t = makeTableOn>(table->asArrowTableRef(), *table, localCache.getSliceFor(value)); + auto t = makeTableOn>(unsortedSliceRange(table->asArrowTableRef(), selection), *table, selection); if (t.tableSize() != 0) { table->copyIndexBindings(t); } diff --git a/Framework/Core/include/Framework/GroupSlicer.h b/Framework/Core/include/Framework/GroupSlicer.h index 5cc9d16ed9b31..fbd81f777a4f9 100644 --- a/Framework/Core/include/Framework/GroupSlicer.h +++ b/Framework/Core/include/Framework/GroupSlicer.h @@ -193,7 +193,8 @@ struct GroupSlicer { } } } - return soa::makeTableOn>(originalTable.asArrowTableRef(), originalTable, std::move(s)); + auto range = soa::unsortedSliceRange(originalTable.asArrowTableRef(), s); + return soa::makeTableOn>(range, originalTable, std::move(s)); } template From d44cbfabd36ff45e5872798a51f63ea746c86f4c Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 09:14:36 +0100 Subject: [PATCH 14/26] DPL Analysis: remove unnecessary heap allocation from Filtered --- Framework/Core/include/Framework/ASoA.h | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index e5e0abddf3d84..07a3103aa992b 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -3864,7 +3864,7 @@ class FilteredBase : public T [[nodiscard]] RowViewSentinel end() const { - return RowViewSentinel{*mFilteredEnd}; + return RowViewSentinel{mFilteredEnd}; } auto& cached_begin() @@ -4031,9 +4031,9 @@ class FilteredBase : public T if (mCached) { mSelectedRows = std::span{mSelectedRowsCache}; } - mFilteredEnd.reset(new RowViewSentinel{static_cast(mSelectedRows.size())}); + mFilteredEnd = static_cast(mSelectedRows.size()); if (tableSize() == 0) { - mFilteredBegin = *mFilteredEnd; + mFilteredBegin = RowViewSentinel{mFilteredEnd}; } else if (mFilteredBeginBuilt) { mFilteredBegin.resetSelection(mSelectedRows); } else if (!mSelectedRows.empty()) { @@ -4080,7 +4080,8 @@ class FilteredBase : public T /// whether mFilteredBegin has been made; it is not while no row is selected bool mFilteredBeginBuilt = false; iterator mFilteredBegin; - std::shared_ptr mFilteredEnd; + /// the number of selected rows, which end() returns as a sentinel + int64_t mFilteredEnd = 0; }; template From f9cb03e6733d43ebeb7b0230b8de11d830d68a4d Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 09:27:10 +0100 Subject: [PATCH 15/26] DPL Analysis: workaround for copy elision issue --- .../include/Framework/GroupedCombinations.h | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/Framework/Core/include/Framework/GroupedCombinations.h b/Framework/Core/include/Framework/GroupedCombinations.h index d8f63b85ff0ba..49f8c769cf4a0 100644 --- a/Framework/Core/include/Framework/GroupedCombinations.h +++ b/Framework/Core/include/Framework/GroupedCombinations.h @@ -34,6 +34,20 @@ expressions::BindingNode getMatchingIndexNode() return expressions::BindingNode{index_column_t::mLabel, o2::framework::TypeIdHelpers::uniqueId(), expressions::selectArrowType()}; } +namespace detail +{ +/// Makes a T when converted to it. An element of a tuple (or of a tuple in an +/// optional) initialized from it is made in place by the conversion function, +/// instead of being moved from a temporary T. This is the resolution of +/// CWG 2327 that clang and GCC implement; with a compiler that does not, the +/// element is moved, as it would be from a T. +template +struct MakeOnConversion { + F make; + operator T() const { return make(); } +}; +} // namespace detail + template requires(sizeof...(As) > 0) struct GroupedCombinationsGenerator { @@ -178,14 +192,23 @@ struct GroupedCombinationsGenerator { } /// Make the current combination: the grouping elements interleaved with the - /// slices of the associated tables. The slices are made as temporaries - /// referenced by a tuple of references, so that each of them is moved once, - /// directly into the combination. + /// slices of the associated tables. Each slice is made by a conversion + /// function when its element of the combination is initialized, so that it + /// is made in place rather than moved there. template void emplaceCurrentGrouped(std::index_sequence) { std::apply([this](auto&&... elements) { mCurrentGrouped.emplace(std::forward(elements)...); }, - std::tuple_cat(std::forward_as_tuple(std::get(GroupingPolicy::mCurrent), getAssociatedTable())...)); + std::tuple_cat(std::forward_as_tuple(std::get(GroupingPolicy::mCurrent), + makeSliceOnConversion())...)); + } + + template + auto makeSliceOnConversion() + { + using slice_t = std::tuple_element_t<2 * I + 1, GroupedIteratorType>; + auto make = [this]() { return getAssociatedTable(); }; + return detail::MakeOnConversion{make}; } std::array mIndexColumns; From bae2f7b90aa3276abe5df785421182e470739962 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 09:31:39 +0100 Subject: [PATCH 16/26] DPL Analysis: skip selection slicing for empty ranges --- Framework/Core/include/Framework/ASoA.h | 3 ++- Framework/Core/include/Framework/GroupSlicer.h | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 07a3103aa992b..2b5e47f4f773b 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -1676,7 +1676,8 @@ SelectionVector sliceSelection(std::span const& mSelectedRows, in template Filtered prepareFilteredSlice(T const* table, o2::soa::ArrowTableRef slice) { - if (slice.range.offset >= static_cast(table->tableSize())) { + // an empty range selects no rows: skip slicing the selection of the table + if (slice.range.size == 0 || slice.range.offset >= static_cast(table->tableSize())) { auto fresult = makeTableOn>(slice, *table, SelectionVector{}); if (fresult.tableSize() != 0) { table->copyIndexBindings(fresult); diff --git a/Framework/Core/include/Framework/GroupSlicer.h b/Framework/Core/include/Framework/GroupSlicer.h index fbd81f777a4f9..a55ae39106920 100644 --- a/Framework/Core/include/Framework/GroupSlicer.h +++ b/Framework/Core/include/Framework/GroupSlicer.h @@ -217,6 +217,10 @@ struct GroupSlicer { uint64_t offset = oc.first; auto count = oc.second; auto groupedElementsTable = originalTable.asArrowTableRef().slice({offset, count}); + if (count == 0) { + // an empty group selects no rows; starts[index] stays valid for the next groups + return soa::makeTableOn>(groupedElementsTable, originalTable, soa::SelectionVector{}); + } // for each grouping element we need to slice the selection vector auto start_iterator = std::lower_bound(starts[index], selections[index]->end(), offset); From df79b4192bbbafa174f8c54db58388282ad9cbb5 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 10:53:28 +0100 Subject: [PATCH 17/26] DPL Analysis: skip default-constructing an iterator when possible --- Framework/Core/include/Framework/ASoA.h | 90 ++++++++++++++++--------- 1 file changed, 57 insertions(+), 33 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 2b5e47f4f773b..aba6366ce8bdb 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -2108,25 +2108,11 @@ class Table Table(o2::soa::ArrowTableRef tableRef) : mArrowTableRef(tableRef), - mEnd{tableRef.range.size} + mEnd{tableRef.range.size}, + mBegin{lookupColumnsAndMakeBegin()} { - if (mArrowTableRef.tablePtr->num_rows() == 0) { - for (size_t ci = 0; ci < framework::pack_size(columns_t{}); ++ci) { - mColumnChunks[ci] = nullptr; - } - mBegin = mEnd; - } else { - auto lookups = [this](framework::pack) -> std::array { return {lookupColumn()...}; }(columns_t{}); - for (size_t ci = 0; ci < framework::pack_size(columns_t{}); ++ci) { - mColumnChunks[ci] = lookups[ci]; - } - if (mEnd.index == 0) { - // empty range: nothing to iterate, begin is already at the end - mBegin = mEnd; - } else { - mBegin = unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}}; - mBegin.bindInternalIndices(this); - } + if (mEnd.index != 0) { + mBegin.bindInternalIndices(this); } } @@ -2138,22 +2124,10 @@ class Table requires(isColumnPrefix()) Table(o2::soa::ArrowTableRef tableRef, P const& parent) : mArrowTableRef(tableRef), - mEnd{tableRef.range.size} + mEnd{tableRef.range.size}, + mBegin{inheritColumnsAndMakeBegin(parent)} { - if (O2_BUILTIN_UNLIKELY(tableRef.tablePtr != parent.asArrowTableRef().tablePtr)) { - parentTableMismatch(o2::aod::label()); - } - auto inheritedEnd = std::ranges::copy(parent.getColumnChunks(), std::begin(mColumnChunks)).out; - std::fill(inheritedEnd, std::end(mColumnChunks), nullptr); - if (mEnd.index == 0) { - // empty range: nothing to iterate, begin is already at the end - mBegin = mEnd; - } else if (parent.hasCachedBegin()) { - // copy the parent's column iterators and only position the copy on the range - mBegin = unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}, parent.cachedUnfilteredBegin()}; - mBegin.bindInternalIndices(this); - } else { - mBegin = unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}}; + if (mEnd.index != 0) { mBegin.bindInternalIndices(this); } } @@ -2424,6 +2398,56 @@ class Table return table->column(position).get(); } + // mBegin is made in the constructors' initializer lists by the helpers below, + // which also fill mColumnChunks (declared before it), so that it is + // constructed once, in place, instead of being default-initialized (which + // zero-fills every column) and then assigned. + + /// The begin iterator of an empty range: at the end, with no column bound + iterator makeEmptyBegin() const + { + iterator it; + it = mEnd; + return it; + } + + /// Look up the column arrays by label and make the begin iterator + iterator lookupColumnsAndMakeBegin() + { + if (mArrowTableRef.tablePtr->num_rows() == 0) { + std::fill(std::begin(mColumnChunks), std::end(mColumnChunks), nullptr); + return makeEmptyBegin(); + } + auto lookups = [this](framework::pack) -> std::array { return {lookupColumn()...}; }(columns_t{}); + std::ranges::copy(lookups, std::begin(mColumnChunks)); + if (mEnd.index == 0) { + // empty range: nothing to iterate, begin is already at the end + return makeEmptyBegin(); + } + return unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}}; + } + + /// Take the column arrays from the parent and make the begin iterator, + /// copying the parent's column iterators when it has them + template + iterator inheritColumnsAndMakeBegin(P const& parent) + { + if (O2_BUILTIN_UNLIKELY(mArrowTableRef.tablePtr != parent.asArrowTableRef().tablePtr)) { + parentTableMismatch(o2::aod::label()); + } + auto inheritedEnd = std::ranges::copy(parent.getColumnChunks(), std::begin(mColumnChunks)).out; + std::fill(inheritedEnd, std::end(mColumnChunks), nullptr); + if (mEnd.index == 0) { + // empty range: nothing to iterate, begin is already at the end + return makeEmptyBegin(); + } + if (parent.hasCachedBegin()) { + // copy the parent's column iterators and only position the copy on the range + return unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}, parent.cachedUnfilteredBegin()}; + } + return unfiltered_iterator{mColumnChunks, {mEnd.index, mArrowTableRef.range.offset}}; + } + ArrowTableRef mArrowTableRef; // std::shared_ptr mTable = nullptr; // uint64_t mOffset = 0; From d034823885c65ec28cb0926a8a7a1303d8609e68 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 11:03:25 +0100 Subject: [PATCH 18/26] Add a TODO with C++23 requirement --- Framework/Core/include/Framework/ASoA.h | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index aba6366ce8bdb..dcbd638318bd0 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -622,6 +622,21 @@ class ColumnIterator : ChunkingPolicy } mutable unwrap_t const* mCurrent = nullptr; + // TODO(C++23): drop mCurrentPos and mGlobalOffset. They point back into the + // index policy of the enclosing TableIterator, because a column getter, being + // a member of the column base class, cannot name the iterator it is part of; + // TableIterator::bind() has to reset them (and the boundIterators of dynamic + // columns) on every construction and copy. With explicit object parameters + // (deducing this) the getters generated by the column macros can receive the + // whole iterator, e.g. + // template + // decltype(auto) pt(this Self const& self) { return self.Pt::mColumnIterator.at(self.mRowIndex + self.mOffset); } + // and read the position from it directly. That makes every ColumnIterator two + // pointers smaller and TableIterator copyable without bind(), which matters for + // slices of wide tables. Postponed until O2 switches to C++23: under C++20 + // Apple clang rejects explicit object parameters, and GCC 14 only accepts them + // with a -Wc++23-extensions warning. Getters becoming templates also breaks + // code that takes their address. int64_t const* mCurrentPos = nullptr; uint64_t const* mGlobalOffset = nullptr; mutable unwrap_t const* mLast = nullptr; From 13f47e59f494a13a49e3b27e56cac29014394535 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 11:11:15 +0100 Subject: [PATCH 19/26] DPL Analysis: reduce shared_ptr copies when passing ArrowTableRef around --- Framework/Core/include/Framework/ASoA.h | 40 ++++++++++--------- .../Core/include/Framework/GroupSlicer.h | 6 +-- 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index dcbd638318bd0..10288dc86276b 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -1609,12 +1609,14 @@ consteval bool isColumnPrefix() template R makeTableOn(ArrowTableRef ref, P const& parent, Args&&... args) { + // ref is moved along to the table, so that the shared_ptr to the arrow + // table is not copied (and its reference count updated) at every step if constexpr (std::constructible_from) { - return R(ref, parent, std::forward(args)...); + return R(std::move(ref), parent, std::forward(args)...); } else if constexpr (std::constructible_from) { - return R(ref, std::forward(args)...); + return R(std::move(ref), std::forward(args)...); } else { - return R(std::vector{ref}, std::forward(args)...); + return R(std::vector{std::move(ref)}, std::forward(args)...); } } @@ -1641,7 +1643,7 @@ typename T::self_t doSliceBy(T const* table, o2::framework::PresliceBaseasArrowTableRef()); - auto t = makeTableOn(out, *table); + auto t = makeTableOn(std::move(out), *table); if (t.tableSize() != 0) { table->copyIndexBindings(t); t.bindInternalIndicesTo(table); @@ -1693,14 +1695,14 @@ Filtered prepareFilteredSlice(T const* table, o2::soa::Arrow { // an empty range selects no rows: skip slicing the selection of the table if (slice.range.size == 0 || slice.range.offset >= static_cast(table->tableSize())) { - auto fresult = makeTableOn>(slice, *table, SelectionVector{}); + auto fresult = makeTableOn>(std::move(slice), *table, SelectionVector{}); if (fresult.tableSize() != 0) { table->copyIndexBindings(fresult); } return fresult; } auto slicedSelection = sliceSelection(table->getSelectedRows(), slice.range.size, slice.range.offset); - auto fresult = makeTableOn>(slice, *table, std::move(slicedSelection)); + auto fresult = makeTableOn>(std::move(slice), *table, std::move(slicedSelection)); if (fresult.tableSize() != 0) { table->copyIndexBindings(fresult); } @@ -2122,8 +2124,8 @@ class Table using unfiltered_const_iterator = unfiltered_iterator; Table(o2::soa::ArrowTableRef tableRef) - : mArrowTableRef(tableRef), - mEnd{tableRef.range.size}, + : mArrowTableRef(std::move(tableRef)), + mEnd{mArrowTableRef.range.size}, mBegin{lookupColumnsAndMakeBegin()} { if (mEnd.index != 0) { @@ -2138,8 +2140,8 @@ class Table template requires(isColumnPrefix()) Table(o2::soa::ArrowTableRef tableRef, P const& parent) - : mArrowTableRef(tableRef), - mEnd{tableRef.range.size}, + : mArrowTableRef(std::move(tableRef)), + mEnd{mArrowTableRef.range.size}, mBegin{inheritColumnsAndMakeBegin(parent)} { if (mEnd.index != 0) { @@ -2275,7 +2277,9 @@ class Table return mArrowTableRef.tablePtr->Slice(mArrowTableRef.range.offset, mArrowTableRef.range.size); } - [[nodiscard]] ArrowTableRef asArrowTableRef() const + /// The arrow table and range of this table; copy it to keep it beyond the + /// lifetime of the table + [[nodiscard]] ArrowTableRef const& asArrowTableRef() const { return mArrowTableRef; } @@ -3680,7 +3684,7 @@ struct Join : Table, o2::aod::Hash<"JOIN/0"_h>, o2::aod: template requires(std::constructible_from) Join(ArrowTableRef table, P const& parent) - : base{table, parent} + : base{std::move(table), parent} { if (this->tableSize() != 0) { bindInternalIndicesTo(this); @@ -3788,7 +3792,7 @@ struct Concat : Table, o2::aod::Hash<"CONC/0"_h>, o2::ao using self_t = Concat; Concat(ArrowTableRef table) - : base{table} + : base{std::move(table)} { bindInternalIndicesTo(this); } @@ -3875,7 +3879,7 @@ class FilteredBase : public T template requires(std::constructible_from) FilteredBase(ArrowTableRef table, P const& parent, is_a_selection auto selection) - : T{table, parent} + : T{std::move(table), parent} { adoptSelection(selection); T::bindInternalIndicesTo(this); @@ -4153,7 +4157,7 @@ class Filtered : public FilteredBase template requires(std::constructible_from) Filtered(ArrowTableRef table, P const& parent, is_a_selection auto selection) - : FilteredBase{table, parent, std::forward(selection)} {} + : FilteredBase{std::move(table), parent, std::forward(selection)} {} Filtered operator+(is_a_selection auto selection) { @@ -4295,7 +4299,7 @@ class Filtered> : public FilteredBase template requires(std::constructible_from) Filtered(ArrowTableRef table, P const& parent, is_a_selection auto selection) - : FilteredBase{table, parent, std::forward(selection)} {} + : FilteredBase{std::move(table), parent, std::forward(selection)} {} Filtered> operator+(is_a_selection auto selection) { @@ -4431,7 +4435,7 @@ struct IndexTable : Table { } IndexTable(ArrowTableRef table) - : base_t{table} {} + : base_t{std::move(table)} {} /// FIXME: this is a compatiblity for a generic constructor call with a vector /// there has to be a safer way @@ -4460,7 +4464,7 @@ struct SmallGroupsBase : public Filtered { template requires(std::constructible_from) SmallGroupsBase(ArrowTableRef table, P const& parent, is_a_selection auto selection) - : Filtered(table, parent, selection) {} + : Filtered(std::move(table), parent, selection) {} }; template diff --git a/Framework/Core/include/Framework/GroupSlicer.h b/Framework/Core/include/Framework/GroupSlicer.h index a55ae39106920..5b383aa066917 100644 --- a/Framework/Core/include/Framework/GroupSlicer.h +++ b/Framework/Core/include/Framework/GroupSlicer.h @@ -194,7 +194,7 @@ struct GroupSlicer { } } auto range = soa::unsortedSliceRange(originalTable.asArrowTableRef(), s); - return soa::makeTableOn>(range, originalTable, std::move(s)); + return soa::makeTableOn>(std::move(range), originalTable, std::move(s)); } template @@ -219,7 +219,7 @@ struct GroupSlicer { auto groupedElementsTable = originalTable.asArrowTableRef().slice({offset, count}); if (count == 0) { // an empty group selects no rows; starts[index] stays valid for the next groups - return soa::makeTableOn>(groupedElementsTable, originalTable, soa::SelectionVector{}); + return soa::makeTableOn>(std::move(groupedElementsTable), originalTable, soa::SelectionVector{}); } // for each grouping element we need to slice the selection vector @@ -232,7 +232,7 @@ struct GroupSlicer { return idx - static_cast(offset); }); - return soa::makeTableOn>(groupedElementsTable, originalTable, std::move(slicedSelection)); + return soa::makeTableOn>(std::move(groupedElementsTable), originalTable, std::move(slicedSelection)); } template From d3d36ec9dcee64bb5ee93e22bc86f57616025fb0 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 11:19:47 +0100 Subject: [PATCH 20/26] DPL Analysis: avoid extra copies of SelectionVector --- Framework/Core/include/Framework/ASoA.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 10288dc86276b..0f7b6a043c314 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -3870,7 +3870,8 @@ class FilteredBase : public T FilteredBase(std::vector&& tables, is_a_selection auto selection) : T{std::move(tables)} { - adoptSelection(selection); + // selection is this table's own copy: move it in instead of copying it again + adoptSelection(std::move(selection)); T::bindInternalIndicesTo(this); resetRanges(); mFilteredBegin.bindInternalIndices(this); @@ -3881,7 +3882,8 @@ class FilteredBase : public T FilteredBase(ArrowTableRef table, P const& parent, is_a_selection auto selection) : T{std::move(table), parent} { - adoptSelection(selection); + // selection is this table's own copy: move it in instead of copying it again + adoptSelection(std::move(selection)); T::bindInternalIndicesTo(this); resetRanges(); mFilteredBegin.bindInternalIndices(this); @@ -4459,12 +4461,12 @@ struct SmallGroupsBase : public Filtered { static constexpr bool applyFilters = APPLY; SmallGroupsBase(std::vector&& tables, is_a_selection auto selection) - : Filtered(std::move(tables), selection) {} + : Filtered(std::move(tables), std::move(selection)) {} template requires(std::constructible_from) SmallGroupsBase(ArrowTableRef table, P const& parent, is_a_selection auto selection) - : Filtered(std::move(table), parent, selection) {} + : Filtered(std::move(table), parent, std::move(selection)) {} }; template From e9b052ffddf7c6b91b8fbd6986757c4108bf1fa2 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 11:39:59 +0100 Subject: [PATCH 21/26] DPL Analysis: adopt gandiva::Selection as const& --- Framework/Core/include/Framework/ASoA.h | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Framework/Core/include/Framework/ASoA.h b/Framework/Core/include/Framework/ASoA.h index 0f7b6a043c314..619c8a39a1c8f 100644 --- a/Framework/Core/include/Framework/ASoA.h +++ b/Framework/Core/include/Framework/ASoA.h @@ -3870,7 +3870,8 @@ class FilteredBase : public T FilteredBase(std::vector&& tables, is_a_selection auto selection) : T{std::move(tables)} { - // selection is this table's own copy: move it in instead of copying it again + // a SelectionVector is this table's own copy: it is moved in instead of + // being copied again (other selections are only viewed, see adoptSelection) adoptSelection(std::move(selection)); T::bindInternalIndicesTo(this); resetRanges(); @@ -3882,7 +3883,8 @@ class FilteredBase : public T FilteredBase(ArrowTableRef table, P const& parent, is_a_selection auto selection) : T{std::move(table), parent} { - // selection is this table's own copy: move it in instead of copying it again + // a SelectionVector is this table's own copy: it is moved in instead of + // being copied again (other selections are only viewed, see adoptSelection) adoptSelection(std::move(selection)); T::bindInternalIndicesTo(this); resetRanges(); @@ -4090,14 +4092,12 @@ class FilteredBase : public T // with no rows selected and no built iterator, begin is already at the end } - template - inline void adoptSelection(S) - { - } - + // A gandiva::Selection is not adopted, only viewed through a span, so it is + // taken by reference: the constructor's parameter keeps it alive while the + // table is set up, even when the constructor passes it on with std::move. template requires(std::same_as, gandiva::Selection>) - inline void adoptSelection(S selection) + inline void adoptSelection(S const& selection) { mSelectedRows = getSpan(selection); mCached = false; From 2a00e3fd447219dadbd4cfdee049920e3e7f3c18 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 11:41:53 +0100 Subject: [PATCH 22/26] DPL Analysis: fix the tests: selection should not go out of the scope --- Framework/Core/test/test_ASoA.cxx | 4 +++- Framework/Core/test/test_ASoAHelpers.cxx | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/Framework/Core/test/test_ASoA.cxx b/Framework/Core/test/test_ASoA.cxx index 40d6e71893a9b..31bc2126d5304 100644 --- a/Framework/Core/test/test_ASoA.cxx +++ b/Framework/Core/test/test_ASoA.cxx @@ -867,7 +867,9 @@ TEST_CASE("TestAdvancedIndices") using Flt = o2::soa::Filtered; expressions::Filter fltx = (o2::aod::test::x <= -6); - Flt f{{tpts1}, expressions::createSelection(tpts1, fltx)}; + // a Filtered table only views a gandiva::Selection: keep it alive while the table is used + auto selectionx = expressions::createSelection(tpts1, fltx); + Flt f{{tpts1}, selectionx}; prt.bindExternalIndices(&f); auto it2 = prt.begin(); diff --git a/Framework/Core/test/test_ASoAHelpers.cxx b/Framework/Core/test/test_ASoAHelpers.cxx index 5fdecedbfc1a8..51b32a44df325 100644 --- a/Framework/Core/test/test_ASoAHelpers.cxx +++ b/Framework/Core/test/test_ASoAHelpers.cxx @@ -72,7 +72,9 @@ TEST_CASE("IteratorTuple") REQUIRE(*(static_cast(std::get<1>(maxOffset2)).getIterator().mCurrentPos) == 8); expressions::Filter filter = test::x > 3; - auto filtered = Filtered{{tests.asArrowTableRef()}, o2::framework::expressions::createSelection(tests.asArrowTable(), filter)}; + // a Filtered table only views a gandiva::Selection: keep it alive while the table is used + auto selection = o2::framework::expressions::createSelection(tests.asArrowTable(), filter); + auto filtered = Filtered{{tests.asArrowTableRef()}, selection}; std::tuple, Filtered> filteredTuple = std::make_tuple(filtered, filtered); auto it1 = std::get<0>(filteredTuple).begin(); From d285b17c9249fa7e936a8118e66afb6256cf9c7d Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 11:55:43 +0100 Subject: [PATCH 23/26] DPL Analysis: avoid copying selection in SmallGroups slices; avoid rebinding the tables that are obtained by reference --- .../Core/include/Framework/AnalysisTask.h | 16 ++++++++++--- .../Core/include/Framework/GroupSlicer.h | 23 ++++++++----------- 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/Framework/Core/include/Framework/AnalysisTask.h b/Framework/Core/include/Framework/AnalysisTask.h index 90527315a8cf8..8ccb382370e94 100644 --- a/Framework/Core/include/Framework/AnalysisTask.h +++ b/Framework/Core/include/Framework/AnalysisTask.h @@ -25,6 +25,7 @@ #include "Framework/GroupSlicer.h" #include "Framework/StructToTuple.h" #include "Framework/TypeIdHelpers.h" +#include "Framework/VariantHelpers.h" #include "Framework/ArrowTableSlicingCache.h" #include "Framework/AnalysisDataModel.h" #include "Framework/DanglingEdgesContext.h" @@ -401,9 +402,18 @@ struct AnalysisDataProcessorBuilder { // the slices are passed as prvalues and bound to the parameters // directly, so that they are not copied on their way to the process function [&](auto&&... associatedSlices) { - (associatedSlices.setPointerReconstructor(pointerReconstructor), ...); - (associatedSlices.bindInternalIndicesTo(&std::get>(associatedTables)), ...); - (binder(associatedSlices), ...); + auto prepareSlice = framework::overloaded{ + [&](S&& t) + requires(!std::is_lvalue_reference_v) + { + t.setPointerReconstructor(pointerReconstructor); + t.bindInternalIndicesTo(&std::get>(associatedTables)); + binder(t); + }, + // tables not related to the grouping table are passed as references to + // the full tables, which got the same bindings before the slicer was made + [](auto&) {}}; + (prepareSlice(std::forward(associatedSlices)), ...); // bind partitions and grouping table homogeneous_apply_refs_sized([&groupingTable](auto& x) { diff --git a/Framework/Core/include/Framework/GroupSlicer.h b/Framework/Core/include/Framework/GroupSlicer.h index 5b383aa066917..e84dcc60edcf0 100644 --- a/Framework/Core/include/Framework/GroupSlicer.h +++ b/Framework/Core/include/Framework/GroupSlicer.h @@ -178,23 +178,20 @@ struct GroupSlicer { } // generic split auto selection = sliceInfosUnsorted[index].getSliceFor(pos); - // intersect selections - o2::soa::SelectionVector s; - if (selections[index]->empty()) { - if (!selection.empty()) { - std::copy(selection.begin(), selection.end(), std::back_inserter(s)); - } - } else { - if (!selection.empty()) { - if constexpr (std::decay_t::applyFilters) { + if constexpr (std::decay_t::applyFilters) { + if (!selections[index]->empty()) { + // intersect with the filter of the full table: the result is a new selection + o2::soa::SelectionVector s; + if (!selection.empty()) { std::set_intersection(selection.begin(), selection.end(), selections[index]->begin(), selections[index]->end(), std::back_inserter(s)); - } else { - std::copy(selection.begin(), selection.end(), std::back_inserter(s)); } + auto range = soa::unsortedSliceRange(originalTable.asArrowTableRef(), s); + return soa::makeTableOn>(std::move(range), originalTable, std::move(s)); } } - auto range = soa::unsortedSliceRange(originalTable.asArrowTableRef(), s); - return soa::makeTableOn>(std::move(range), originalTable, std::move(s)); + // no filter to apply: view the rows of the group in the slicing cache, + // which lives throughout the process call, instead of copying them + return soa::makeTableOn>(soa::unsortedSliceRange(originalTable.asArrowTableRef(), selection), originalTable, selection); } template From d2e331491b24e0104cdae965f1d2df58d7f88ea7 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 11:56:25 +0100 Subject: [PATCH 24/26] DPL Analysis: add a benchmarks for extreme slicing cases --- .../Core/test/benchmark_SparseSlicing.cxx | 438 ++++++++++++++++++ 1 file changed, 438 insertions(+) create mode 100644 Framework/Core/test/benchmark_SparseSlicing.cxx diff --git a/Framework/Core/test/benchmark_SparseSlicing.cxx b/Framework/Core/test/benchmark_SparseSlicing.cxx new file mode 100644 index 0000000000000..6099fa01ca9ea --- /dev/null +++ b/Framework/Core/test/benchmark_SparseSlicing.cxx @@ -0,0 +1,438 @@ +// Copyright 2019-2020 CERN and copyright holders of ALICE O2. +// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +// All rights not expressly granted are reserved. +// +// This software is distributed under the terms of the GNU General Public +// License v3 (GPL Version 3), copied verbatim in the file "COPYING". +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +#include "Framework/ASoAHelpers.h" +#include "Framework/GroupedCombinations.h" +#include "Framework/GroupSlicer.h" +#include "Framework/TableBuilder.h" +#include "Framework/AnalysisDataModel.h" +#include +#include +#include + +namespace o2::aod +{ +// A table with no index to collisions, so GroupSlicer passes it whole +namespace unrelated +{ +DECLARE_SOA_COLUMN(A, a, float); +DECLARE_SOA_COLUMN(B, b, float); +DECLARE_SOA_COLUMN(C, c, float); +DECLARE_SOA_COLUMN(D, d, float); +DECLARE_SOA_COLUMN(E, e, float); +DECLARE_SOA_COLUMN(F, f, float); +DECLARE_SOA_COLUMN(G, g, float); +DECLARE_SOA_COLUMN(H, h, float); +} // namespace unrelated +DECLARE_SOA_TABLE(Unrelated, "AOD", "UNRELATED", unrelated::A, unrelated::B, unrelated::C, unrelated::D, + unrelated::E, unrelated::F, unrelated::G, unrelated::H); +} // namespace o2::aod + +using namespace o2::framework; +using namespace o2::soa; + +// Derived-data-like input: many collisions, and tracks in only a few of them. +// Per-collision slicing then produces mostly empty tables, so the cost of +// making a table dominates over the cost of iterating its rows. + +namespace +{ +constexpr int collisionsPerTrack = 100; // 1% of the collisions have a track + +using BinningType = ColumnBinningPolicy; + +struct SparseData { + std::shared_ptr collisionTable; + std::shared_ptr trackTable; + std::shared_ptr unrelatedTable; + ArrowTableSlicingCache slicingCache; + SliceCache cache{nullptr}; + // The same index registered as unsorted: a key can be in only one of the + // lists of a cache, as the sorted list is searched first + ArrowTableSlicingCache unsortedSlicingCache; + SliceCache unsortedCache{nullptr}; + + explicit SparseData(int64_t nCollisions) + : slicingCache{{{getLabelFromType(), + getMatcherFromTypeForKey(key()), key()}}}, + unsortedSlicingCache{{}, {{getLabelFromType(), getMatcherFromTypeForKey(key()), key()}}} + { + std::default_random_engine e1(1234567891); + std::uniform_real_distribution uniform_dist(0.f, 1.f); + std::uniform_real_distribution uniform_dist_x(-0.065f, 0.073f); + std::uniform_real_distribution uniform_dist_y(-0.320f, 0.360f); + std::uniform_int_distribution uniform_dist_int(0, 5); + + TableBuilder colBuilder; + auto rowWriterCol = colBuilder.cursor(); + for (auto i = 0; i < nCollisions; ++i) { + rowWriterCol(0, uniform_dist_int(e1), + uniform_dist_x(e1), uniform_dist_y(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist_int(e1), uniform_dist(e1), + uniform_dist_int(e1), + uniform_dist(e1), uniform_dist(e1)); + } + collisionTable = colBuilder.finalize(); + + TableBuilder trackBuilder; + auto rowWriterTrack = trackBuilder.cursor(); + for (auto colIndex = 0; colIndex < nCollisions; colIndex += collisionsPerTrack) { + rowWriterTrack(0, colIndex, 0, + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1)); + } + trackTable = trackBuilder.finalize(); + + TableBuilder unrelatedBuilder; + auto rowWriterUnrelated = unrelatedBuilder.cursor(); + for (auto i = 0; i < 100; ++i) { + rowWriterUnrelated(0, uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), + uniform_dist(e1), uniform_dist(e1), uniform_dist(e1), uniform_dist(e1)); + } + unrelatedTable = unrelatedBuilder.finalize(); + + auto s = slicingCache.updateCacheEntry(0, trackTable); + cache = SliceCache{&slicingCache}; + auto su = unsortedSlicingCache.updateCacheEntryUnsorted(0, trackTable); + unsortedCache = SliceCache{&unsortedSlicingCache}; + } + + static std::string key() + { + return "fIndex" + cutString(getLabelFromType()); + } +}; + +void setCounters(benchmark::State& state, int64_t slices, int64_t rows) +{ + state.counters["Slices"] = static_cast(slices); + state.counters["Rows"] = static_cast(rows); + state.counters["Slices/s"] = benchmark::Counter(static_cast(slices) * state.iterations(), benchmark::Counter::kIsRate); +} +} // namespace + +// The path of a process(Collision const&, Tracks const&) signature: the slices +// are passed to the invoked function directly, as AnalysisTask does +static void BM_SparseGroupSlicer(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + auto associated = std::make_tuple(tracks); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + GroupSlicer slicer(collisions, associated, data.slicingCache); + for (auto& slice : slicer) { + [&](auto&&... tables) { + (tables.bindInternalIndicesTo(&std::get>(associated)), ...); + rows += (tables.size() + ...); + }(slice.template prepareArgument()); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseGroupSlicer)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +// The same with a second associated table that has no index to collisions, +// as in process(Collision const&, Tracks const&, Unrelated const&): GroupSlicer +// passes that table whole for every collision +static void BM_SparseGroupSlicerUnrelated(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + o2::aod::Unrelated unrelated{data.unrelatedTable}; + auto associated = std::make_tuple(tracks, unrelated); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + GroupSlicer slicer(collisions, associated, data.slicingCache); + for (auto& slice : slicer) { + [&](auto&&... tables) { + (tables.bindInternalIndicesTo(&std::get>(associated)), ...); + rows += (tables.size() + ...); + }(slice.template prepareArgument(), slice.template prepareArgument()); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseGroupSlicerUnrelated)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +static void BM_SparseSliceByCached(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceByCached(o2::aod::track::collisionId, collision.globalIndex(), data.cache); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseSliceByCached)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +static void BM_SparseFilteredSliceByCached(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + SelectionVector all(data.trackTable->num_rows()); + std::iota(all.begin(), all.end(), 0); + Filtered tracks{{data.trackTable}, std::move(all)}; + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceByCached(o2::aod::track::collisionId, collision.globalIndex(), data.cache); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseFilteredSliceByCached)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +// Slicing with a sorted Preslice, as a task does with sliceBy +static void BM_SparseSliceBy(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + Preslice perCollision = o2::aod::track::collisionId; + perCollision.updateSliceInfo(data.slicingCache.getCacheFor(perCollision.getBindingKey())); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceBy(perCollision, collision.globalIndex()); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseSliceBy)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +static void BM_SparseFilteredSliceBy(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + SelectionVector all(data.trackTable->num_rows()); + std::iota(all.begin(), all.end(), 0); + Filtered tracks{{data.trackTable}, std::move(all)}; + Preslice perCollision = o2::aod::track::collisionId; + perCollision.updateSliceInfo(data.slicingCache.getCacheFor(perCollision.getBindingKey())); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceBy(perCollision, collision.globalIndex()); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseFilteredSliceBy)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +// Slicing with an unsorted Preslice: the slices are filtered tables +static void BM_SparseSliceByUnsorted(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + PresliceUnsorted perCollision = o2::aod::track::collisionId; + perCollision.updateSliceInfo(data.unsortedSlicingCache.getCacheUnsortedFor(perCollision.getBindingKey())); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceBy(perCollision, collision.globalIndex()); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseSliceByUnsorted)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +static void BM_SparseFilteredSliceByUnsorted(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + SelectionVector all(data.trackTable->num_rows()); + std::iota(all.begin(), all.end(), 0); + Filtered tracks{{data.trackTable}, std::move(all)}; + PresliceUnsorted perCollision = o2::aod::track::collisionId; + perCollision.updateSliceInfo(data.unsortedSlicingCache.getCacheUnsortedFor(perCollision.getBindingKey())); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceBy(perCollision, collision.globalIndex()); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseFilteredSliceByUnsorted)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +static void BM_SparseSliceByCachedUnsorted(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceByCachedUnsorted(o2::aod::track::collisionId, collision.globalIndex(), data.unsortedCache); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseSliceByCachedUnsorted)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +static void BM_SparseFilteredSliceByCachedUnsorted(benchmark::State& state) +{ + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + SelectionVector all(data.trackTable->num_rows()); + std::iota(all.begin(), all.end(), 0); + Filtered tracks{{data.trackTable}, std::move(all)}; + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + for (auto const& collision : collisions) { + auto slice = tracks.sliceByCachedUnsorted(o2::aod::track::collisionId, collision.globalIndex(), data.unsortedCache); + rows += slice.size(); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseFilteredSliceByCachedUnsorted)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); + +// Event mixing: every collision pair slices the tracks of both collisions +static void BM_SparseMixedPairs(benchmark::State& state) +{ + constexpr int numEventsToMix = 5; + std::vector xBins{VARIABLE_WIDTH, -0.064, -0.062, -0.060, 0.066, 0.068, 0.070, 0.072}; + std::vector yBins{VARIABLE_WIDTH, -0.320, -0.301, -0.300, 0.330, 0.340, 0.350, 0.360}; + BinningType binningOnPositions{{xBins, yBins}, true}; + + SparseData data(state.range(0)); + o2::aod::Collisions collisions{data.collisionTable}; + o2::aod::StoredTracks tracks{data.trackTable}; + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + auto tracksTuple = std::make_tuple(tracks); + SameKindPair pairs{binningOnPositions, numEventsToMix - 1, -1, collisions, tracksTuple, &data.cache}; + for (auto& [c1, tracks1, c2, tracks2] : pairs) { + rows += tracks1.size() + tracks2.size(); + slices += 2; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +BENCHMARK(BM_SparseMixedPairs)->RangeMultiplier(8)->Range(1 << 10, 1 << 13); + +// A table made directly from an arrow table, as for the inputs of every timeframe +static void BM_TableFromArrow(benchmark::State& state) +{ + SparseData data(1 << 10); + int64_t tables = 0; + int64_t rows = 0; + for (auto _ : state) { + tables = 0; + rows = 0; + for (auto i = 0; i < state.range(0); ++i) { + o2::aod::StoredTracks tracks{data.trackTable}; + rows += tracks.size(); + ++tables; + } + benchmark::DoNotOptimize(rows); + } + state.counters["Tables/s"] = benchmark::Counter(static_cast(tables) * state.iterations(), benchmark::Counter::kIsRate); +} + +BENCHMARK(BM_TableFromArrow)->Arg(1 << 12); + +BENCHMARK_MAIN(); From f5874b4355cf1a41cf32af824f778c29f9aeb040 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 11:59:53 +0100 Subject: [PATCH 25/26] DPL Analysis: add SmallGroups slicing benchmark --- .../Core/test/benchmark_SparseSlicing.cxx | 55 ++++++++++++++++++- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/Framework/Core/test/benchmark_SparseSlicing.cxx b/Framework/Core/test/benchmark_SparseSlicing.cxx index 6099fa01ca9ea..2dee307d33ba3 100644 --- a/Framework/Core/test/benchmark_SparseSlicing.cxx +++ b/Framework/Core/test/benchmark_SparseSlicing.cxx @@ -45,7 +45,7 @@ using namespace o2::soa; namespace { -constexpr int collisionsPerTrack = 100; // 1% of the collisions have a track +constexpr int64_t defaultCollisionsPerTrack = 100; // 1% of the collisions have a track using BinningType = ColumnBinningPolicy; @@ -60,7 +60,7 @@ struct SparseData { ArrowTableSlicingCache unsortedSlicingCache; SliceCache unsortedCache{nullptr}; - explicit SparseData(int64_t nCollisions) + explicit SparseData(int64_t nCollisions, int64_t collisionsPerTrack = defaultCollisionsPerTrack) : slicingCache{{{getLabelFromType(), getMatcherFromTypeForKey(key()), key()}}}, unsortedSlicingCache{{}, {{getLabelFromType(), getMatcherFromTypeForKey(key()), key()}}} @@ -182,6 +182,57 @@ static void BM_SparseGroupSlicerUnrelated(benchmark::State& state) BENCHMARK(BM_SparseGroupSlicerUnrelated)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); +// The path of a process(Collision const&, SmallGroups const&) signature: +// the tracks are sliced through the unsorted cache. With all tracks selected, the +// rows of each group are intersected with the selection of the full table. +// The second argument is the number of collisions per track: 100 is the sparse +// case, 1 gives every collision a track, so that every group has rows. +template +void runGroupSlicerSmallGroups(benchmark::State& state, T const& tracks, SparseData& data) +{ + o2::aod::Collisions collisions{data.collisionTable}; + auto associated = std::make_tuple(tracks); + + int64_t slices = 0; + int64_t rows = 0; + for (auto _ : state) { + slices = 0; + rows = 0; + GroupSlicer slicer(collisions, associated, data.unsortedSlicingCache); + for (auto& slice : slicer) { + [&](auto&&... tables) { + (tables.bindInternalIndicesTo(&std::get>(associated)), ...); + rows += (tables.size() + ...); + }(slice.template prepareArgument()); + ++slices; + } + benchmark::DoNotOptimize(rows); + } + setCounters(state, slices, rows); +} + +static void BM_SparseGroupSlicerSmallGroups(benchmark::State& state) +{ + SparseData data(state.range(0), state.range(1)); + SelectionVector all(data.trackTable->num_rows()); + std::iota(all.begin(), all.end(), 0); + SmallGroups tracks{{data.trackTable}, std::move(all)}; + runGroupSlicerSmallGroups(state, tracks, data); +} + +BENCHMARK(BM_SparseGroupSlicerSmallGroups)->ArgsProduct({benchmark::CreateRange(1 << 10, 1 << 16, 8), {defaultCollisionsPerTrack, 1}}); + +// The same with SmallGroupsUnfiltered, or SmallGroups with no selection on the +// full table: the slices view the rows of each group in the slicing cache +static void BM_SparseGroupSlicerSmallGroupsUnfiltered(benchmark::State& state) +{ + SparseData data(state.range(0), state.range(1)); + SmallGroupsUnfiltered tracks{{data.trackTable}, SelectionVector{}}; + runGroupSlicerSmallGroups(state, tracks, data); +} + +BENCHMARK(BM_SparseGroupSlicerSmallGroupsUnfiltered)->ArgsProduct({benchmark::CreateRange(1 << 10, 1 << 16, 8), {defaultCollisionsPerTrack, 1}}); + static void BM_SparseSliceByCached(benchmark::State& state) { SparseData data(state.range(0)); From 9aec8575152d7b07b2e3a4468aa96aa935ace6a9 Mon Sep 17 00:00:00 2001 From: Anton Alkin Date: Fri, 4 Dec 2026 12:16:56 +0100 Subject: [PATCH 26/26] DPL Analysis: SmallGroups shortcut for a full selection; add benchmarks --- .../Core/include/Framework/GroupSlicer.h | 6 ++++-- .../Core/test/benchmark_SparseSlicing.cxx | 19 +++++++++++++++++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/Framework/Core/include/Framework/GroupSlicer.h b/Framework/Core/include/Framework/GroupSlicer.h index e84dcc60edcf0..aa6fe2c42939d 100644 --- a/Framework/Core/include/Framework/GroupSlicer.h +++ b/Framework/Core/include/Framework/GroupSlicer.h @@ -179,7 +179,9 @@ struct GroupSlicer { // generic split auto selection = sliceInfosUnsorted[index].getSliceFor(pos); if constexpr (std::decay_t::applyFilters) { - if (!selections[index]->empty()) { + // a selection of sorted, unique rows that is as long as the full table + // selects every row: the intersection is then the group itself + if (!selections[index]->empty() && std::ssize(*selections[index]) != originalTable.tableSize()) { // intersect with the filter of the full table: the result is a new selection o2::soa::SelectionVector s; if (!selection.empty()) { @@ -189,7 +191,7 @@ struct GroupSlicer { return soa::makeTableOn>(std::move(range), originalTable, std::move(s)); } } - // no filter to apply: view the rows of the group in the slicing cache, + // no filter to apply, or one that selects every row: view the rows of the group in the slicing cache, // which lives throughout the process call, instead of copying them return soa::makeTableOn>(soa::unsortedSliceRange(originalTable.asArrowTableRef(), selection), originalTable, selection); } diff --git a/Framework/Core/test/benchmark_SparseSlicing.cxx b/Framework/Core/test/benchmark_SparseSlicing.cxx index 2dee307d33ba3..2dc894dc19770 100644 --- a/Framework/Core/test/benchmark_SparseSlicing.cxx +++ b/Framework/Core/test/benchmark_SparseSlicing.cxx @@ -183,8 +183,8 @@ static void BM_SparseGroupSlicerUnrelated(benchmark::State& state) BENCHMARK(BM_SparseGroupSlicerUnrelated)->RangeMultiplier(8)->Range(1 << 10, 1 << 16); // The path of a process(Collision const&, SmallGroups const&) signature: -// the tracks are sliced through the unsorted cache. With all tracks selected, the -// rows of each group are intersected with the selection of the full table. +// the tracks are sliced through the unsorted cache. All tracks are selected, so +// the slices view the rows of each group in the slicing cache. // The second argument is the number of collisions per track: 100 is the sparse // case, 1 gives every collision a track, so that every group has rows. template @@ -222,6 +222,21 @@ static void BM_SparseGroupSlicerSmallGroups(benchmark::State& state) BENCHMARK(BM_SparseGroupSlicerSmallGroups)->ArgsProduct({benchmark::CreateRange(1 << 10, 1 << 16, 8), {defaultCollisionsPerTrack, 1}}); +// The same with a filter that rejects every other track: the rows of each group +// are intersected with the selection of the full table into a new selection +static void BM_SparseGroupSlicerSmallGroupsPartial(benchmark::State& state) +{ + SparseData data(state.range(0), state.range(1)); + SelectionVector half; + for (int64_t i = 0; i < data.trackTable->num_rows(); i += 2) { + half.push_back(i); + } + SmallGroups tracks{{data.trackTable}, std::move(half)}; + runGroupSlicerSmallGroups(state, tracks, data); +} + +BENCHMARK(BM_SparseGroupSlicerSmallGroupsPartial)->ArgsProduct({benchmark::CreateRange(1 << 10, 1 << 16, 8), {defaultCollisionsPerTrack, 1}}); + // The same with SmallGroupsUnfiltered, or SmallGroups with no selection on the // full table: the slices view the rows of each group in the slicing cache static void BM_SparseGroupSlicerSmallGroupsUnfiltered(benchmark::State& state)