Copilot commented on code in PR #12278:
URL: https://github.com/apache/gluten/pull/12278#discussion_r3410396616


##########
backends-velox/src-delta40/main/scala/org/apache/spark/sql/delta/stats/GlutenDeltaJobStatsTracker.scala:
##########
@@ -99,6 +110,48 @@ object GlutenDeltaJobStatsTracker extends Logging {
       new GlutenDeltaJobStatsFallbackTracker(tracker)
   }
 
+  /**
+   * Returns whether the Delta per-file statistics aggregation can be 
offloaded to a Velox
+   * whole-stage transformer. This mirrors the plan that 
[[GlutenDeltaTaskStatsTracker]] builds on
+   * the executors: if the aggregation/projection is not supported by Velox it 
stays a vanilla
+   * [[ProjectExec]] (i.e. does not collapse into a 
[[WholeStageTransformer]]), in which case the
+   * native stats tracker must not be used. Evaluated once on the driver so 
the executors never
+   * allocate native resources for a plan that cannot run.
+   */
+  private def canOffloadStats(dataCols: Seq[Attribute], statsColExpr: 
Expression): Boolean = {
+    try {
+      val aggregates = statsColExpr.collect {
+        case ae: AggregateExpression if 
ae.aggregateFunction.isInstanceOf[DeclarativeAggregate] =>
+          ae
+      }

Review Comment:
   canOffloadStats() only collects DeclarativeAggregate AggregateExpressions 
and silently ignores any other AggregateExpression(s). If statsColExpr contains 
a non-declarative aggregate (or other aggregate forms you can’t offload), this 
method may still return true and select the native tracker, recreating the 
ClassCastException/crash scenario you’re trying to avoid. Consider collecting 
all AggregateExpression nodes first, and returning false if any 
aggregateFunction is not a DeclarativeAggregate (and/or if there are any 
aggregates you explicitly can’t offload such as distinct/filtered aggregates, 
depending on your validator behavior).



##########
cpp/velox/substrait/SubstraitToVeloxExpr.cc:
##########
@@ -217,13 +217,29 @@ std::shared_ptr<const core::FieldAccessTypedExpr> 
SubstraitVeloxExprConverter::t
       auto inputColumnType = inputType;
       for (;;) {
         auto idx = tmp->field();
-        fieldAccess = makeFieldAccessExpr(inputColumnType->nameOf(idx), 
inputColumnType->childAt(idx), fieldAccess);
+        VELOX_USER_CHECK(
+            idx >= 0 && static_cast<uint32_t>(idx) < inputColumnType->size(),
+            "Field reference index {} is out of range for the {}-field row 
type.",
+            idx,
+            inputColumnType->size());
+        const TypePtr childType = inputColumnType->childAt(idx);
+        fieldAccess = makeFieldAccessExpr(inputColumnType->nameOf(idx), 
childType, fieldAccess);
 
         if (!tmp->has_child()) {
           break;
         }
 
-        inputColumnType = asRowType(inputColumnType->childAt(idx));
+        // Descending into a nested field is only valid when the current child 
is
+        // itself a struct/row. For array/map/primitive children (e.g. a field
+        // nested under an array, as in Delta's "updating array type" case)
+        // asRowType() returns null; previously the next loop iteration
+        // dereferenced that null RowType and crashed the process with a 
SIGSEGV.
+        // Throw a user error instead so plan validation fails cleanly and the
+        // query falls back to vanilla execution.
+        inputColumnType = asRowType(childType);
+        VELOX_USER_CHECK_NOT_NULL(
+            inputColumnType,
+            "Nested field reference into a non-struct type (e.g. an array or 
map element) is not supported.");

Review Comment:
   This new error avoids a crash, but the message is missing the key debugging 
context (which field/index and what the actual child type was). Consider 
including at least the offending index (idx), the referenced field name, and 
the child type’s kind/name (e.g., array/map/primitive) so users can identify 
which column/path caused the failure.



##########
.github/workflows/delta_spark_ut.yml:
##########
@@ -0,0 +1,572 @@
+# 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.
+
+# Runs Delta Lake's `spark` sbt module unit tests against a Gluten Velox bundle
+# that is built from the source in this repository. The pipeline:
+#
+#   1. Builds the Velox/Gluten native libraries (centos-7 + vcpkg, x86_64).
+#   2. Builds the Gluten Java/Scala jars and assembles the
+#      `gluten-velox-bundle-spark<spark>_<scala>-linux_amd64-<version>.jar`
+#      fat jar for Spark 4.1 + Scala 2.13 + Java 17 with the Delta profile.
+#   3. Clones delta-io/delta at the requested release tag (default `v4.2.0`),
+#      drops the bundle jar into `spark-unified/lib/` only (NOT `spark/lib/`
+#      -- see setup-delta.sh for the unmanagedJars scoping rationale),
+#      patches Delta's `DeltaSQLCommandTest` to register the Gluten plugin,
+#      and runs `sbt spark/test` sharded across the matrix.
+#
+# Limited to Velox + x86 to keep the matrix simple, per the pipeline's purpose
+# of validating Gluten changes against the latest Delta release.
+
+name: Delta Spark UT (Gluten)
+
+on:
+  workflow_dispatch:
+    inputs:
+      delta_ref:
+        description: 'delta-io/delta git ref (tag/branch/SHA) to test against'
+        required: true
+        default: 'v4.2.0'
+      spark_version:
+        description: 'Delta `-DsparkVersion` value (must match the Gluten -P 
profile below)'
+        required: true
+        default: '4.1'
+      test_parallelism:
+        description: 'Forked test JVMs per shard (TEST_PARALLELISM_COUNT)'
+        required: true
+        default: '1'
+      update_baseline:
+        description: 'Seed/refresh the known-failures baseline instead of 
enforcing it'
+        type: boolean
+        required: false
+        default: false
+      fail_on_fixed:
+        description: 'Fail when a baseline test now passes (keeps the baseline 
honest)'
+        type: boolean
+        required: false
+        default: true
+  pull_request:
+    paths:
+      - '.github/workflows/delta_spark_ut.yml'
+      - '.github/workflows/util/delta-spark-ut/**'
+      - 'gluten-delta/**'
+      - 'backends-velox/src-delta40/**/DeltaSQLCommandTest.scala'
+
+env:
+  ACTIONS_ALLOW_USE_UNSECURE_NODE_VERSION: true

Review Comment:
   Setting ACTIONS_ALLOW_USE_UNSECURE_NODE_VERSION=true weakens your GitHub 
Actions runtime safety guarantees and can allow deprecated/unsupported Node 
runtimes for actions. If this workflow doesn’t require legacy Node-based 
actions, remove this env var; otherwise, scope it as narrowly as possible and 
document the specific action/version that needs it (prefer upgrading actions to 
Node20-compatible versions instead).



##########
backends-velox/src-delta40/main/scala/org/apache/spark/sql/delta/stats/GlutenDeltaJobStatsTracker.scala:
##########
@@ -99,6 +110,48 @@ object GlutenDeltaJobStatsTracker extends Logging {
       new GlutenDeltaJobStatsFallbackTracker(tracker)
   }
 
+  /**
+   * Returns whether the Delta per-file statistics aggregation can be 
offloaded to a Velox
+   * whole-stage transformer. This mirrors the plan that 
[[GlutenDeltaTaskStatsTracker]] builds on
+   * the executors: if the aggregation/projection is not supported by Velox it 
stays a vanilla
+   * [[ProjectExec]] (i.e. does not collapse into a 
[[WholeStageTransformer]]), in which case the
+   * native stats tracker must not be used. Evaluated once on the driver so 
the executors never
+   * allocate native resources for a plan that cannot run.
+   */
+  private def canOffloadStats(dataCols: Seq[Attribute], statsColExpr: 
Expression): Boolean = {
+    try {
+      val aggregates = statsColExpr.collect {
+        case ae: AggregateExpression if 
ae.aggregateFunction.isInstanceOf[DeclarativeAggregate] =>
+          ae
+      }
+      val statsAttrs = 
aggregates.flatMap(_.aggregateFunction.aggBufferAttributes)
+      val statsResultAttrs = 
aggregates.flatMap(_.aggregateFunction.inputAggBufferAttributes)
+      val aggOp = SortAggregateExec(
+        None,
+        isStreaming = false,
+        None,
+        Seq.empty,
+        aggregates,
+        statsAttrs,
+        0,
+        statsResultAttrs,
+        StatisticsInputNode(dataCols))
+      val projOp = ProjectExec(statsResultAttrs, aggOp)
+      val offloads = Seq(OffloadOthers()).map(_.toStrcitRule())

Review Comment:
   `toStrcitRule()` looks like a misspelling (likely meant `toStrictRule()`). 
If the actual method is `toStrictRule()`, this won’t compile. If the misspelled 
method really exists, it’s still easy to misuse elsewhere—consider aligning the 
API name to `toStrictRule` (or adding a correctly-spelled alias and migrating) 
to prevent repeated call-site typos.



##########
backends-velox/src-delta33/main/scala/org/apache/spark/sql/delta/stats/GlutenDeltaJobStatsTracker.scala:
##########
@@ -99,6 +110,48 @@ object GlutenDeltaJobStatsTracker extends Logging {
       new GlutenDeltaJobStatsFallbackTracker(tracker)
   }
 
+  /**
+   * Returns whether the Delta per-file statistics aggregation can be 
offloaded to a Velox
+   * whole-stage transformer. This mirrors the plan that 
[[GlutenDeltaTaskStatsTracker]] builds on
+   * the executors: if the aggregation/projection is not supported by Velox it 
stays a vanilla
+   * [[ProjectExec]] (i.e. does not collapse into a 
[[WholeStageTransformer]]), in which case the
+   * native stats tracker must not be used. Evaluated once on the driver so 
the executors never
+   * allocate native resources for a plan that cannot run.
+   */
+  private def canOffloadStats(dataCols: Seq[Attribute], statsColExpr: 
Expression): Boolean = {
+    try {
+      val aggregates = statsColExpr.collect {
+        case ae: AggregateExpression if 
ae.aggregateFunction.isInstanceOf[DeclarativeAggregate] =>
+          ae
+      }

Review Comment:
   Same issue as the delta40 variant: canOffloadStats() ignores non-declarative 
AggregateExpressions, which can produce false positives and select the native 
stats tracker even when the full stats aggregation cannot be offloaded. Prefer: 
collect all AggregateExpression nodes and return false if any are not 
DeclarativeAggregate (and/or are in unsupported aggregate forms).



##########
.github/workflows/util/delta-spark-ut/setup-delta.sh:
##########
@@ -0,0 +1,141 @@
+#!/usr/bin/env bash
+
+# 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.
+
+#
+# Prepares a delta-io/delta clone for running its `spark` module tests with the
+# Gluten (Velox) bundle jar on the classpath.
+#
+# Usage:
+#   setup-delta.sh <delta_ref> <delta_dir> <gluten_bundle_jar> 
<gluten_repo_root>
+#
+# Arguments:
+#   delta_ref           - git ref (tag/branch/sha) to check out (e.g. v4.2.0)
+#   delta_dir           - destination directory for the Delta clone
+#   gluten_bundle_jar   - path to the gluten-velox-bundle fat jar
+#   gluten_repo_root    - path to the Gluten repository root (used to locate
+#                         
backends-velox/src-delta40/.../DeltaSQLCommandTest.scala)
+#
+
+set -euo pipefail
+
+if [ "$#" -ne 4 ]; then
+  echo "Usage: $0 <delta_ref> <delta_dir> <gluten_bundle_jar> 
<gluten_repo_root>" >&2
+  exit 1
+fi
+
+DELTA_REF="$1"
+DELTA_DIR="$2"
+GLUTEN_BUNDLE_JAR="$3"
+GLUTEN_ROOT="$4"
+
+if [ ! -f "$GLUTEN_BUNDLE_JAR" ]; then
+  echo "Gluten bundle jar not found: $GLUTEN_BUNDLE_JAR" >&2
+  exit 1
+fi
+
+# Reuse the existing DeltaSQLCommandTest from Gluten's backends-velox module
+# rather than maintaining a separate copy. This file is compiled as part of the
+# unified `spark` project's Test scope, which has the Gluten bundle on its
+# classpath (via spark-unified/lib/), so the typed GlutenConfig / 
VeloxDeltaConfig
+# imports resolve correctly.
+PATCH_SOURCE="$GLUTEN_ROOT/backends-velox/src-delta40/test/scala/org/apache/spark/sql/delta/test/DeltaSQLCommandTest.scala"
+if [ ! -f "$PATCH_SOURCE" ]; then
+  echo "Gluten DeltaSQLCommandTest not found: $PATCH_SOURCE" >&2
+  exit 1
+fi
+
+echo "::group::Cloning delta-io/delta @ ${DELTA_REF}"
+# Shallow clone the requested tag/branch. Fall back to full clone when the ref 
is a SHA.
+if ! git clone --depth 1 --branch "$DELTA_REF" 
https://github.com/delta-io/delta.git "$DELTA_DIR"; then
+  echo "Shallow clone of ref '${DELTA_REF}' failed, falling back to full 
clone."
+  rm -rf "$DELTA_DIR"
+  git clone https://github.com/delta-io/delta.git "$DELTA_DIR"
+  git -C "$DELTA_DIR" checkout "$DELTA_REF"
+fi
+git -C "$DELTA_DIR" --no-pager log -1 --oneline
+echo "::endgroup::"
+
+echo "::group::Injecting Gluten bundle jar onto the spark project's TEST 
classpath"
+# The Gluten bundle jar must be on the spark project's TEST runtime classpath
+# (so DeltaSQLCommandTest can load org.apache.gluten.GlutenPlugin by name) but
+# NOT on the COMPILE classpath of `sparkV1`, which is the project that holds
+# Delta's main sources. The bundle's transitive contents include extra symbols
+# under `org.apache.spark.sql` that collide with Delta's main sources -- e.g.
+# MergeOutputGeneration.scala imports both `org.apache.spark.sql._` and
+# `org.apache.spark.sql.delta.ClassicColumnConversions._`, and would then fail
+# with `reference to expression is ambiguous`.
+#
+# sbt auto-scans `<baseDirectory>/lib` via `unmanagedBase`. Two relevant
+# projects in Delta v4.2.0 have a `lib/` baseDirectory:
+#   - sparkV1: `project in file("spark")`     -> spark/lib
+#   - spark  : `project in file("spark-unified")` -> spark-unified/lib
+# unmanagedJars are project-scoped (NOT inherited by dependents), so dropping
+# the bundle into spark-unified/lib/ adds it to the unified `spark` project's
+# Compile *and* Test classpaths -- but NOT to sparkV1's. That's exactly what
+# we want:
+#   * sparkV1/Compile sees ONLY Delta's regular deps -> Delta main compiles.
+#   * spark/Test/fullClasspath sees the bundle -> tests load GlutenPlugin.
+# (Verified empirically: with bundle only in spark-unified/lib/, sbt's
+#  `show sparkV1/Compile/dependencyClasspath` excludes the bundle and
+#  `show spark/Test/fullClasspath` includes it.)
+#
+# We deliberately do NOT also drop the bundle into spark/lib/, which is what
+# caused the previous compile failure: spark/lib/ is sparkV1's unmanagedBase,
+# and putting the bundle there would re-introduce the ambiguity errors.
+SPARK_UNIFIED_LIB="$DELTA_DIR/spark-unified/lib"
+mkdir -p "$SPARK_UNIFIED_LIB"
+cp "$GLUTEN_BUNDLE_JAR" "$SPARK_UNIFIED_LIB/gluten-velox-bundle.jar"
+ls -lh "$SPARK_UNIFIED_LIB"
+echo "::endgroup::"
+
+echo "::group::Patching DeltaSQLCommandTest to enable Gluten plugin"
+TARGET="$DELTA_DIR/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaSQLCommandTest.scala"
+if [ ! -f "$TARGET" ]; then
+  echo "Expected file not found in Delta clone: $TARGET" >&2
+  echo "The Delta directory layout for ref '${DELTA_REF}' may have changed."
+  exit 1
+fi
+cp "$PATCH_SOURCE" "$TARGET"
+echo "Patched $TARGET"
+echo "--- diff vs. upstream ---"
+git -C "$DELTA_DIR" --no-pager diff -- 
"spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaSQLCommandTest.scala"
 || true
+echo "::endgroup::"
+
+echo "::group::Disabling Delta scalastyle HeaderMatchesChecker"
+# Our reused DeltaSQLCommandTest carries Gluten's ASF-only license header, 
which
+# does not match Delta's HeaderMatchesChecker regex (the regex expects either a
+# Delta copyright block, or the ASF header followed by a Spark-modifications
+# block and the Delta copyright block). HeaderMatchesChecker is a file-level
+# checker that does NOT honor `// scalastyle:off` directives, so we instead
+# disable it globally in Delta's shared scalastyle-config.xml. The config is
+# applied via `ThisBuild / scalastyleConfig` in project/Checkstyle.scala, so a
+# single edit covers every sbt sub-project.
+SCALASTYLE_CONFIG="$DELTA_DIR/scalastyle-config.xml"
+if [ ! -f "$SCALASTYLE_CONFIG" ]; then
+  echo "Expected scalastyle config not found: $SCALASTYLE_CONFIG" >&2
+  exit 1
+fi
+sed -i \
+  's|<check level="error" class="org.scalastyle.file.HeaderMatchesChecker" 
enabled="true">|<check level="error" 
class="org.scalastyle.file.HeaderMatchesChecker" enabled="false">|' \
+  "$SCALASTYLE_CONFIG"

Review Comment:
   `sed -i` is GNU-specific; on macOS/BSD sed this will fail unless a backup 
suffix is provided. Since the README suggests local usage, consider making this 
portable (e.g., detect GNU vs BSD sed and choose `sed -i''`/`sed -i ''` vs `sed 
-i`, or use a temporary file + mv) so contributors can run it outside the CI 
container.



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to