From a0ded2fab4639de34d715874b8e33f308bf1e88e Mon Sep 17 00:00:00 2001 From: Alexander Date: Wed, 29 Sep 2021 14:23:38 -0500 Subject: [PATCH 1/4] init --- cpp/src/arrow/CMakeLists.txt | 1 + cpp/src/arrow/compute/exec/options.h | 15 +++++ cpp/src/arrow/compute/exec/plan_test.cc | 39 ++++++++++++ cpp/src/arrow/compute/exec/select_k.cc | 74 ++++++++++++++++++++++ cpp/src/arrow/compute/exec/select_k.h | 46 ++++++++++++++ cpp/src/arrow/compute/exec/sink_node.cc | 82 +++++++++++++++++++++++++ 6 files changed, 257 insertions(+) create mode 100644 cpp/src/arrow/compute/exec/select_k.cc create mode 100644 cpp/src/arrow/compute/exec/select_k.h diff --git a/cpp/src/arrow/CMakeLists.txt b/cpp/src/arrow/CMakeLists.txt index 5d01376796b6..fe7145110f4f 100644 --- a/cpp/src/arrow/CMakeLists.txt +++ b/cpp/src/arrow/CMakeLists.txt @@ -378,6 +378,7 @@ if(ARROW_COMPUTE) compute/exec/project_node.cc compute/exec/source_node.cc compute/exec/sink_node.cc + compute/exec/select_k.cc compute/function.cc compute/function_internal.cc compute/kernel.cc diff --git a/cpp/src/arrow/compute/exec/options.h b/cpp/src/arrow/compute/exec/options.h index 3dd88210e784..7469635f0373 100644 --- a/cpp/src/arrow/compute/exec/options.h +++ b/cpp/src/arrow/compute/exec/options.h @@ -219,5 +219,20 @@ class ARROW_EXPORT HashJoinNodeOptions : public ExecNodeOptions { std::string output_prefix_for_right; }; +/// \brief Make a node which select top_k/bottom_k rows passed through it +/// +/// All batches pushed to this node will be accumulated, then selected, by the given +/// fields. Then sorted batches will be forwarded to the generator in sorted order. +class ARROW_EXPORT SelectKSinkNodeOptions : public SinkNodeOptions { + public: + explicit SelectKSinkNodeOptions( + SelectKOptions select_k_options, + std::function>()>* generator) + : SinkNodeOptions(generator), select_k_options(std::move(select_k_options)) {} + + /// SelectK options + SelectKOptions select_k_options; +}; + } // namespace compute } // namespace arrow diff --git a/cpp/src/arrow/compute/exec/plan_test.cc b/cpp/src/arrow/compute/exec/plan_test.cc index 8b1c2794bb37..32d5133828f5 100644 --- a/cpp/src/arrow/compute/exec/plan_test.cc +++ b/cpp/src/arrow/compute/exec/plan_test.cc @@ -665,6 +665,45 @@ TEST(ExecPlanExecution, SourceFilterProjectGroupedSumOrderBy) { } } +TEST(ExecPlanExecution, SourceFilterProjectGroupedSumTopK) { + for (bool parallel : {false, true}) { + SCOPED_TRACE(parallel ? "parallel/merged" : "serial"); + + int batch_multiplicity = parallel ? 100 : 1; + auto input = MakeGroupableBatches(/*multiplicity=*/batch_multiplicity); + + ASSERT_OK_AND_ASSIGN(auto plan, ExecPlan::Make()); + AsyncGenerator> sink_gen; + + SelectKOptions options = SelectKOptions::TopKDefault(/*k=*/2, {"str"}); + ASSERT_OK( + Declaration::Sequence( + { + {"source", + SourceNodeOptions{input.schema, input.gen(parallel, /*slow=*/false)}}, + {"filter", + FilterNodeOptions{greater_equal(field_ref("i32"), literal(0))}}, + {"project", ProjectNodeOptions{{ + field_ref("str"), + call("multiply", {field_ref("i32"), literal(2)}), + }}}, + {"aggregate", AggregateNodeOptions{/*aggregates=*/{{"hash_sum", nullptr}}, + /*targets=*/{"multiply(i32, 2)"}, + /*names=*/{"sum(multiply(i32, 2))"}, + /*keys=*/{"str"}}}, + {"filter", FilterNodeOptions{greater(field_ref("sum(multiply(i32, 2))"), + literal(10 * batch_multiplicity))}}, + {"select_k_sink", SelectKSinkNodeOptions{options, &sink_gen}}, + }) + .AddToPlan(plan.get())); + + ASSERT_THAT(StartAndCollect(plan.get(), sink_gen), + Finishes(ResultWith(ElementsAreArray({ExecBatchFromJSON( + {int64(), utf8()}, parallel ? R"([[2000, "beta"], [3600, "alfa"]])" + : R"([[20, "beta"], [36, "alfa"]])")})))); + } +} + TEST(ExecPlanExecution, SourceScalarAggSink) { ASSERT_OK_AND_ASSIGN(auto plan, ExecPlan::Make()); AsyncGenerator> sink_gen; diff --git a/cpp/src/arrow/compute/exec/select_k.cc b/cpp/src/arrow/compute/exec/select_k.cc new file mode 100644 index 000000000000..e8960f290707 --- /dev/null +++ b/cpp/src/arrow/compute/exec/select_k.cc @@ -0,0 +1,74 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "arrow/compute/exec/select_k.h" + +#include +#include +#include +#include +#include "arrow/compute/api_vector.h" +#include "arrow/compute/exec/options.h" +#include "arrow/record_batch.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/table.h" +#include "arrow/type.h" + +namespace arrow { +namespace compute { + +class SelectKBasicImpl : public SelectKImpl { + Status Init(ExecContext* ctx, SelectKOptions select_k_options, + const std::shared_ptr& output_schema) override { + ctx_ = ctx; + select_k_options_ = select_k_options; + output_schema_ = output_schema; + return Status::OK(); + } + Status InputReceived(std::shared_ptr batch) override { + std::unique_lock lock(mutex_); + batches_.push_back(batch); + return Status::OK(); + } + + Result DoFinish() override { + std::unique_lock lock(mutex_); + ARROW_ASSIGN_OR_RAISE(auto table, + Table::FromRecordBatches(output_schema_, std::move(batches_))); + + ARROW_ASSIGN_OR_RAISE(auto indices, SelectKUnstable(table, select_k_options_, ctx_)); + return Take(table, indices, TakeOptions::NoBoundsCheck(), ctx_); + } + + void Abort(bool pos_abort_callback) override {} + + private: + ExecContext* ctx_; + std::shared_ptr output_schema_; + SelectKOptions select_k_options_; + std::mutex mutex_; + std::vector> batches_; +}; + +Result> SelectKImpl::MakeBasic() { + std::unique_ptr impl{new SelectKBasicImpl()}; + return std::move(impl); +} + +} // namespace compute +} // namespace arrow diff --git a/cpp/src/arrow/compute/exec/select_k.h b/cpp/src/arrow/compute/exec/select_k.h new file mode 100644 index 000000000000..c5d6cd455800 --- /dev/null +++ b/cpp/src/arrow/compute/exec/select_k.h @@ -0,0 +1,46 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include +#include + +#include "arrow/compute/exec/options.h" +#include "arrow/record_batch.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/type.h" + +namespace arrow { +namespace compute { + +class SelectKImpl { + public: + virtual ~SelectKImpl() = default; + virtual Status Init(ExecContext* ctx, SelectKOptions select_k_options, + const std::shared_ptr& output_schema) = 0; + virtual Status InputReceived(std::shared_ptr batch) = 0; + virtual Result DoFinish() = 0; + virtual void Abort(bool pos_abort_callback) = 0; + + static Result> MakeBasic(); +}; + +} // namespace compute +} // namespace arrow diff --git a/cpp/src/arrow/compute/exec/sink_node.cc b/cpp/src/arrow/compute/exec/sink_node.cc index b5f3ae4ee600..809aa55caf0c 100644 --- a/cpp/src/arrow/compute/exec/sink_node.cc +++ b/cpp/src/arrow/compute/exec/sink_node.cc @@ -24,6 +24,7 @@ #include "arrow/compute/exec.h" #include "arrow/compute/exec/expression.h" #include "arrow/compute/exec/options.h" +#include "arrow/compute/exec/select_k.h" #include "arrow/compute/exec/util.h" #include "arrow/compute/exec_internal.h" #include "arrow/datum.h" @@ -207,11 +208,92 @@ struct OrderBySinkNode final : public SinkNode { std::vector> batches_; }; +// A sink node that receives inputs and then compute top_k/bottom_k. +struct SelectKSinkNode final : public SinkNode { + SelectKSinkNode(ExecPlan* plan, std::vector inputs, + SelectKOptions select_k_options, std::unique_ptr impl, + AsyncGenerator>* generator) + : SinkNode(plan, std::move(inputs), generator), + select_k_options_(std::move(select_k_options)), + impl_{std::move(impl)} {} + + const char* kind_name() const override { return "SelectKSinkNode"; } + + static Result Make(ExecPlan* plan, std::vector inputs, + const ExecNodeOptions& options) { + RETURN_NOT_OK(ValidateExecNodeInputs(plan, inputs, 1, "SelectKSinkNode")); + + const auto& sink_options = checked_cast(options); + ARROW_ASSIGN_OR_RAISE(std::unique_ptr impl, SelectKImpl::MakeBasic()); + return plan->EmplaceNode(plan, std::move(inputs), + sink_options.select_k_options, + std::move(impl), sink_options.generator); + } + + Status StartProducing() override { + finished_ = Future<>::Make(); + RETURN_NOT_OK(impl_->Init(plan_->exec_context(), select_k_options_, + inputs_[0]->output_schema())); + return Status::OK(); + } + + void InputReceived(ExecNode* input, ExecBatch batch) override { + DCHECK_EQ(input, inputs_[0]); + + auto maybe_batch = batch.ToRecordBatch(inputs_[0]->output_schema(), + plan()->exec_context()->memory_pool()); + if (ErrorIfNotOk(maybe_batch.status())) return; + auto record_batch = maybe_batch.MoveValueUnsafe(); + + Status status = impl_->InputReceived(std::move(record_batch)); + if (!status.ok()) { + StopProducing(); + ErrorIfNotOk(status); + return; + } + if (input_counter_.Increment()) { + Finish(); + } + } + + protected: + Status DoFinish() { + ARROW_ASSIGN_OR_RAISE(Datum sorted, impl_->DoFinish()); + TableBatchReader reader(*sorted.table()); + while (true) { + std::shared_ptr batch; + RETURN_NOT_OK(reader.ReadNext(&batch)); + if (!batch) break; + bool did_push = producer_.Push(ExecBatch(*batch)); + if (!did_push) break; // producer_ was Closed already + } + return Status::OK(); + } + + void Finish() override { + Status st = DoFinish(); + if (ErrorIfNotOk(st)) { + producer_.Push(std::move(st)); + } + SinkNode::Finish(); + } + + protected: + std::string ToStringExtra() const override { + return "by=" + select_k_options_.ToString(); + } + + private: + SelectKOptions select_k_options_; + std::unique_ptr impl_; +}; + } // namespace namespace internal { void RegisterSinkNode(ExecFactoryRegistry* registry) { + DCHECK_OK(registry->AddFactory("select_k_sink", SelectKSinkNode::Make)); DCHECK_OK(registry->AddFactory("order_by_sink", OrderBySinkNode::Make)); DCHECK_OK(registry->AddFactory("sink", SinkNode::Make)); } From ae5beda7fb659b68ec9f30738638171704198536 Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 30 Sep 2021 03:44:13 -0500 Subject: [PATCH 2/4] second --- cpp/src/arrow/CMakeLists.txt | 2 +- cpp/src/arrow/compute/exec/order_by_impl.cc | 105 +++++++++++++++ .../exec/{select_k.h => order_by_impl.h} | 19 ++- cpp/src/arrow/compute/exec/plan_test.cc | 14 +- cpp/src/arrow/compute/exec/select_k.cc | 74 ----------- cpp/src/arrow/compute/exec/sink_node.cc | 124 ++++-------------- 6 files changed, 151 insertions(+), 187 deletions(-) create mode 100644 cpp/src/arrow/compute/exec/order_by_impl.cc rename cpp/src/arrow/compute/exec/{select_k.h => order_by_impl.h} (74%) delete mode 100644 cpp/src/arrow/compute/exec/select_k.cc diff --git a/cpp/src/arrow/CMakeLists.txt b/cpp/src/arrow/CMakeLists.txt index fe7145110f4f..70119df9e464 100644 --- a/cpp/src/arrow/CMakeLists.txt +++ b/cpp/src/arrow/CMakeLists.txt @@ -378,7 +378,7 @@ if(ARROW_COMPUTE) compute/exec/project_node.cc compute/exec/source_node.cc compute/exec/sink_node.cc - compute/exec/select_k.cc + compute/exec/order_by_impl.cc compute/function.cc compute/function_internal.cc compute/kernel.cc diff --git a/cpp/src/arrow/compute/exec/order_by_impl.cc b/cpp/src/arrow/compute/exec/order_by_impl.cc new file mode 100644 index 000000000000..b0642de51472 --- /dev/null +++ b/cpp/src/arrow/compute/exec/order_by_impl.cc @@ -0,0 +1,105 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include "arrow/compute/exec/order_by_impl.h" + +#include +#include +#include +#include +#include "arrow/compute/api_vector.h" +#include "arrow/compute/exec/options.h" +#include "arrow/record_batch.h" +#include "arrow/result.h" +#include "arrow/status.h" +#include "arrow/table.h" +#include "arrow/type.h" +#include "arrow/util/checked_cast.h" + +namespace arrow { +using internal::checked_cast; + +namespace compute { + +class SortBasicImpl : public OrderByImpl { + public: + SortBasicImpl(ExecContext* ctx, const std::shared_ptr& output_schema, + const SortOptions& options = SortOptions{}) + : ctx_(ctx), output_schema_(output_schema), options_(options) {} + + Status InputReceived(std::shared_ptr batch) override { + std::unique_lock lock(mutex_); + batches_.push_back(batch); + return Status::OK(); + } + + virtual Result DoFinish() override { + std::unique_lock lock(mutex_); + ARROW_ASSIGN_OR_RAISE(auto table, + Table::FromRecordBatches(output_schema_, std::move(batches_))); + ARROW_ASSIGN_OR_RAISE(auto indices, SortIndices(table, options_, ctx_)); + return Take(table, indices, TakeOptions::NoBoundsCheck(), ctx_); + } + + virtual std::string ToString() const override { return options_.ToString(); } + + protected: + ExecContext* ctx_; + std::shared_ptr output_schema_; + std::mutex mutex_; + std::vector> batches_; + + private: + const SortOptions options_; +}; // namespace compute + +class SelectKBasicImpl : public SortBasicImpl { + public: + SelectKBasicImpl(ExecContext* ctx, const std::shared_ptr& output_schema, + const SelectKOptions& options) + : SortBasicImpl(ctx, output_schema), options_(options) {} + + Result DoFinish() override { + std::unique_lock lock(mutex_); + ARROW_ASSIGN_OR_RAISE(auto table, + Table::FromRecordBatches(output_schema_, std::move(batches_))); + ARROW_ASSIGN_OR_RAISE(auto indices, SelectKUnstable(table, options_, ctx_)); + return Take(table, indices, TakeOptions::NoBoundsCheck(), ctx_); + } + + virtual std::string ToString() const override { return options_.ToString(); } + + private: + const SelectKOptions options_; +}; + +Result> OrderByImpl::MakeSort( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SortOptions& options) { + std::unique_ptr impl{new SortBasicImpl(ctx, output_schema, options)}; + return std::move(impl); +} + +Result> OrderByImpl::MakeSelectK( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SelectKOptions& options) { + std::unique_ptr impl{new SelectKBasicImpl(ctx, output_schema, options)}; + return std::move(impl); +} + +} // namespace compute +} // namespace arrow diff --git a/cpp/src/arrow/compute/exec/select_k.h b/cpp/src/arrow/compute/exec/order_by_impl.h similarity index 74% rename from cpp/src/arrow/compute/exec/select_k.h rename to cpp/src/arrow/compute/exec/order_by_impl.h index c5d6cd455800..7f24b0870247 100644 --- a/cpp/src/arrow/compute/exec/select_k.h +++ b/cpp/src/arrow/compute/exec/order_by_impl.h @@ -30,16 +30,23 @@ namespace arrow { namespace compute { -class SelectKImpl { +class OrderByImpl { public: - virtual ~SelectKImpl() = default; - virtual Status Init(ExecContext* ctx, SelectKOptions select_k_options, - const std::shared_ptr& output_schema) = 0; + virtual ~OrderByImpl() = default; + virtual Status InputReceived(std::shared_ptr batch) = 0; + virtual Result DoFinish() = 0; - virtual void Abort(bool pos_abort_callback) = 0; - static Result> MakeBasic(); + virtual std::string ToString() const = 0; + + static Result> MakeSort( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SortOptions& options); + + static Result> MakeSelectK( + ExecContext* ctx, const std::shared_ptr& output_schema, + const SelectKOptions& options); }; } // namespace compute diff --git a/cpp/src/arrow/compute/exec/plan_test.cc b/cpp/src/arrow/compute/exec/plan_test.cc index 32d5133828f5..85b657fe118a 100644 --- a/cpp/src/arrow/compute/exec/plan_test.cc +++ b/cpp/src/arrow/compute/exec/plan_test.cc @@ -675,14 +675,12 @@ TEST(ExecPlanExecution, SourceFilterProjectGroupedSumTopK) { ASSERT_OK_AND_ASSIGN(auto plan, ExecPlan::Make()); AsyncGenerator> sink_gen; - SelectKOptions options = SelectKOptions::TopKDefault(/*k=*/2, {"str"}); + SelectKOptions options = SelectKOptions::TopKDefault(/*k=*/1, {"str"}); ASSERT_OK( Declaration::Sequence( { {"source", SourceNodeOptions{input.schema, input.gen(parallel, /*slow=*/false)}}, - {"filter", - FilterNodeOptions{greater_equal(field_ref("i32"), literal(0))}}, {"project", ProjectNodeOptions{{ field_ref("str"), call("multiply", {field_ref("i32"), literal(2)}), @@ -691,16 +689,14 @@ TEST(ExecPlanExecution, SourceFilterProjectGroupedSumTopK) { /*targets=*/{"multiply(i32, 2)"}, /*names=*/{"sum(multiply(i32, 2))"}, /*keys=*/{"str"}}}, - {"filter", FilterNodeOptions{greater(field_ref("sum(multiply(i32, 2))"), - literal(10 * batch_multiplicity))}}, {"select_k_sink", SelectKSinkNodeOptions{options, &sink_gen}}, }) .AddToPlan(plan.get())); - ASSERT_THAT(StartAndCollect(plan.get(), sink_gen), - Finishes(ResultWith(ElementsAreArray({ExecBatchFromJSON( - {int64(), utf8()}, parallel ? R"([[2000, "beta"], [3600, "alfa"]])" - : R"([[20, "beta"], [36, "alfa"]])")})))); + ASSERT_THAT( + StartAndCollect(plan.get(), sink_gen), + Finishes(ResultWith(ElementsAreArray({ExecBatchFromJSON( + {int64(), utf8()}, parallel ? R"([[800, "gama"]])" : R"([[8, "gama"]])")})))); } } diff --git a/cpp/src/arrow/compute/exec/select_k.cc b/cpp/src/arrow/compute/exec/select_k.cc deleted file mode 100644 index e8960f290707..000000000000 --- a/cpp/src/arrow/compute/exec/select_k.cc +++ /dev/null @@ -1,74 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -#include "arrow/compute/exec/select_k.h" - -#include -#include -#include -#include -#include "arrow/compute/api_vector.h" -#include "arrow/compute/exec/options.h" -#include "arrow/record_batch.h" -#include "arrow/result.h" -#include "arrow/status.h" -#include "arrow/table.h" -#include "arrow/type.h" - -namespace arrow { -namespace compute { - -class SelectKBasicImpl : public SelectKImpl { - Status Init(ExecContext* ctx, SelectKOptions select_k_options, - const std::shared_ptr& output_schema) override { - ctx_ = ctx; - select_k_options_ = select_k_options; - output_schema_ = output_schema; - return Status::OK(); - } - Status InputReceived(std::shared_ptr batch) override { - std::unique_lock lock(mutex_); - batches_.push_back(batch); - return Status::OK(); - } - - Result DoFinish() override { - std::unique_lock lock(mutex_); - ARROW_ASSIGN_OR_RAISE(auto table, - Table::FromRecordBatches(output_schema_, std::move(batches_))); - - ARROW_ASSIGN_OR_RAISE(auto indices, SelectKUnstable(table, select_k_options_, ctx_)); - return Take(table, indices, TakeOptions::NoBoundsCheck(), ctx_); - } - - void Abort(bool pos_abort_callback) override {} - - private: - ExecContext* ctx_; - std::shared_ptr output_schema_; - SelectKOptions select_k_options_; - std::mutex mutex_; - std::vector> batches_; -}; - -Result> SelectKImpl::MakeBasic() { - std::unique_ptr impl{new SelectKBasicImpl()}; - return std::move(impl); -} - -} // namespace compute -} // namespace arrow diff --git a/cpp/src/arrow/compute/exec/sink_node.cc b/cpp/src/arrow/compute/exec/sink_node.cc index 809aa55caf0c..9cac339ebfc0 100644 --- a/cpp/src/arrow/compute/exec/sink_node.cc +++ b/cpp/src/arrow/compute/exec/sink_node.cc @@ -24,7 +24,7 @@ #include "arrow/compute/exec.h" #include "arrow/compute/exec/expression.h" #include "arrow/compute/exec/options.h" -#include "arrow/compute/exec/select_k.h" +#include "arrow/compute/exec/order_by_impl.h" #include "arrow/compute/exec/util.h" #include "arrow/compute/exec_internal.h" #include "arrow/datum.h" @@ -132,109 +132,40 @@ class SinkNode : public ExecNode { PushGenerator>::Producer producer_; }; -// A sink node that accumulates inputs, then sorts them before emitting them. struct OrderBySinkNode final : public SinkNode { - OrderBySinkNode(ExecPlan* plan, std::vector inputs, SortOptions sort_options, + OrderBySinkNode(ExecPlan* plan, std::vector inputs, + std::unique_ptr impl, AsyncGenerator>* generator) - : SinkNode(plan, std::move(inputs), generator), - sort_options_(std::move(sort_options)) {} + : SinkNode(plan, std::move(inputs), generator), impl_{std::move(impl)} {} const char* kind_name() const override { return "OrderBySinkNode"; } - static Result Make(ExecPlan* plan, std::vector inputs, - const ExecNodeOptions& options) { + // A sink node that accumulates inputs, then sorts them before emitting them. + static Result MakeSort(ExecPlan* plan, std::vector inputs, + const ExecNodeOptions& options) { RETURN_NOT_OK(ValidateExecNodeInputs(plan, inputs, 1, "OrderBySinkNode")); const auto& sink_options = checked_cast(options); - return plan->EmplaceNode( - plan, std::move(inputs), sink_options.sort_options, sink_options.generator); - } - - void InputReceived(ExecNode* input, ExecBatch batch) override { - DCHECK_EQ(input, inputs_[0]); - - // Accumulate data - { - std::unique_lock lock(mutex_); - auto maybe_batch = batch.ToRecordBatch(inputs_[0]->output_schema(), - plan()->exec_context()->memory_pool()); - if (ErrorIfNotOk(maybe_batch.status())) return; - batches_.push_back(maybe_batch.MoveValueUnsafe()); - } - - if (input_counter_.Increment()) { - Finish(); - } - } - - protected: - Status DoFinish() { - Datum sorted; - { - std::unique_lock lock(mutex_); - ARROW_ASSIGN_OR_RAISE( - auto table, - Table::FromRecordBatches(inputs_[0]->output_schema(), std::move(batches_))); - ARROW_ASSIGN_OR_RAISE(auto indices, - SortIndices(table, sort_options_, plan()->exec_context())); - ARROW_ASSIGN_OR_RAISE(sorted, Take(table, indices, TakeOptions::NoBoundsCheck(), - plan()->exec_context())); - } - TableBatchReader reader(*sorted.table()); - while (true) { - std::shared_ptr batch; - RETURN_NOT_OK(reader.ReadNext(&batch)); - if (!batch) break; - bool did_push = producer_.Push(ExecBatch(*batch)); - if (!did_push) break; // producer_ was Closed already - } - return Status::OK(); + ARROW_ASSIGN_OR_RAISE( + std::unique_ptr impl, + OrderByImpl::MakeSort(plan->exec_context(), inputs[0]->output_schema(), + sink_options.sort_options)); + return plan->EmplaceNode(plan, std::move(inputs), std::move(impl), + sink_options.generator); } - void Finish() override { - Status st = DoFinish(); - if (ErrorIfNotOk(st)) { - producer_.Push(std::move(st)); - } - SinkNode::Finish(); - } - - protected: - std::string ToStringExtra() const override { return "by=" + sort_options_.ToString(); } - - private: - SortOptions sort_options_; - std::mutex mutex_; - std::vector> batches_; -}; - -// A sink node that receives inputs and then compute top_k/bottom_k. -struct SelectKSinkNode final : public SinkNode { - SelectKSinkNode(ExecPlan* plan, std::vector inputs, - SelectKOptions select_k_options, std::unique_ptr impl, - AsyncGenerator>* generator) - : SinkNode(plan, std::move(inputs), generator), - select_k_options_(std::move(select_k_options)), - impl_{std::move(impl)} {} - - const char* kind_name() const override { return "SelectKSinkNode"; } - - static Result Make(ExecPlan* plan, std::vector inputs, - const ExecNodeOptions& options) { - RETURN_NOT_OK(ValidateExecNodeInputs(plan, inputs, 1, "SelectKSinkNode")); + // A sink node that receives inputs and then compute top_k/bottom_k. + static Result MakeSelectK(ExecPlan* plan, std::vector inputs, + const ExecNodeOptions& options) { + RETURN_NOT_OK(ValidateExecNodeInputs(plan, inputs, 1, "OrderBySinkNode")); const auto& sink_options = checked_cast(options); - ARROW_ASSIGN_OR_RAISE(std::unique_ptr impl, SelectKImpl::MakeBasic()); - return plan->EmplaceNode(plan, std::move(inputs), - sink_options.select_k_options, - std::move(impl), sink_options.generator); - } - - Status StartProducing() override { - finished_ = Future<>::Make(); - RETURN_NOT_OK(impl_->Init(plan_->exec_context(), select_k_options_, - inputs_[0]->output_schema())); - return Status::OK(); + ARROW_ASSIGN_OR_RAISE( + std::unique_ptr impl, + OrderByImpl::MakeSelectK(plan->exec_context(), inputs[0]->output_schema(), + sink_options.select_k_options)); + return plan->EmplaceNode(plan, std::move(inputs), std::move(impl), + sink_options.generator); } void InputReceived(ExecNode* input, ExecBatch batch) override { @@ -280,12 +211,11 @@ struct SelectKSinkNode final : public SinkNode { protected: std::string ToStringExtra() const override { - return "by=" + select_k_options_.ToString(); + return std::string("by=") + impl_->ToString(); } private: - SelectKOptions select_k_options_; - std::unique_ptr impl_; + std::unique_ptr impl_; }; } // namespace @@ -293,8 +223,8 @@ struct SelectKSinkNode final : public SinkNode { namespace internal { void RegisterSinkNode(ExecFactoryRegistry* registry) { - DCHECK_OK(registry->AddFactory("select_k_sink", SelectKSinkNode::Make)); - DCHECK_OK(registry->AddFactory("order_by_sink", OrderBySinkNode::Make)); + DCHECK_OK(registry->AddFactory("select_k_sink", OrderBySinkNode::MakeSelectK)); + DCHECK_OK(registry->AddFactory("order_by_sink", OrderBySinkNode::MakeSort)); DCHECK_OK(registry->AddFactory("sink", SinkNode::Make)); } From fe81c405cf8ecd04be8dfc52c0fa7afeca39dd0b Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 30 Sep 2021 11:05:35 -0500 Subject: [PATCH 3/4] minor change --- cpp/src/arrow/compute/exec/order_by_impl.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cpp/src/arrow/compute/exec/order_by_impl.cc b/cpp/src/arrow/compute/exec/order_by_impl.cc index b0642de51472..fecbd914c549 100644 --- a/cpp/src/arrow/compute/exec/order_by_impl.cc +++ b/cpp/src/arrow/compute/exec/order_by_impl.cc @@ -47,7 +47,7 @@ class SortBasicImpl : public OrderByImpl { return Status::OK(); } - virtual Result DoFinish() override { + Result DoFinish() override { std::unique_lock lock(mutex_); ARROW_ASSIGN_OR_RAISE(auto table, Table::FromRecordBatches(output_schema_, std::move(batches_))); @@ -55,7 +55,7 @@ class SortBasicImpl : public OrderByImpl { return Take(table, indices, TakeOptions::NoBoundsCheck(), ctx_); } - virtual std::string ToString() const override { return options_.ToString(); } + std::string ToString() const override { return options_.ToString(); } protected: ExecContext* ctx_; @@ -81,7 +81,7 @@ class SelectKBasicImpl : public SortBasicImpl { return Take(table, indices, TakeOptions::NoBoundsCheck(), ctx_); } - virtual std::string ToString() const override { return options_.ToString(); } + std::string ToString() const override { return options_.ToString(); } private: const SelectKOptions options_; From ee955b2e0887c24d0cd1f10a95e2f6483f656886 Mon Sep 17 00:00:00 2001 From: Alexander Date: Thu, 30 Sep 2021 13:24:44 -0500 Subject: [PATCH 4/4] addressing feedback --- cpp/src/arrow/compute/exec/order_by_impl.cc | 3 +-- cpp/src/arrow/compute/exec/order_by_impl.h | 2 +- cpp/src/arrow/compute/exec/sink_node.cc | 13 +++++++------ 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cpp/src/arrow/compute/exec/order_by_impl.cc b/cpp/src/arrow/compute/exec/order_by_impl.cc index fecbd914c549..4afcf884f53a 100644 --- a/cpp/src/arrow/compute/exec/order_by_impl.cc +++ b/cpp/src/arrow/compute/exec/order_by_impl.cc @@ -41,10 +41,9 @@ class SortBasicImpl : public OrderByImpl { const SortOptions& options = SortOptions{}) : ctx_(ctx), output_schema_(output_schema), options_(options) {} - Status InputReceived(std::shared_ptr batch) override { + void InputReceived(const std::shared_ptr& batch) override { std::unique_lock lock(mutex_); batches_.push_back(batch); - return Status::OK(); } Result DoFinish() override { diff --git a/cpp/src/arrow/compute/exec/order_by_impl.h b/cpp/src/arrow/compute/exec/order_by_impl.h index 7f24b0870247..afc92aeddb2c 100644 --- a/cpp/src/arrow/compute/exec/order_by_impl.h +++ b/cpp/src/arrow/compute/exec/order_by_impl.h @@ -34,7 +34,7 @@ class OrderByImpl { public: virtual ~OrderByImpl() = default; - virtual Status InputReceived(std::shared_ptr batch) = 0; + virtual void InputReceived(const std::shared_ptr& batch) = 0; virtual Result DoFinish() = 0; diff --git a/cpp/src/arrow/compute/exec/sink_node.cc b/cpp/src/arrow/compute/exec/sink_node.cc index 9cac339ebfc0..76889c244d7a 100644 --- a/cpp/src/arrow/compute/exec/sink_node.cc +++ b/cpp/src/arrow/compute/exec/sink_node.cc @@ -173,15 +173,16 @@ struct OrderBySinkNode final : public SinkNode { auto maybe_batch = batch.ToRecordBatch(inputs_[0]->output_schema(), plan()->exec_context()->memory_pool()); - if (ErrorIfNotOk(maybe_batch.status())) return; - auto record_batch = maybe_batch.MoveValueUnsafe(); - - Status status = impl_->InputReceived(std::move(record_batch)); - if (!status.ok()) { + if (ErrorIfNotOk(maybe_batch.status())) { StopProducing(); - ErrorIfNotOk(status); + bool cancelled = input_counter_.Cancel(); + DCHECK(cancelled); + finished_.MarkFinished(maybe_batch.status()); return; } + auto record_batch = maybe_batch.MoveValueUnsafe(); + + impl_->InputReceived(std::move(record_batch)); if (input_counter_.Increment()) { Finish(); }