rok commented on code in PR #55665:
URL: https://github.com/apache/arrow/pull/55665#discussion_r4660801320


##########
cpp/src/arrow/dataset/dataset.cc:
##########
@@ -321,6 +323,202 @@ Result<FragmentIterator> 
UnionDataset::GetFragmentsImpl(compute::Expression pred
   return GetFragmentsFromDatasets(children_, predicate);
 }
 
+FilteredFragment::FilteredFragment(std::shared_ptr<Fragment> fragment,
+                                   compute::Expression filter)
+    : Fragment(fragment->partition_expression(), /*physical_schema=*/nullptr),
+      fragment_(std::move(fragment)),
+      filter_(std::move(filter)) {}
+
+Result<std::shared_ptr<Schema>> FilteredFragment::ReadPhysicalSchemaImpl() {
+  return fragment_->ReadPhysicalSchema();
+}
+
+Status FilteredFragment::ClearCachedMetadata() {
+  RETURN_NOT_OK(Fragment::ClearCachedMetadata());
+  return fragment_->ClearCachedMetadata();
+}
+
+std::string FilteredFragment::ToString() const {
+  // The scanner uses ToString() for the __filename augmented field, so this 
must
+  // match the wrapped fragment.
+  return fragment_->ToString();
+}
+
+namespace {
+
+// Bind a FilteredFragment's filter to the dataset schema of the scan options.
+// FilteredFragment can be constructed and scanned directly, so validate the 
inputs.
+Result<compute::Expression> BindFragmentFilter(const compute::Expression& 
filter,
+                                               const ScanOptions& options) {
+  if (options.dataset_schema == nullptr) {
+    return Status::Invalid("Scanning a FilteredFragment requires a dataset 
schema");
+  }
+  ARROW_ASSIGN_OR_RAISE(auto bound, filter.Bind(*options.dataset_schema));

Review Comment:
   :robot: Non-blocking nit: Since `FilteredFragment` can be constructed 
directly, we might want to guard `!filter.is_valid()` here (matching 
`FilteredDataset::Make`) so a default-constructed `Expression` returns 
`Status::Invalid` rather than hitting a null dereference in `Bind()`.



##########
cpp/src/arrow/dataset/dataset.cc:
##########
@@ -321,6 +323,202 @@ Result<FragmentIterator> 
UnionDataset::GetFragmentsImpl(compute::Expression pred
   return GetFragmentsFromDatasets(children_, predicate);
 }
 
+FilteredFragment::FilteredFragment(std::shared_ptr<Fragment> fragment,
+                                   compute::Expression filter)
+    : Fragment(fragment->partition_expression(), /*physical_schema=*/nullptr),
+      fragment_(std::move(fragment)),
+      filter_(std::move(filter)) {}
+
+Result<std::shared_ptr<Schema>> FilteredFragment::ReadPhysicalSchemaImpl() {
+  return fragment_->ReadPhysicalSchema();
+}
+
+Status FilteredFragment::ClearCachedMetadata() {
+  RETURN_NOT_OK(Fragment::ClearCachedMetadata());
+  return fragment_->ClearCachedMetadata();
+}
+
+std::string FilteredFragment::ToString() const {
+  // The scanner uses ToString() for the __filename augmented field, so this 
must
+  // match the wrapped fragment.
+  return fragment_->ToString();
+}
+
+namespace {
+
+// Bind a FilteredFragment's filter to the dataset schema of the scan options.
+// FilteredFragment can be constructed and scanned directly, so validate the 
inputs.
+Result<compute::Expression> BindFragmentFilter(const compute::Expression& 
filter,
+                                               const ScanOptions& options) {
+  if (options.dataset_schema == nullptr) {
+    return Status::Invalid("Scanning a FilteredFragment requires a dataset 
schema");
+  }
+  ARROW_ASSIGN_OR_RAISE(auto bound, filter.Bind(*options.dataset_schema));
+  if (!bound.type()->Equals(*boolean())) {
+    return Status::TypeError("FilteredFragment filter must be boolean, got ",
+                             *bound.type());
+  }
+  return bound;
+}
+
+}  // namespace
+
+Result<RecordBatchGenerator> FilteredFragment::ScanBatchesAsync(
+    const std::shared_ptr<ScanOptions>& options) {
+  const auto& dataset_schema = options->dataset_schema;
+  ARROW_ASSIGN_OR_RAISE(auto filter, BindFragmentFilter(filter_, *options));
+  ARROW_ASSIGN_OR_RAISE(filter,
+                        SimplifyWithGuarantee(std::move(filter), 
partition_expression_));
+  if (!filter.IsSatisfiable()) {
+    return MakeEmptyGenerator<std::shared_ptr<RecordBatch>>();
+  }
+
+  // The filter might simplify to true if it only references partition fields,
+  // in which case the wrapped fragment can be scanned unchanged.
+  if (filter == compute::literal(true)) {
+    return fragment_->ScanBatchesAsync(options);
+  }
+
+  // Combine any existing filter in the scan options with the fragment's 
filter,
+  // so the wrapped fragment can skip data that cannot match.
+  auto fragment_options = std::make_shared<ScanOptions>(*options);
+  ARROW_ASSIGN_OR_RAISE(fragment_options->filter,
+                        compute::and_(options->filter, 
filter).Bind(*dataset_schema));
+  ARROW_ASSIGN_OR_RAISE(auto batches, 
fragment_->ScanBatchesAsync(fragment_options));
+
+  // Apply the fragment's filter to scanned rows.
+  // The filter in the scan options is only used for data pruning at this point
+  // and will be used to filter rows later, so don't duplicate that work.
+  auto guarantee = partition_expression_;
+  auto pool = options->pool;
+  return MakeMappedGenerator(
+      std::move(batches),
+      [filter, dataset_schema, guarantee, pool](const 
std::shared_ptr<RecordBatch>& batch)
+          -> Result<std::shared_ptr<RecordBatch>> {
+        compute::ExecContext exec_context(pool);
+        ARROW_ASSIGN_OR_RAISE(auto exec_batch,
+                              compute::MakeExecBatch(*dataset_schema, batch, 
guarantee));
+        ARROW_ASSIGN_OR_RAISE(Datum mask, compute::ExecuteScalarExpression(
+                                              filter, exec_batch, 
&exec_context));
+        if (mask.is_scalar()) {
+          const auto& selected = mask.scalar_as<BooleanScalar>();
+          return selected.is_valid && selected.value ? batch : batch->Slice(0, 
0);
+        }
+        ARROW_ASSIGN_OR_RAISE(
+            Datum filtered,
+            compute::Filter(batch, mask, compute::FilterOptions::Defaults(),
+                            &exec_context));
+        return filtered.record_batch();
+      });
+}
+
+Future<std::optional<int64_t>> FilteredFragment::CountRows(
+    compute::Expression predicate, const std::shared_ptr<ScanOptions>& 
options) {
+  ARROW_ASSIGN_OR_RAISE(auto filter, BindFragmentFilter(filter_, *options));
+  ARROW_ASSIGN_OR_RAISE(
+      auto combined,
+      compute::and_(std::move(predicate), 
filter).Bind(*options->dataset_schema));
+  // Simplify so the wrapped fragment can count from metadata where possible,
+  // matching FileFragment::CountRows.
+  ARROW_ASSIGN_OR_RAISE(combined, 
compute::SimplifyWithGuarantee(std::move(combined),
+                                                                 
partition_expression_));
+  if (!combined.IsSatisfiable()) {
+    return Future<std::optional<int64_t>>::MakeFinished(0);
+  }
+  return fragment_->CountRows(std::move(combined), options);
+}
+
+FilteredDataset::FilteredDataset(std::shared_ptr<Dataset> child,
+                                 compute::Expression filter)
+    : Dataset(child->schema(), child->partition_expression()),
+      child_(std::move(child)),
+      filter_(std::move(filter)) {}
+
+namespace {
+
+// Replace positional field references with references by name, so the 
expression
+// refers to the same fields if the schema is replaced with one that reorders 
them.
+Result<compute::Expression> FieldRefsToNames(compute::Expression expr,
+                                             const Schema& schema) {
+  return compute::ModifyExpression(
+      std::move(expr),
+      [&schema](compute::Expression e) -> Result<compute::Expression> {
+        const FieldRef* ref = e.field_ref();
+        if (ref == nullptr || ref->IsNameSequence()) {
+          return e;
+        }
+        ARROW_ASSIGN_OR_RAISE(auto path, ref->FindOne(schema));
+        std::vector<FieldRef> names;
+        const FieldVector* fields = &schema.fields();
+        for (int index : path.indices()) {
+          const auto& field = (*fields)[index];
+          names.emplace_back(field->name());
+          fields = &field->type()->fields();
+        }
+        FieldRef by_name(std::move(names));
+        // Fails if a name is ambiguous, e.g. due to duplicate field names
+        RETURN_NOT_OK(by_name.FindOne(schema));
+        return compute::field_ref(std::move(by_name));

Review Comment:
   :robot: Non-blocking nit: If a C++ caller passes an already-bound 
`Expression` with a positional `FieldRef` to `FilteredDataset::Make`, replacing 
only the leaf with an unbound `field_ref` leaves enclosing `Call` nodes with 
their old kernel/type metadata until re-bound. It still works in practice since 
`IsBound()` becomes false and `Bind()` re-binds the full tree, so this is just 
a defensive note in case we want the stored expression to stay consistently 
unbound.



##########
cpp/src/arrow/dataset/dataset.cc:
##########
@@ -321,6 +323,202 @@ Result<FragmentIterator> 
UnionDataset::GetFragmentsImpl(compute::Expression pred
   return GetFragmentsFromDatasets(children_, predicate);
 }
 
+FilteredFragment::FilteredFragment(std::shared_ptr<Fragment> fragment,
+                                   compute::Expression filter)
+    : Fragment(fragment->partition_expression(), /*physical_schema=*/nullptr),
+      fragment_(std::move(fragment)),
+      filter_(std::move(filter)) {}
+
+Result<std::shared_ptr<Schema>> FilteredFragment::ReadPhysicalSchemaImpl() {
+  return fragment_->ReadPhysicalSchema();
+}
+
+Status FilteredFragment::ClearCachedMetadata() {
+  RETURN_NOT_OK(Fragment::ClearCachedMetadata());
+  return fragment_->ClearCachedMetadata();
+}
+
+std::string FilteredFragment::ToString() const {
+  // The scanner uses ToString() for the __filename augmented field, so this 
must
+  // match the wrapped fragment.
+  return fragment_->ToString();
+}
+
+namespace {
+
+// Bind a FilteredFragment's filter to the dataset schema of the scan options.
+// FilteredFragment can be constructed and scanned directly, so validate the 
inputs.
+Result<compute::Expression> BindFragmentFilter(const compute::Expression& 
filter,
+                                               const ScanOptions& options) {
+  if (options.dataset_schema == nullptr) {
+    return Status::Invalid("Scanning a FilteredFragment requires a dataset 
schema");
+  }
+  ARROW_ASSIGN_OR_RAISE(auto bound, filter.Bind(*options.dataset_schema));
+  if (!bound.type()->Equals(*boolean())) {
+    return Status::TypeError("FilteredFragment filter must be boolean, got ",
+                             *bound.type());
+  }
+  return bound;
+}
+
+}  // namespace
+
+Result<RecordBatchGenerator> FilteredFragment::ScanBatchesAsync(
+    const std::shared_ptr<ScanOptions>& options) {
+  const auto& dataset_schema = options->dataset_schema;
+  ARROW_ASSIGN_OR_RAISE(auto filter, BindFragmentFilter(filter_, *options));
+  ARROW_ASSIGN_OR_RAISE(filter,
+                        SimplifyWithGuarantee(std::move(filter), 
partition_expression_));
+  if (!filter.IsSatisfiable()) {
+    return MakeEmptyGenerator<std::shared_ptr<RecordBatch>>();
+  }
+
+  // The filter might simplify to true if it only references partition fields,
+  // in which case the wrapped fragment can be scanned unchanged.
+  if (filter == compute::literal(true)) {
+    return fragment_->ScanBatchesAsync(options);
+  }
+
+  // Combine any existing filter in the scan options with the fragment's 
filter,
+  // so the wrapped fragment can skip data that cannot match.
+  auto fragment_options = std::make_shared<ScanOptions>(*options);
+  ARROW_ASSIGN_OR_RAISE(fragment_options->filter,
+                        compute::and_(options->filter, 
filter).Bind(*dataset_schema));
+  ARROW_ASSIGN_OR_RAISE(auto batches, 
fragment_->ScanBatchesAsync(fragment_options));
+
+  // Apply the fragment's filter to scanned rows.
+  // The filter in the scan options is only used for data pruning at this point
+  // and will be used to filter rows later, so don't duplicate that work.
+  auto guarantee = partition_expression_;
+  auto pool = options->pool;
+  return MakeMappedGenerator(
+      std::move(batches),
+      [filter, dataset_schema, guarantee, pool](const 
std::shared_ptr<RecordBatch>& batch)
+          -> Result<std::shared_ptr<RecordBatch>> {
+        compute::ExecContext exec_context(pool);
+        ARROW_ASSIGN_OR_RAISE(auto exec_batch,
+                              compute::MakeExecBatch(*dataset_schema, batch, 
guarantee));
+        ARROW_ASSIGN_OR_RAISE(Datum mask, compute::ExecuteScalarExpression(
+                                              filter, exec_batch, 
&exec_context));
+        if (mask.is_scalar()) {
+          const auto& selected = mask.scalar_as<BooleanScalar>();
+          return selected.is_valid && selected.value ? batch : batch->Slice(0, 
0);
+        }
+        ARROW_ASSIGN_OR_RAISE(
+            Datum filtered,
+            compute::Filter(batch, mask, compute::FilterOptions::Defaults(),
+                            &exec_context));
+        return filtered.record_batch();
+      });
+}
+
+Future<std::optional<int64_t>> FilteredFragment::CountRows(
+    compute::Expression predicate, const std::shared_ptr<ScanOptions>& 
options) {
+  ARROW_ASSIGN_OR_RAISE(auto filter, BindFragmentFilter(filter_, *options));
+  ARROW_ASSIGN_OR_RAISE(
+      auto combined,
+      compute::and_(std::move(predicate), 
filter).Bind(*options->dataset_schema));
+  // Simplify so the wrapped fragment can count from metadata where possible,
+  // matching FileFragment::CountRows.
+  ARROW_ASSIGN_OR_RAISE(combined, 
compute::SimplifyWithGuarantee(std::move(combined),
+                                                                 
partition_expression_));
+  if (!combined.IsSatisfiable()) {
+    return Future<std::optional<int64_t>>::MakeFinished(0);
+  }
+  return fragment_->CountRows(std::move(combined), options);
+}
+
+FilteredDataset::FilteredDataset(std::shared_ptr<Dataset> child,
+                                 compute::Expression filter)
+    : Dataset(child->schema(), child->partition_expression()),
+      child_(std::move(child)),
+      filter_(std::move(filter)) {}
+
+namespace {
+
+// Replace positional field references with references by name, so the 
expression
+// refers to the same fields if the schema is replaced with one that reorders 
them.
+Result<compute::Expression> FieldRefsToNames(compute::Expression expr,
+                                             const Schema& schema) {
+  return compute::ModifyExpression(
+      std::move(expr),
+      [&schema](compute::Expression e) -> Result<compute::Expression> {
+        const FieldRef* ref = e.field_ref();
+        if (ref == nullptr || ref->IsNameSequence()) {
+          return e;
+        }
+        ARROW_ASSIGN_OR_RAISE(auto path, ref->FindOne(schema));
+        std::vector<FieldRef> names;
+        const FieldVector* fields = &schema.fields();
+        for (int index : path.indices()) {
+          const auto& field = (*fields)[index];
+          names.emplace_back(field->name());
+          fields = &field->type()->fields();
+        }
+        FieldRef by_name(std::move(names));
+        // Fails if a name is ambiguous, e.g. due to duplicate field names
+        RETURN_NOT_OK(by_name.FindOne(schema));
+        return compute::field_ref(std::move(by_name));
+      },
+      [](compute::Expression e, compute::Expression*) { return e; });
+}
+
+}  // namespace
+
+Result<std::shared_ptr<FilteredDataset>> FilteredDataset::Make(
+    std::shared_ptr<Dataset> child, compute::Expression filter) {
+  if (child == nullptr) {
+    return Status::Invalid("FilteredDataset child must not be null");
+  }
+  if (!filter.is_valid()) {
+    return Status::Invalid("FilteredDataset filter must be a valid 
expression");
+  }
+  // Verify the filter produces a bool
+  ARROW_ASSIGN_OR_RAISE(auto bound, filter.Bind(*child->schema()));
+  if (!bound.type()->Equals(*boolean())) {
+    return Status::TypeError("FilteredDataset filter must be boolean, got ",
+                             *bound.type());
+  }
+  // Store the unbound filter so it can be bound on-demand on the unified 
schema of a
+  // UnionDataset, with fields referenced by name so the filter refers to the 
same
+  // fields if they are reordered.
+  ARROW_ASSIGN_OR_RAISE(filter, FieldRefsToNames(std::move(filter), 
*child->schema()));
+  return std::shared_ptr<FilteredDataset>(
+      new FilteredDataset(std::move(child), std::move(filter)));
+}
+
+Result<std::shared_ptr<Dataset>> FilteredDataset::ReplaceSchema(
+    std::shared_ptr<Schema> schema) const {
+  ARROW_ASSIGN_OR_RAISE(auto child, child_->ReplaceSchema(std::move(schema)));
+  ARROW_ASSIGN_OR_RAISE(auto filtered, Make(std::move(child), filter_));
+  return std::static_pointer_cast<Dataset>(std::move(filtered));
+}
+
+Result<FragmentIterator> FilteredDataset::GetFragmentsImpl(
+    compute::Expression predicate) {
+  // Compute a combined predicate that can be used for predicate-pushdown to 
select
+  // fragments from the child Dataset.
+  ARROW_ASSIGN_OR_RAISE(auto combined_predicate,
+                        compute::and_(std::move(predicate), 
filter_).Bind(*schema_));
+  ARROW_ASSIGN_OR_RAISE(auto fragments,
+                        child_->GetFragments(std::move(combined_predicate)));
+
+  // Convert the child's fragments to FilteredFragments that apply the 
additional filter.
+  // The filter is simplified using each fragment's partition expression, 
which removes
+  // references to partition fields, so a fragment can also be scanned with 
only its
+  // physical schema.
+  ARROW_ASSIGN_OR_RAISE(auto filter, filter_.Bind(*schema_));
+  return MakeMaybeMapIterator(
+      [filter](std::shared_ptr<Fragment> fragment) -> 
Result<std::shared_ptr<Fragment>> {
+        ARROW_ASSIGN_OR_RAISE(
+            auto fragment_filter,
+            compute::SimplifyWithGuarantee(filter, 
fragment->partition_expression()));
+        return std::make_shared<FilteredFragment>(std::move(fragment),
+                                                  std::move(fragment_filter));

Review Comment:
   :robot: Non-blocking question: When `fragment_filter` simplifies to 
`literal(true)` (e.g. a partition-only filter), is wrapping in 
`FilteredFragment` intentional to keep `type_name()` uniform, or would 
returning the underlying fragment directly be preferable so callers retain 
`FileFragment`/`ParquetFileFragment` attributes in Python? Fine either way 
since `ScanBatchesAsync` already short-circuits.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to