diff --git a/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp b/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp index 805c11816bf5..db9462a1713a 100644 --- a/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp +++ b/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp @@ -1090,6 +1090,13 @@ namespace hpx::traits { { return iter->get_id(); } + + // Extract the locality id stored in the partition metadata. This + // avoids an AGAS lookup when an algorithm only needs placement. + static std::uint32_t get_locality_id(segment_iterator const& iter) + { + return iter->locality_id_; + } }; template @@ -1182,6 +1189,13 @@ namespace hpx::traits { { return iter->get_id(); } + + // Extract the locality id stored in the partition metadata. This + // avoids an AGAS lookup when an algorithm only needs placement. + static std::uint32_t get_locality_id(segment_iterator const& iter) + { + return iter->locality_id_; + } }; /////////////////////////////////////////////////////////////////////////// diff --git a/libs/full/include/include/hpx/include/parallel_sort.hpp b/libs/full/include/include/hpx/include/parallel_sort.hpp index 2c4e1662c0e6..ac44bc207f62 100644 --- a/libs/full/include/include/hpx/include/parallel_sort.hpp +++ b/libs/full/include/include/hpx/include/parallel_sort.hpp @@ -8,3 +8,4 @@ #include #include +#include diff --git a/libs/full/segmented_algorithms/CMakeLists.txt b/libs/full/segmented_algorithms/CMakeLists.txt index 850175e944a5..24b3eb2bf4a9 100644 --- a/libs/full/segmented_algorithms/CMakeLists.txt +++ b/libs/full/segmented_algorithms/CMakeLists.txt @@ -37,6 +37,7 @@ set(segmented_algorithms_headers hpx/parallel/segmented_algorithms/reduce.hpp hpx/parallel/segmented_algorithms/replace.hpp hpx/parallel/segmented_algorithms/replace_copy.hpp + hpx/parallel/segmented_algorithms/sort.hpp hpx/parallel/segmented_algorithms/traits/zip_iterator.hpp hpx/parallel/segmented_algorithms/transform_exclusive_scan.hpp hpx/parallel/segmented_algorithms/transform.hpp diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp index af509816055a..fa86776ef3d7 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp @@ -325,11 +325,12 @@ namespace hpx::parallel::detail { { std::list errors; parallel::util::detail::handle_remote_exceptions::call( - f.get_exception_ptr(), - errors); // NOLINT(bugprone-use-after-move) + f.get_exception_ptr(), errors); - // NOLINTNEXTLINE(bugprone-use-after-move) - HPX_ASSERT(errors.empty()); + // handle_remote_exceptions populates errors for non-bad_alloc + // failures; bad_alloc is rethrown from call() above. Assert the + // postcondition, then propagate as exception_list. + HPX_ASSERT(!errors.empty()); throw exception_list(HPX_MOVE(errors)); } return f.get(); diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp new file mode 100644 index 000000000000..17bf017740b0 --- /dev/null +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -0,0 +1,897 @@ +// Copyright (c) 2026 Pratyksh Gupta +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace hpx::parallel::detail { + + /// \cond NOINTERNAL + + // sequential() is templated on the iterator actually passed after + // segmented_local_iterator_traits unwraps to a raw iterator. The class + // result type stays the local (serializable) iterator so dispatch can + // return it. + template + struct segmented_local_sort : algorithm, Iter> + { + constexpr segmented_local_sort() noexcept + : algorithm("segmented_local_sort") + { + } + + template + static InIter sequential(ExPolicy&& policy, InIter first, Sent last, + Comp&& comp, Proj&& proj) + { + auto last_iter = advance_to_sentinel(first, last); + // Unwrap to the local raw iterator (same path as dispatch). Fold + // proj into the comparator: hpx::sort's CPO has no projection. + using local_traits = + hpx::traits::segmented_local_iterator_traits; + hpx::sort(hpx::execution::experimental::to_non_task( + HPX_FORWARD(ExPolicy, policy)), + local_traits::local(first), local_traits::local(last_iter), + util::compare_projected( + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj))); + return last_iter; + } + + template + static InIter parallel(ExPolicy&& policy, InIter first, Sent last, + Comp&& comp, Proj&& proj) + { + // The shared control path still passes the parallel policy to the + // local hpx::sort invocation above. + return sequential(HPX_FORWARD(ExPolicy, policy), first, last, + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); + } + }; + + // Bound outstanding transport and namespace requests independently of + // the number of partitions. + inline constexpr std::size_t segmented_sort_transfer_limit = 8; + + // Even a synchronous launch failure must not leave actions accessing the + // input after the caller observes an exception. + template + void segmented_sort_wait( + std::vector>& pending, std::exception_ptr error = {}) + { + bool const exceptional = hpx::wait_all_nothrow(pending); + if (!exceptional && !error) + { + return; + } + + std::list errors; + using handler = util::detail::handle_remote_exceptions; + if (error) + { + handler::call(error, errors); + } + handler::call(pending, errors); + } + + template + struct segmented_sort_run + { + hpx::id_type id{}; + hpx::id_type locality{}; + LocalIter first{}; + LocalIter last{}; + + std::ptrdiff_t size() const + { + return last - first; + } + }; + + template + auto segmented_sort_runs(SegIter first, SegIter last) + { + using traits = hpx::traits::segmented_iterator_traits; + using segment_iterator = typename traits::segment_iterator; + using local_iterator = typename traits::local_iterator; + using run_type = segmented_sort_run; + + segment_iterator sit = traits::segment(first); + segment_iterator send = traits::segment(last); + + std::vector runs; + runs.reserve(static_cast(std::distance(sit, send)) + 1); + + auto add_run = [&](segment_iterator const& segment, + local_iterator const& beg, + local_iterator const& end) { + if (beg != end) + { + auto id = traits::get_id(segment); + if constexpr (requires { traits::get_locality_id(segment); }) + { + hpx::id_type locality; + auto const locality_id = traits::get_locality_id(segment); + if (locality_id != hpx::naming::invalid_locality_id) + { + locality = + hpx::naming::get_id_from_locality_id(locality_id); + } + runs.emplace_back( + HPX_MOVE(id), HPX_MOVE(locality), beg, end); + } + else + { + runs.emplace_back(HPX_MOVE(id), hpx::id_type{}, beg, end); + } + } + }; + + if (sit == send) + { + add_run(sit, traits::local(first), traits::local(last)); + } + else + { + add_run(sit, traits::local(first), traits::end(sit)); + for (++sit; sit != send; ++sit) + { + add_run(sit, traits::begin(sit), traits::end(sit)); + } + add_run(sit, traits::begin(sit), traits::local(last)); + } + + // Segmented containers without placement metadata still use bounded, + // concurrent namespace lookups. Task policies collect runs inside + // their asynchronous operation, including this fallback phase. + std::vector unresolved; + for (std::size_t i = 0; i != runs.size(); ++i) + { + if (runs[i].locality == hpx::invalid_id) + { + unresolved.push_back(i); + } + } + for (std::size_t first_run = 0; first_run < unresolved.size();) + { + std::vector> pending; + auto const count = (std::min) (segmented_sort_transfer_limit, + unresolved.size() - first_run); + pending.reserve(count); + std::exception_ptr error; + try + { + for (std::size_t i = 0; i < count; ++i) + { + pending.push_back(hpx::get_colocation_id( + runs[unresolved[first_run + i]].id)); + } + } + catch (...) + { + error = std::current_exception(); + } + segmented_sort_wait( + pending, error); + for (std::size_t i = 0; i < count; ++i) + { + runs[unresolved[first_run + i]].locality = pending[i].get(); + } + first_run += count; + } + return runs; + } + + // Bound the payload of each remote transfer independently of the physical + // partition size. Physical partitions remain the sorting units. + inline constexpr std::size_t segmented_sort_transfer_chunk_size = 65536; + + template + using segmented_sort_block = std::vector>; + + template + std::size_t segmented_sort_block_size( + segmented_sort_block const& block) + { + std::size_t size = 0; + for (auto const& run : block) + { + size += static_cast(run.size()); + } + return size; + } + + template + auto segmented_sort_transfer_chunks( + segmented_sort_block const& block) + { + std::vector> chunks; + for (auto const& run : block) + { + auto first = run.first; + while (first != run.last) + { + auto const count = + (std::min) (segmented_sort_transfer_chunk_size, + static_cast(run.last - first)); + auto last = first + static_cast(count); + chunks.push_back({{run.id, run.locality, first, last}}); + first = last; + } + } + return chunks; + } + + // Choose the locality holding the most participating data so the k-way + // merge transfers as little input as possible. + template + hpx::id_type segmented_sort_host( + segmented_sort_block const& left, + segmented_sort_block const& right) + { + std::map sizes; + for (auto const& run : left) + { + sizes[run.locality] += static_cast(run.size()); + } + for (auto const& run : right) + { + sizes[run.locality] += static_cast(run.size()); + } + auto host = sizes.begin(); + for (auto it = std::next(host); it != sizes.end(); ++it) + { + if (it->second > host->second) + { + host = it; + } + } + return host->first; + } + + template + struct segmented_fetch_values + : algorithm, + std::vector::value_type>> + { + using value_type = std::iterator_traits::value_type; + + constexpr segmented_fetch_values() noexcept + : algorithm>( + "segmented_fetch_values") + { + } + + template + static std::vector sequential( + ExPolicy const&, segmented_sort_block const& runs) + { + using traits = + hpx::traits::segmented_local_iterator_traits; + std::vector values; + values.reserve(segmented_sort_block_size(runs)); + for (auto const& run : runs) + { + if constexpr (std::is_copy_constructible_v) + { + values.insert(values.end(), traits::local(run.first), + traits::local(run.last)); + } + else + { + values.insert(values.end(), + std::make_move_iterator(traits::local(run.first)), + std::make_move_iterator(traits::local(run.last))); + } + } + return values; + } + + template + static std::vector parallel( + ExPolicy const& policy, segmented_sort_block const& runs) + { + // A single block is copied serially. Concurrency between remote + // blocks is provided by segmented_sort_fetch_block. + return sequential(policy, runs); + } + }; + + template + struct segmented_store_values + : algorithm, bool> + { + using value_type = std::iterator_traits::value_type; + + constexpr segmented_store_values() noexcept + : algorithm("segmented_store_values") + { + } + + template + static bool sequential(ExPolicy const& policy, + segmented_sort_block const& runs, + std::vector values) + { + using traits = + hpx::traits::segmented_local_iterator_traits; + auto first = values.begin(); + for (auto const& run : runs) + { + auto last = first + run.size(); + hpx::move(policy, first, last, traits::local(run.first)); + first = last; + } + return true; + } + + template + static bool parallel(ExPolicy const& policy, + segmented_sort_block const& runs, + std::vector values) + { + // The shared control path still passes the parallel policy to + // hpx::move for every destination run. + return sequential(policy, runs, HPX_MOVE(values)); + } + }; + + template + auto segmented_sort_fetch_block( + ExPolicy const& policy, segmented_sort_block const& block) + { + using value_type = std::iterator_traits::value_type; + auto const here = hpx::find_here(); + if (std::all_of(block.begin(), block.end(), + [&](auto const& run) { return run.locality == here; })) + { + return segmented_fetch_values::sequential(policy, block); + } + std::vector values; + values.reserve(segmented_sort_block_size(block)); + auto chunks = segmented_sort_transfer_chunks(block); + constexpr auto limit = hpx::is_sequenced_execution_policy_v ? + 1 : + segmented_sort_transfer_limit; + auto it = chunks.begin(); + while (it != chunks.end()) + { + auto batch_end = it; + for (std::size_t i = 0; i < limit && batch_end != chunks.end(); + ++i, ++batch_end) + { + } + + auto const count = + static_cast(std::distance(it, batch_end)); + std::vector> parts(count); + std::vector> pending; + pending.reserve(limit); + std::exception_ptr error; + try + { + auto current = it; + for (std::size_t i = 0; current != batch_end; ++i, ++current) + { + auto pieces = *current; + auto const host = pieces.front().locality; + if (host != here) + { + pending.push_back(dispatch_async(host, + segmented_fetch_values(), policy, + std::true_type(), HPX_MOVE(pieces)) + .then([&parts, i]( + hpx::future> + ready) { + parts[i] = ready.get(); + })); + } + } + + current = it; + for (std::size_t i = 0; current != batch_end; ++i, ++current) + { + auto const& pieces = *current; + if (pieces.front().locality == here) + { + parts[i] = + segmented_fetch_values::sequential( + policy, pieces); + } + } + } + catch (...) + { + error = std::current_exception(); + } + segmented_sort_wait(pending, error); + for (auto& part : parts) + { + values.insert(values.end(), + std::make_move_iterator(part.begin()), + std::make_move_iterator(part.end())); + } + it = batch_end; + } + return values; + } + + template + Iter segmented_sort_store_block(ExPolicy const& policy, + segmented_sort_block const& block, Iter first) + { + using value_type = std::iterator_traits::value_type; + auto const here = hpx::find_here(); + auto chunks = segmented_sort_transfer_chunks(block); + constexpr auto limit = hpx::is_sequenced_execution_policy_v ? + 1 : + segmented_sort_transfer_limit; + auto it = chunks.begin(); + while (it != chunks.end()) + { + auto batch_end = it; + for (std::size_t i = 0; i < limit && batch_end != chunks.end(); + ++i, ++batch_end) + { + } + + std::vector> pending; + pending.reserve(limit); + std::exception_ptr error; + try + { + auto current = first; + for (auto chunk = it; chunk != batch_end; ++chunk) + { + auto pieces = *chunk; + auto const host = pieces.front().locality; + auto last = current + + static_cast( + segmented_sort_block_size(pieces)); + if (host != here) + { + std::vector values( + std::make_move_iterator(current), + std::make_move_iterator(last)); + pending.push_back(dispatch_async(host, + segmented_store_values(), policy, + std::true_type(), HPX_MOVE(pieces), + HPX_MOVE(values))); + } + current = last; + } + + current = first; + for (auto chunk = it; chunk != batch_end; ++chunk) + { + auto const& pieces = *chunk; + auto last = current + + static_cast( + segmented_sort_block_size(pieces)); + if (pieces.front().locality == here) + { + using traits = + hpx::traits::segmented_local_iterator_traits< + LocalIter>; + auto source = current; + for (auto const& piece : pieces) + { + auto next = source + piece.size(); + hpx::move(policy, source, next, + traits::local(piece.first)); + source = next; + } + } + current = last; + } + first = current; + } + catch (...) + { + error = std::current_exception(); + } + segmented_sort_wait(pending, error); + it = batch_end; + } + return first; + } + + // Merge the sorted input runs without constructing a second full-size + // output buffer. Values are selected once into one destination buffer at + // a time. Stores are incremental and therefore cannot be rolled back if a + // later comparison or destination operation throws. + template + void segmented_sort_kway_for_each(std::vector& values, + std::vector const& offsets, + std::vector const& counts, Pred& pred, Emit&& emit) + { + struct cursor + { + std::size_t pos; + std::size_t end; + }; + + auto order = [&](cursor const& lhs, cursor const& rhs) { + return pred(values[rhs.pos], values[lhs.pos]); + }; + std::priority_queue, decltype(order)> heap( + order); + + for (std::size_t i = 0; i != counts.size(); ++i) + { + if (counts[i] != 0) + { + heap.push(cursor{offsets[i], offsets[i] + counts[i]}); + } + } + + while (!heap.empty()) + { + auto current = heap.top(); + heap.pop(); + emit(HPX_MOVE(values[current.pos])); + if (++current.pos != current.end) + { + heap.push(current); + } + } + } + + template + struct segmented_sort_local_runs_on_host + : algorithm, bool> + { + constexpr segmented_sort_local_runs_on_host() noexcept + : algorithm( + "segmented_sort_local_runs_on_host") + { + } + + template + static bool sequential(ExPolicy const& policy, + segmented_sort_block const& runs, Comp comp, Proj proj) + { + for (auto const& run : runs) + { + segmented_local_sort::sequential( + policy, run.first, run.last, comp, proj); + } + return true; + } + + template + static bool parallel(ExPolicy const& policy, + segmented_sort_block const& runs, Comp comp, Proj proj) + { + // The run loop is orchestration; each local sort receives the + // parallel policy, and localities are overlapped by the caller. + return sequential(policy, runs, HPX_MOVE(comp), HPX_MOVE(proj)); + } + }; + + // Send one operation to each participating locality. A parallel policy + // overlaps localities, while each operation applies the caller's policy to + // every complete physical partition on that locality. + template + void segmented_sort_local_runs(ExPolicy const& policy, + segmented_sort_block const& runs, Comp const& comp, + Proj const& proj, IsSeq is_seq) + { + using operation = segmented_sort_local_runs_on_host; + std::map> groups; + for (auto const& run : runs) + { + groups[run.locality].push_back(run); + } + + auto const here = hpx::find_here(); + if constexpr (IsSeq::value) + { + for (auto const& [host, local_runs] : groups) + { + if (host == here) + { + operation::sequential(policy, local_runs, comp, proj); + } + else + { + dispatch(host, operation(), policy, is_seq, local_runs, + comp, proj); + } + } + } + else + { + std::vector> pending; + pending.reserve(groups.size()); + std::exception_ptr error; + try + { + for (auto const& [host, local_runs] : groups) + { + if (host == here) + { + pending.push_back(hpx::async( + [policy, local_runs, comp, proj]() mutable { + return operation::parallel(policy, local_runs, + HPX_MOVE(comp), HPX_MOVE(proj)); + })); + } + else + { + pending.push_back(dispatch_async(host, operation(), + policy, is_seq, local_runs, comp, proj)); + } + } + } + catch (...) + { + error = std::current_exception(); + } + segmented_sort_wait(pending, error); + } + } + + template + struct segmented_sort_kway_merge_on_host + : algorithm, bool> + { + constexpr segmented_sort_kway_merge_on_host() noexcept + : algorithm( + "segmented_sort_kway_merge_on_host") + { + } + + template + static bool execute(ExPolicy const& policy, + segmented_sort_block const& runs, Comp comp, Proj proj) + { + using value_type = std::iterator_traits::value_type; + + std::vector counts; + std::vector offsets; + counts.reserve(runs.size()); + offsets.reserve(runs.size()); + std::size_t total = 0; + for (auto const& run : runs) + { + offsets.push_back(total); + auto const count = static_cast(run.size()); + counts.push_back(count); + total += count; + } + + auto values = segmented_sort_fetch_block(policy, runs); + HPX_ASSERT(values.size() == total); + + util::compare_projected pred(comp, proj); + std::size_t destination = 0; + std::vector output; + output.reserve(counts.front()); + auto emit = [&](value_type&& value) { + output.push_back(HPX_MOVE(value)); + if (output.size() != counts[destination]) + { + return; + } + + segmented_sort_block block{runs[destination]}; + [[maybe_unused]] auto const last = + segmented_sort_store_block(policy, block, output.begin()); + HPX_ASSERT(last == output.end()); + output.clear(); + if (++destination != runs.size()) + { + output.reserve(counts[destination]); + } + }; + + segmented_sort_kway_for_each(values, offsets, counts, pred, emit); + HPX_ASSERT(destination == runs.size()); + return true; + } + + template + static bool sequential(ExPolicy const& policy, + segmented_sort_block const& runs, Comp comp, Proj proj) + { + return execute(policy, runs, HPX_MOVE(comp), HPX_MOVE(proj)); + } + + template + static bool parallel(ExPolicy const& policy, + segmented_sort_block const& runs, Comp comp, Proj proj) + { + // The current first implementation intentionally shares the + // serial k-way merge. The policy still controls fetch/store work. + return execute(policy, runs, HPX_MOVE(comp), HPX_MOVE(proj)); + } + }; + + // This first implementation fetches each sorted run onto the locality + // already holding the most participating data, performs one serial k-way + // merge there, and writes each final run once. Network traffic and peak + // coordinator storage are O(N); the merge is O(N log P), where P is the + // number of participating runs. + template + void segmented_sort_merge_runs(ExPolicy const& policy, + segmented_sort_block const& runs, Comp const& comp, + Proj const& proj, IsSeq is_seq) + { + if (runs.size() <= 1) + { + return; + } + + using operation = segmented_sort_kway_merge_on_host; + segmented_sort_block const empty; + auto const host = segmented_sort_host(runs, empty); + std::vector> pending; + std::exception_ptr error; + try + { + if (host == hpx::find_here()) + { + operation().call2(policy, is_seq, runs, comp, proj); + } + else + { + pending.push_back(dispatch_async( + host, operation(), policy, is_seq, runs, comp, proj)); + } + } + catch (...) + { + error = std::current_exception(); + } + segmented_sort_wait(pending, error); + } + + template + void segmented_sort_distributed(ExPolicy const& policy, + segmented_sort_block const& runs, Comp const& comp, + Proj const& proj, IsSeq is_seq) + { + segmented_sort_local_runs(policy, runs, comp, proj, is_seq); + segmented_sort_merge_runs(policy, runs, comp, proj, is_seq); + } + + template + util::detail::algorithm_result_t segmented_sort( + ExPolicy const& policy, SegIter first, SegIter last, Comp&& comp, + Proj&& proj, IsSeq is_seq) + { + using result = util::detail::algorithm_result; + + if (first == last) + { + return result::get(); + } + + std::decay_t cmp(HPX_FORWARD(Comp, comp)); + std::decay_t prj(HPX_FORWARD(Proj, proj)); + + // Drop the task bit so nested hpx::sort/copy/merge stay synchronous + // while still honouring the caller's parallel/sequenced choice. + auto const sync_policy = + hpx::execution::experimental::to_non_task(policy); + + if constexpr (hpx::is_async_execution_policy_v) + { + return result::get(hpx::async([=]() mutable { + auto runs = segmented_sort_runs(first, last); + if (!runs.empty()) + { + segmented_sort_distributed( + sync_policy, runs, cmp, prj, is_seq); + } + })); + } + else + { + auto runs = segmented_sort_runs(first, last); + if (!runs.empty()) + { + segmented_sort_distributed(sync_policy, runs, cmp, prj, is_seq); + } + return result::get(); + } + } + + /// \endcond +} // namespace hpx::parallel::detail + +namespace hpx::segmented { + + /// \brief Segmented overload of \a hpx::sort for + /// \a partitioned_vector iterators. + /// + /// A sequenced policy processes participating localities one at a time. + /// A parallel policy overlaps independent locality operations. For ranges + /// spanning localities, the comparator must be copyable and serializable + /// by HPX. + /// + /// This first implementation gathers all participating runs on one + /// locality. Its final merge is serial, requires O(N) coordinator storage, + /// and takes O(N log P) comparisons for P participating runs. Destination + /// runs are committed incrementally; an exception during this phase can + /// leave a partially reordered range. + HPX_CXX_EXPORT template + requires(hpx::traits::is_iterator_v && + hpx::traits::is_segmented_iterator_v) + void hpx_invoke( + hpx::sort_t, SegIter first, SegIter last, Comp&& comp = Comp()) + { + static_assert(std::random_access_iterator, + "Requires a random access iterator."); + + if (first == last) + { + return; + } + + hpx::parallel::detail::segmented_sort(hpx::execution::seq, first, last, + HPX_FORWARD(Comp, comp), hpx::identity_v, std::true_type{}); + } + + /// \brief Segmented overload of \a hpx::sort with an execution policy. + /// + /// For ranges spanning localities, the comparator must be copyable and + /// serializable by HPX. + /// + /// The policy controls local partition sorting and whether independent + /// locality operations overlap. This first implementation gathers all + /// participating runs on one locality. Its final merge is serial, requires + /// O(N) coordinator storage, and takes O(N log P) comparisons for P + /// participating runs. Destination runs are committed incrementally; an + /// exception during this phase can leave a partially reordered range. + HPX_CXX_EXPORT template + requires(hpx::is_execution_policy_v && + hpx::traits::is_iterator_v && + hpx::traits::is_segmented_iterator_v) + hpx::parallel::util::detail::algorithm_result_t hpx_invoke( + hpx::sort_t, ExPolicy&& policy, SegIter first, SegIter last, + Comp&& comp = Comp()) + { + static_assert(std::random_access_iterator, + "Requires a random access iterator."); + + using is_seq = hpx::is_sequenced_execution_policy; + + return hpx::parallel::detail::segmented_sort( + HPX_FORWARD(ExPolicy, policy), first, last, HPX_FORWARD(Comp, comp), + hpx::identity_v, is_seq()); + } +} // namespace hpx::segmented diff --git a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt index dce31478ece1..3004e40df7a2 100644 --- a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt +++ b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt @@ -59,6 +59,7 @@ set(tests partitioned_vector_reduce partitioned_vector_replace partitioned_vector_replace_copy + partitioned_vector_sort ) set(partitioned_vector_inclusive_scan_PARAMETERS RUN_SERIAL) @@ -95,7 +96,10 @@ foreach(test ${tests}) set(sources ${test}.cpp) set(${test}_FLAGS DEPENDENCIES partitioned_vector_component) - if(test MATCHES "^partitioned_vector_merge(_extended|_regressions)?$") + if(test STREQUAL "partitioned_vector_sort" + OR test MATCHES "^partitioned_vector_merge(_extended|_regressions)?$" + ) + # Four localities exercise concurrent merges and remote transfers. set(test_localities 4) else() set(test_localities 2) @@ -123,3 +127,10 @@ foreach(test ${tests}) ) endforeach() + +if(HPX_WITH_CXX_MODULES) + # This test inspects implementation helpers that are not exported by HPX.Full. + target_compile_definitions( + partitioned_vector_sort_test PRIVATE HPX_HAVE_FORCE_NO_CXX_MODULES + ) +endif() diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp new file mode 100644 index 000000000000..b9cead3637cc --- /dev/null +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -0,0 +1,629 @@ +// Copyright (c) 2026 Pratyksh Gupta +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +#include +#if !defined(HPX_COMPUTE_DEVICE_CODE) +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/////////////////////////////////////////////////////////////////////////////// +#define HPX_SEGMENTED_SORT_TEST_SIZE 64 +#define LARGE_SIZE 2048 + +template +T make_sort_value(int i) +{ + if constexpr (std::is_same_v) + { + return std::to_string(i); + } + else + { + return T(i); + } +} + +// Transfer test data per partition instead of issuing a synchronous remote +// request for every element during setup and verification. +template +std::vector copy_values(hpx::partitioned_vector const& values) +{ + std::vector positions(values.size()); + std::iota(positions.begin(), positions.end(), std::size_t(0)); + return values.get_values(hpx::launch::sync, positions); +} + +template +void initialize_values(hpx::partitioned_vector& values, F make_value) +{ + std::vector positions(values.size()); + std::iota(positions.begin(), positions.end(), std::size_t(0)); + std::vector data(values.size()); + std::transform( + positions.begin(), positions.end(), data.begin(), make_value); + values.set_values(hpx::launch::sync, positions, data); +} + +template +void verify_sorted( + hpx::partitioned_vector const& values, std::vector expected) +{ + std::sort(expected.begin(), expected.end()); + HPX_TEST(hpx::is_sorted(values.begin(), values.end())); + + std::vector const got = copy_values(values); + HPX_TEST_EQ(got.size(), expected.size()); + for (std::size_t i = 0; i != got.size(); ++i) + { + HPX_TEST_EQ(got[i], expected[i]); + } +} + +template +void verify_sorted(hpx::partitioned_vector const& values, + std::vector expected, Comp comp) +{ + std::sort(expected.begin(), expected.end(), comp); + HPX_TEST(hpx::is_sorted(values.begin(), values.end(), comp)); + + std::vector const got = copy_values(values); + HPX_TEST_EQ(got.size(), expected.size()); + for (std::size_t i = 0; i != got.size(); ++i) + { + HPX_TEST_EQ(got[i], expected[i]); + } +} + +template +void initialize_reverse(hpx::partitioned_vector& values) +{ + initialize_values(values, [](int i) { + return make_sort_value(HPX_SEGMENTED_SORT_TEST_SIZE - i); + }); +} + +template +void initialize_mixed(hpx::partitioned_vector& values) +{ + initialize_values(values, [](int i) { + return make_sort_value((i * 17 + 3) % HPX_SEGMENTED_SORT_TEST_SIZE); + }); +} + +template +void initialize_sorted(hpx::partitioned_vector& values) +{ + initialize_values(values, [](int i) { return make_sort_value(i); }); +} + +template +void initialize_duplicates(hpx::partitioned_vector& values) +{ + initialize_values(values, [](int i) { return make_sort_value(i % 4); }); +} + +template +void initialize_mixed_n(hpx::partitioned_vector& values, int n) +{ + initialize_values( + values, [n](int i) { return make_sort_value((i * 17 + 3) % n); }); +} + +struct throwing_less +{ + // Two template parameters so libc++ can pass heterogeneous + // iterator dereference / proxy types into std::sort. + template + bool operator()(T const&, U const&) const + { + throw std::runtime_error("segmented sort comparator"); + } + + template + void serialize(Archive&, unsigned) + { + } +}; + +template +void test_sort_once(hpx::partitioned_vector& values) +{ + std::vector const expected = copy_values(values); + hpx::sort(values.begin(), values.end()); + verify_sorted(values, expected); +} + +template +void test_sort_once(ExPolicy&& policy, hpx::partitioned_vector& values) +{ + std::vector const expected = copy_values(values); + hpx::sort(HPX_FORWARD(ExPolicy, policy), values.begin(), values.end()); + verify_sorted(values, expected); +} + +template +void test_sort_once_async(ExPolicy&& policy, hpx::partitioned_vector& values) +{ + std::vector const expected = copy_values(values); + hpx::sort(HPX_FORWARD(ExPolicy, policy), values.begin(), values.end()) + .get(); + verify_sorted(values, expected); +} + +template +void test_sort_comp(hpx::partitioned_vector& values, Comp comp) +{ + std::vector const expected = copy_values(values); + hpx::sort(values.begin(), values.end(), comp); + verify_sorted(values, expected, comp); +} + +template +void test_sort_comp( + ExPolicy&& policy, hpx::partitioned_vector& values, Comp comp) +{ + std::vector const expected = copy_values(values); + hpx::sort( + HPX_FORWARD(ExPolicy, policy), values.begin(), values.end(), comp); + verify_sorted(values, expected, comp); +} + +template +void test_sort_comp_async( + ExPolicy&& policy, hpx::partitioned_vector& values, Comp comp) +{ + std::vector const expected = copy_values(values); + hpx::sort(HPX_FORWARD(ExPolicy, policy), values.begin(), values.end(), comp) + .get(); + verify_sorted(values, expected, comp); +} + +bool caught_sort_exception(std::function const& f) +{ + try + { + f(); + } + catch (hpx::exception_list const&) + { + return true; + } + catch (std::runtime_error const&) + { + return true; + } + return false; +} + +template +void test_sort_throwing(std::vector& localities) +{ + hpx::partitioned_vector values( + HPX_SEGMENTED_SORT_TEST_SIZE, T{}, hpx::container_layout(localities)); + initialize_mixed(values); + + throwing_less comp; + HPX_TEST(caught_sort_exception( + [&]() { hpx::sort(values.begin(), values.end(), comp); })); + + initialize_mixed(values); + HPX_TEST(caught_sort_exception([&]() { + hpx::sort(hpx::execution::par, values.begin(), values.end(), comp); + })); + + initialize_mixed(values); + HPX_TEST(caught_sort_exception([&]() { + hpx::sort(hpx::execution::par(hpx::execution::task), values.begin(), + values.end(), comp) + .get(); + })); +} + +template +void test_sort_large(std::vector& localities) +{ + hpx::partitioned_vector values( + LARGE_SIZE, T{}, hpx::container_layout(localities)); + initialize_mixed_n(values, LARGE_SIZE); + test_sort_once(hpx::execution::par, values); +} + +template +void run_cases(std::vector& localities) +{ + hpx::partitioned_vector values( + HPX_SEGMENTED_SORT_TEST_SIZE, T{}, hpx::container_layout(localities)); + + initialize_reverse(values); + test_sort_once(values); + + initialize_mixed(values); + test_sort_once(hpx::execution::seq, values); + + initialize_mixed(values); + test_sort_once(hpx::execution::par, values); + + initialize_mixed(values); + test_sort_once_async(hpx::execution::seq(hpx::execution::task), values); + + initialize_mixed(values); + test_sort_once_async(hpx::execution::par(hpx::execution::task), values); + + initialize_sorted(values); + test_sort_once(values); + + initialize_duplicates(values); + test_sort_once(values); + + std::greater greater; + initialize_mixed(values); + test_sort_comp(values, greater); + + initialize_mixed(values); + test_sort_comp(hpx::execution::par, values, greater); + + initialize_mixed(values); + test_sort_comp_async( + hpx::execution::par(hpx::execution::task), values, greater); + + hpx::partitioned_vector empty(0, T{}, hpx::container_layout(localities)); + test_sort_once(empty); +} + +template +void test_sort_subranges( + ExPolicy const& policy, std::vector const& localities) +{ + // Eight partitions put multiple partitions on each locality. The + // [3, 47) subrange spans five runs, including clipped endpoints. + // [33, 77) starts on a remote partition with two or four localities. + hpx::partitioned_vector values( + 80, 0, hpx::container_layout(8, localities)); + std::pair const ranges[] = { + {0, 0}, {3, 4}, {2, 7}, {3, 10}, {10, 20}, {3, 47}, {33, 77}, {0, 80}}; + + for (auto const& [begin, end] : ranges) + { + initialize_mixed_n(values, 80); + auto expected = copy_values(values); + std::sort(expected.begin() + begin, expected.begin() + end, + std::greater{}); + + if constexpr (hpx::is_async_execution_policy_v) + { + hpx::sort(policy, values.begin() + begin, values.begin() + end, + std::greater{}) + .get(); + } + else + { + hpx::sort(policy, values.begin() + begin, values.begin() + end, + std::greater{}); + } + + // Comparing the whole vector also checks that values outside the + // requested subrange remain unchanged. + HPX_TEST(copy_values(values) == expected); + } +} + +struct move_only_sort_value +{ + explicit move_only_sort_value(int value) + : value(value) + { + } + + move_only_sort_value() = delete; + move_only_sort_value(move_only_sort_value const&) = delete; + move_only_sort_value& operator=(move_only_sort_value const&) = delete; + move_only_sort_value(move_only_sort_value&&) = default; + move_only_sort_value& operator=(move_only_sort_value&&) = default; + + int value; +}; + +// Cover arbitrary run counts, short final runs, duplicates, and value types +// that cannot be copied or default constructed. +void test_kway_merge() +{ + namespace detail = hpx::parallel::detail; + + for (std::size_t run_count : {3, 5, 6, 7}) + { + for (std::size_t tail = 1; tail != 5; ++tail) + { + for (std::size_t seed = 0; seed != 16; ++seed) + { + std::vector values; + std::vector offsets; + std::vector counts; + std::vector expected; + for (std::size_t run = 0; run != run_count; ++run) + { + offsets.push_back(values.size()); + auto const count = run + 1 == run_count ? tail : 5; + counts.push_back(count); + std::vector part(count); + for (std::size_t i = 0; i != count; ++i) + { + part[i] = static_cast( + (run * 17 + i * 13 + seed * 7) % 11); + } + std::sort(part.begin(), part.end()); + expected.insert(expected.end(), part.begin(), part.end()); + values.insert(values.end(), part.begin(), part.end()); + } + std::sort(expected.begin(), expected.end()); + + std::vector output; + output.reserve(values.size()); + std::less pred; + detail::segmented_sort_kway_for_each(values, offsets, counts, + pred, + [&](int&& value) { output.push_back(HPX_MOVE(value)); }); + HPX_TEST(output == expected); + } + } + } + + std::vector values; + for (int value : {0, 3, 6, 1, 4, 7, 2, 5, 8}) + { + values.emplace_back(value); + } + std::vector const offsets{0, 3, 6}; + std::vector const counts{3, 3, 3}; + auto pred = [](move_only_sort_value const& lhs, + move_only_sort_value const& rhs) { + return lhs.value < rhs.value; + }; + std::vector output; + detail::segmented_sort_kway_for_each( + values, offsets, counts, pred, [&](move_only_sort_value&& value) { + output.push_back(HPX_MOVE(value)); + }); + HPX_TEST_EQ(output.size(), std::size_t(9)); + for (std::size_t i = 0; i != output.size(); ++i) + { + HPX_TEST_EQ(output[i].value, static_cast(i)); + } +} + +void test_large_transfers(std::vector const& localities) +{ + // Large enough to exercise multiple bounded transfers through the public + // algorithm without depending on implementation helpers. + constexpr std::size_t size = 8 * 65536 + 7; + hpx::partitioned_vector values( + size, 0, hpx::container_layout(3, localities)); + initialize_values(values, + [](std::size_t i) { return static_cast((i * 17 + 3) % 97); }); + auto expected = copy_values(values); + std::sort(expected.begin() + 1, expected.end() - 2); + hpx::sort(hpx::execution::par(hpx::execution::task), values.begin() + 1, + values.end() - 2) + .get(); + HPX_TEST(copy_values(values) == expected); + + // Exercise the distributed merge with nontrivial values and descending + // order as well as the default integer comparator above. + hpx::partitioned_vector strings( + 2 * 65536 + 7, std::string{}, hpx::container_layout(3, localities)); + initialize_values(strings, [](std::size_t i) { + return std::to_string((i * 17 + 3) % 97) + std::string(32, 'x'); + }); + auto expected_strings = copy_values(strings); + std::greater greater; + std::sort(expected_strings.begin(), expected_strings.end(), greater); + hpx::sort(hpx::execution::seq(hpx::execution::task), strings.begin(), + strings.end(), greater) + .get(); + HPX_TEST(copy_values(strings) == expected_strings); +} + +struct throwing_merge_less +{ + bool allocation; + + bool operator()(int a, int b) const + { + // Each initial run lies within one band. Only a merge compares + // different bands, after the local sort phase has succeeded. + constexpr auto band_size = static_cast( + hpx::parallel::detail::segmented_sort_transfer_chunk_size); + if (a / band_size != b / band_size) + { + if (allocation) + { + throw std::bad_alloc(); + } + throw std::runtime_error("segmented merge comparator"); + } + return a < b; + } + + template + void serialize(Archive& ar, unsigned) + { + ar & allocation; + } +}; + +template +void test_merge_exceptions( + ExPolicy const& policy, std::vector const& localities) +{ + for (bool allocation : {false, true}) + { + auto const size = + 4 * hpx::parallel::detail::segmented_sort_transfer_chunk_size; + hpx::partitioned_vector values( + size, 0, hpx::container_layout(4, localities)); + initialize_values(values, [](std::size_t i) { + constexpr auto band_size = + hpx::parallel::detail::segmented_sort_transfer_chunk_size; + auto const band = i / band_size; + return static_cast((3 - band) * band_size + i % band_size); + }); + bool caught = false; + try + { + if constexpr (hpx::is_async_execution_policy_v) + { + hpx::sort(policy, values.begin(), values.end(), + throwing_merge_less{allocation}) + .get(); + } + else + { + hpx::sort(policy, values.begin(), values.end(), + throwing_merge_less{allocation}); + } + } + catch (std::bad_alloc const&) + { + HPX_TEST(allocation); + caught = true; + } + catch (hpx::exception_list const&) + { + HPX_TEST(!allocation); + caught = true; + } + HPX_TEST(caught); + // Reuse immediately: the failed operation must have drained its + // actions. + initialize_reverse(values); + test_sort_once(values); + } +} + +struct collection_gate +{ + hpx::promise release; + hpx::shared_future ready = release.get_future(); +}; + +struct collection_probe_iterator +{ + hpx::partitioned_vector::iterator base; + std::shared_ptr gate; + + bool operator==(collection_probe_iterator const& other) const + { + return base == other.base; + } +}; + +namespace hpx::traits { + template <> + struct segmented_iterator_traits + : segmented_iterator_traits::iterator> + { + using base_traits = + segmented_iterator_traits::iterator>; + + static segment_iterator segment(collection_probe_iterator iter) + { + iter.gate->ready.wait(); + return base_traits::segment(iter.base); + } + + static local_iterator local(collection_probe_iterator iter) + { + return base_traits::local(iter.base); + } + + static std::uint32_t get_locality_id(segment_iterator const&) + { + return hpx::naming::invalid_locality_id; + } + }; +} // namespace hpx::traits + +template +void test_async_run_collection(ExPolicy const& policy) +{ + hpx::partitioned_vector values(64, 0, + hpx::container_layout(2, std::vector{hpx::find_here()})); + initialize_reverse(values); + auto gate = std::make_shared(); + hpx::future sorted; + hpx::promise returned; + auto return_signal = returned.get_future(); + auto invoke = hpx::async([&]() { + sorted = hpx::parallel::detail::segmented_sort(policy, + collection_probe_iterator{values.begin(), gate}, + collection_probe_iterator{values.end(), gate}, std::less{}, + hpx::identity_v, hpx::is_sequenced_execution_policy{}); + returned.set_value(); + }); + // Collection is deliberately blocked; obtaining the sort future must + // not wait for it. Release on timeout too, so the old path fails cleanly. + auto const status = return_signal.wait_for(std::chrono::seconds(5)); + gate->release.set_value(); + invoke.get(); + sorted.get(); + HPX_TEST(status == hpx::future_status::ready); + auto got = copy_values(values); + HPX_TEST(std::is_sorted(got.begin(), got.end())); + + auto runs = hpx::parallel::detail::segmented_sort_runs( + collection_probe_iterator{values.begin(), gate}, + collection_probe_iterator{values.end(), gate}); + for (auto const& run : runs) + { + HPX_TEST(run.locality == hpx::find_here()); + } +} + +/////////////////////////////////////////////////////////////////////////////// +int main() +{ + std::vector localities = hpx::find_all_localities(); + test_kway_merge(); + test_large_transfers(localities); + test_async_run_collection(hpx::execution::seq(hpx::execution::task)); + test_async_run_collection(hpx::execution::par(hpx::execution::task)); + test_merge_exceptions(hpx::execution::seq, localities); + test_merge_exceptions(hpx::execution::par, localities); + test_merge_exceptions( + hpx::execution::seq(hpx::execution::task), localities); + test_merge_exceptions( + hpx::execution::par(hpx::execution::task), localities); + run_cases(localities); + run_cases(localities); + test_sort_large(localities); + test_sort_throwing(localities); + test_sort_subranges(hpx::execution::seq, localities); + test_sort_subranges(hpx::execution::par, localities); + test_sort_subranges(hpx::execution::seq(hpx::execution::task), localities); + test_sort_subranges(hpx::execution::par(hpx::execution::task), localities); + return hpx::util::report_errors(); +} +#endif