← Back to Pull requests

[SPARK-60734][SS] Prune the columns that the scans of Data Source V2 streaming sources read #59943

Open
HyukjinKwon opened this pull request with 516 lines diff across 8 files
View on GitHub
HyukjinKwon HyukjinKwon commented on Oct 29, 2026 22:24 UTC
Author

What changes were proposed in this pull request?

The micro-batch and continuous executions now push the top-level columns that a streaming query needs into the scan builders of Data Source V2 streaming sources that support column pruning (SupportsPushDownRequiredColumns), instead of all the columns of their output, as V2ScanRelationPushDown does for batch scans.

  • StreamingV2ColumnPruning (new) computes the attributes of the sources that the query needs from its analyzed plan: those in its output, those that its operators reference, and every column of the children of the operators that need all of them (distinct, unions of any kind and other set operations, CTE definitions, and nodes that map the columns of a child by position). The scan of a streaming source is built once when the query starts, so the pruning uses that plan; the optimizer prunes each micro-batch further as before, so stateful operators keep getting the same columns.

  • MicroBatchExecution and ContinuousExecution call pruneColumns on the scan builder with those columns, and use the readSchema that the scan returns, so a source that reads more columns than required still works. A scan whose readSchema does not have the required columns is replaced by a scan of all the columns, and the stream of the replaced scan is stopped. The TODO: operator pushdown stays, since filters, aggregates and limits are still not pushed into streaming scans.

  • ColumnarScanBuilder (the adapter of native data sources) keeps the required columns and lets the batch scan prune them through its planner, while its streaming scans keep reading the full schema for now.

  • The behavior is behind the internal configuration spark.sql.streaming.v2ColumnPruning.enabled (true by default), and the Structured Streaming migration guide has an entry for it.
  • This targets 4.4.0 (master and branch-4.x).

    Why are the changes needed?

    A streaming scan of a Data Source V2 source reads every column of the source, even when the query needs only some of them, while a batch scan of the same source reads only those. Native data sources (SPARK-60723, #59931) will benefit once their stream readers get the columns to read.

    Does this PR introduce _any_ user-facing change?

    Yes. Streaming queries over Data Source V2 sources whose scan builders implement SupportsPushDownRequiredColumns read only the columns that they need. So a third-party streaming source of this kind now gets a pruned schema in pruneColumns, where it got all the columns of its output before, as batch scans of it already do. The built-in streaming sources (Kafka, rate, memory, file and Python data sources) do not implement it for their streaming scans, so they are not affected. The results do not change. The migration guide says that spark.sql.streaming.v2ColumnPruning.enabled=false restores the previous behavior.

    How was this patch tested?

    New StreamingV2ColumnPruningSuite, which checks the readSchema of the streaming scans of an in-memory table, whose micro-batch reader now reads only the columns of that schema:

  • a projection, a streaming aggregation and a streaming deduplication read only the columns that they need, also after a restart from the checkpoint;

  • metadata columns that the query needs are read;

  • the children of a union read all their columns;

  • a scan that reads more columns than required still returns the right result;

  • a scan that does not read the required columns is replaced by a scan of all the columns, and its stream is stopped;

  • the event-time column of a watermark is read, also when the query does not output it;

  • a stream-static join and a stream-stream join read only the columns of each side, the stream-stream join also after a restart from the checkpoint;

  • all the columns are read when the configuration is disabled.
  • Continuous processing goes through the same code, but is not tested, since the in-memory table only supports micro-batch reads.

    StreamingV2ColumnPruningSuite, DataStreamTableAPISuite, ChangelogResolutionSuite, MicroBatchExecutionSuite, AsyncProgressTrackingMicroBatchExecutionSuite, ColumnarDataSourceSuite, NativeDataSourceSuite and DataSourceV2Suite pass locally.

    Was this patch authored or co-authored using generative AI tooling?

    Generated-by: Claude Code (Claude Opus 5.5)

    This pull request and its description were written by Isaac.

    Diff: 516 lines (+472 / -44) across 8 files Reviewer: dongjoon-hyun Review duration: 7064m
    All Vouch review confidence checks passed
    Residual risk 0.04 = Change Risk (0.51) × (1 − Review Confidence (0.92)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.51 · 516 lines diff across 8 files
    0.51
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.93 · 5 substantive comment(s)
    0.93
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    92%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.374
    Real PR Conversation Timeline
    26 items
    spark-test spark-test commented on Oct 30, 2026 03:13 UTC
    Contributor

    The AI review requested by @HyukjinKwon did not finish. A committer can add the ai-review-requested label again to retry.

    <!-- SPARK_OSS_REVIEW_REQUEST 34642439460 -->

    dongjoon-hyun dongjoon-hyun commented on code on Oct 30, 2026 03:50 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ColumnPruningSuite.scala:1
    @@ -0,0 +1,237 @@
    +/*
    + * 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.
    + */
    +
    +package org.apache.spark.sql.streaming
    +
    +import org.scalatest.BeforeAndAfter
    +
    +import org.apache.spark.sql.Row
    +import org.apache.spark.sql.connector.catalog.{Identifier, InMemoryBaseTable, InMemoryTableCatalog}
    +import org.apache.spark.sql.execution.datasources.v2.StreamingDataSourceV2ScanRelation
    +import org.apache.spark.sql.internal.SQLConf
    +
    +class StreamingV2ColumnPruningSuite extends StreamTest with BeforeAndAfter {
    +
    +  private val tbl = "testcat.t"
    +
    +  before {
    +    spark.conf.set("spark.sql.catalog.testcat", classOf[InMemoryTableCatalog].getName)
    +  }
    +
    +  after {
    +    spark.sessionState.catalogManager.reset()
    +    spark.conf.unset("spark.sql.catalog.testcat")
    +  }
    +
    +  private def withSourceTable(properties: String = "")(f: => Unit): Unit = {
    +    withTable(tbl) {
    +      sql(s"CREATE TABLE $tbl (id bigint, data string, extra int) $properties")
    +      sql(s"INSERT INTO $tbl VALUES (1, 'a', 10), (2, 'b', 20)")
    +      f
    +    }
    +  }
    +
    +  private def insert(values: String): StreamAction = Execute { _ =>
    +    sql(s"INSERT INTO $tbl VALUES $values")
    +  }
    +
    +  private def assertReadSchema(columns: String*): StreamAction = AssertOnQuery { query =>
    +    val readSchemas = query.logicalPlan.collect {
    +      case relation: StreamingDataSourceV2ScanRelation =>
    +        relation.scan.readSchema().fieldNames.toSeq
    +    }
    +    assert(readSchemas.nonEmpty)
    +    readSchemas.foreach(readSchema => assert(readSchema === columns))
    +    true
    +  }
    +
    +  test("read only the columns that a streaming query needs, also after a restart") {
    +    withSourceTable() {
    +      val df = spark.readStream.table(tbl).where("extra > 10").select("data")
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        assertReadSchema("data", "extra"),
    +        CheckAnswer(Row("b")),
    +        StopStream,
    +        insert("(3, 'c', 30), (4, 'd', 5)"),
    +        StartStream(),
    +        ProcessAllAvailable(),
    +        assertReadSchema("data", "extra"),
    +        CheckAnswer(Row("b"), Row("c")))
    +    }
    +  }
    +
    +  test("read only the columns of a streaming aggregation, also after a restart") {
    +    withSourceTable() {
    +      val df = spark.readStream.table(tbl).groupBy("data").count()
    +      testStream(df, OutputMode.Complete())(
    +        ProcessAllAvailable(),
    +        assertReadSchema("data"),
    +        CheckAnswer(Row("a", 1L), Row("b", 1L)),
    +        StopStream,
    +        insert("(3, 'a', 30)"),
    +        StartStream(),
    +        ProcessAllAvailable(),
    +        assertReadSchema("data"),
    +        CheckAnswer(Row("a", 2L), Row("b", 1L)))
    +    }
    +  }
    +
    +  test("read only the columns of a streaming deduplication, also after a restart") {
    +    withSourceTable() {
    +      val df = spark.readStream.table(tbl).dropDuplicates("data").select("id")
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        assertReadSchema("id", "data"),
    +        CheckAnswer(Row(1L), Row(2L)),
    +        StopStream,
    +        insert("(3, 'a', 30), (4, 'c', 40)"),
    +        StartStream(),
    +        ProcessAllAvailable(),
    +        assertReadSchema("id", "data"),
    +        CheckAnswer(Row(1L), Row(2L), Row(4L)))
    +    }
    +  }
    +
    +  test("read the metadata columns that a streaming query needs") {
    +    withSourceTable() {
    +      val df = spark.readStream.table(tbl).select("data", "index")
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        assertReadSchema("data", "index"),
    +        CheckAnswerRowsByFunc(rows => {
    +          assert(rows.map(_.getString(0)).sorted === Seq("a", "b"))
    +          assert(rows.forall(!_.isNullAt(1)))
    +        }, lastOnly = false))
    +    }
    +  }
    +
    +  test("read all the columns of the children of a union") {
    +    withSourceTable() {
    +      val source = spark.readStream.table(tbl)
    +      // A union maps the columns of its children by position, and its output is the one of its
    +      // first child, so the query does not reference the columns of its other children.
    +      val df = source.union(source).select("data")

    1. [Medium] The union test passes without the UnionBase case

    source.union(source) is a self-union, so DeduplicateRelations puts a Project of aliases of all the columns over its second child. The references of that Project already require id, data and extra. So this test still reads all the columns when _: UnionBase is removed from requiredAttributes (StreamingV2ColumnPruning.scala L48). For the same reason, the comment above (L126-127) does not hold for a self-union.

    The UnionBase case is meant for a union of two reads that have their own attributes, where nothing references the columns of the second read. Could the test union two reads of the table instead?

          val df = spark.readStream.table(tbl).union(spark.readStream.table(tbl)).select("data")
    

    Without the case, the scan of the second read would then be pruned to no columns. Distinct, SetOperation, CTERelationDef and mapsColumnsByPosition have no test either.

    dongjoon-hyun dongjoon-hyun commented on Oct 30, 2026 03:50 UTC
    Reviewer

    Thank you, @HyukjinKwon. I did not run the suites; the comments come from reading the code at 097f204.

    None of the comments below is about a query that fails with the built-in sources today:

  • Item 1 is a gap in the tests of the new pruning.

  • Items 3, 6 and 7 are about third-party connectors and operators that the pruning does not know.

  • The rest are smaller.
  • Summary:

    1. [Medium] The union test passes without the UnionBase case (StreamingV2ColumnPruningSuite.scala:128)
    2. [Low] ColumnarScan.readSchema() depends on whether toMicroBatchStream was called (ColumnarTable.scala:176)
    3. [Low] An operator missing from this list makes the scan drop a column that it needs (StreamingV2ColumnPruning.scala:48)
    4. [Low] The first stream is not stopped when the check or the second scan fails (StreamingV2ColumnPruning.scala:101)
    5. [Low] No test reads some of the columns of a columnar stream (ColumnarTable.scala:186)
    6. [Low] The output follows the order of the read schema, not of output (StreamingV2ColumnPruning.scala:107)
    7. [Low] The fallback to all the columns is silent (StreamingV2ColumnPruning.scala:111)
    8. [Nit] This remapping repeats PushDownUtils.toOutputAttrs (StreamingV2ColumnPruning.scala:105)
    9. [Nit] forall(scanOutput.contains) is quadratic in the number of columns (StreamingV2ColumnPruning.scala:108)
    10. [Nit] batchSchema is evaluated only for its side effect (ColumnarTable.scala:168)

    dongjoon-hyun dongjoon-hyun commented on code on Oct 30, 2026 03:50 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarTable.scala:1
    @@ -123,39 +124,56 @@ class ColumnarScanBuilder(
     
       override def pruneColumns(requiredSchema: StructType): Unit = {
         // Only top-level columns are pruned by the data source. Spark prunes the nested fields of the
    -    // columns it reads.
    +    // columns it reads. A batch scan asks its planner to prune them when it is planned, while a
    +    // streaming scan, which Spark also prunes, has no batch planner and reads all the columns.
         val required =
           StructType(requiredSchema.fieldNames.flatMap(name => schema.find(_.name == name)))
    -    if (required.length < schema.length && batchPlanner.pruneColumns(required)) {
    -      readSchema = required
    +    if (required.length < schema.length) {
    +      this.requiredSchema = Some(required)
         }
       }
     
       // The scan takes over the planner, so it is built once.
       private lazy val scan = new ColumnarScan(
    -    shortName, schema, readSchema, dataSource, Option(planner), pushedLimit)
    +    shortName, schema, requiredSchema, dataSource, Option(planner), pushedLimit)
     
       override def build(): Scan = scan
     }
     
     /**
    + * @param requiredSchema the top-level columns that the query needs, if fewer than those of the
    + *                       full schema. A batch scan asks its planner to prune the other columns,
    + *                       while a streaming scan reads all the columns of the full schema, which is
    + *                       the schema that a stream reader gets.
      * @param pushedDownPlanner the planner that the operations were pushed down to, if any. Otherwise,
    - *                          the scan creates one when its batch is planned.
    + *                          the scan creates one when its batch is planned or pruned.
      */
     class ColumnarScan(
         shortName: String,
         fullSchema: StructType,
    -    prunedSchema: StructType,
    +    requiredSchema: Option[StructType],
         dataSource: ColumnarDataSource,
         pushedDownPlanner: Option[ColumnarBatchPlanner],
         pushedLimit: Option[Int])
       extends Scan with SupportsMetadata {
     
    -  // Spark may call `toBatch` more than once for the same scan; the partitions are planned once.
    -  private lazy val batch = new ColumnarBatchScan(
    -    pushedDownPlanner.getOrElse(dataSource.batchPlanner(fullSchema)))
    +  private lazy val planner = pushedDownPlanner.getOrElse(dataSource.batchPlanner(fullSchema))
     
    -  override def readSchema(): StructType = prunedSchema
    +  // The columns that the batch reads: the required ones if the planner prunes the others.
    +  private lazy val batchSchema = requiredSchema.filter(planner.pruneColumns).getOrElse(fullSchema)
    +
    +  // Spark may call `toBatch` more than once for the same scan; the partitions are planned once,
    +  // after the columns are pruned.
    +  private lazy val batch = {
    +    batchSchema
    +    new ColumnarBatchScan(planner)
    +  }
    +
    +  // Whether the scan is the one of a micro-batch stream, which Spark asks for its read schema
    +  // after it creates the stream.
    +  @volatile private var streaming = false
    +
    +  override def readSchema(): StructType = if (streaming) fullSchema else batchSchema

    2. [Low] ColumnarScan.readSchema() depends on whether toMicroBatchStream was called

    StreamingV2ColumnPruning.buildScan asks for the read schema only after it creates the stream, so this works today. But the result of readSchema() now depends on the order of the calls, and the Scan API does not define that order. If anything asks a streaming ColumnarScan for its read schema before toMicroBatchStream, three things go wrong:

  • It evaluates batchSchema, which creates a batch planner for a data source that may not support batch scans (L91-92).

  • It asks that planner to prune the columns.

  • It reports the pruned columns, while the stream reader still reads fullSchema.
  • If the flag stays, could the doc of ColumnarScan say that the read schema of a streaming scan is only valid once its stream is created? Then a later caller does not rely on the other order.

    dongjoon-hyun dongjoon-hyun commented on code on Oct 30, 2026 03:50 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:1
    @@ -0,0 +1,117 @@
    +/*
    + * 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.
    + */
    +
    +package org.apache.spark.sql.execution.streaming.runtime
    +
    +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, AttributeSet, NamedExpression}
    +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, Distinct, LogicalPlan, SetOperation, UnionBase}
    +import org.apache.spark.sql.catalyst.types.DataTypeUtils
    +import org.apache.spark.sql.connector.catalog.SupportsRead
    +import org.apache.spark.sql.connector.read.{Scan, SupportsPushDownRequiredColumns}
    +import org.apache.spark.sql.connector.read.streaming.SparkDataStream
    +import org.apache.spark.sql.util.CaseInsensitiveStringMap
    +
    +/**
    + * Prunes the top-level columns that the scans of Data Source V2 streaming sources read to those
    + * that a streaming query needs, as `V2ScanRelationPushDown` does for batch scans. The scan of a
    + * streaming source is built once, when the query starts, from its analyzed plan, so the required
    + * columns are taken from that plan: the optimizer prunes the columns of each micro-batch further,
    + * so stateful operators keep getting the same columns as without this pruning.
    + */
    +private[sql] object StreamingV2ColumnPruning {
    +
    +  /**
    +   * Returns the attributes of its sources that a query needs: those in its output, those that its
    +   * operators reference, and every column of the children of the operators that need all of them,
    +   * such as a distinct, or that map the columns of a child to their output by position rather
    +   * than by attribute, such as a union of any kind or the definition of a common table expression.
    +   */
    +  def requiredAttributes(plan: LogicalPlan): AttributeSet = {
    +    var required = plan.outputSet
    +    plan.foreach { node =>
    +      required ++= node.references
    +      val needsAllColumns = node match {
    +        case _: UnionBase | _: SetOperation | _: Distinct | _: CTERelationDef => true

    3. [Low] An operator missing from this list makes the scan drop a column that it needs

    This lists the operators that need all the columns of their children, and treats every other operator as safe. So an operator that the list misses fails in the unsafe direction. The scan drops a column that the plan of a micro-batch needs later, and the query fails at planning or reads the wrong column, instead of just reading too much. Two kinds of operators are at risk:

  • An operator that keeps the attributes of its children but maps them by position, as Union does.

  • An operator that an optimizer rule rewrites with new references to the columns of its child, as ReplaceDistinctWithAggregate does for Distinct (which the list covers).
  • Analyzed plans can also hold positions. An example is the unrequiredChildIndex of the Generate that ResolveChangelogTable builds, which is safe today only because its child is an Aggregate.

    Could this be inverted? Only the operators known to map their columns by attribute (Project, Filter, Aggregate, Join, EventTimeWatermark, Deduplicate, ...) would let a column be pruned, and every other operator would keep all the columns of its children. A missed operator would then only cost some pruning.

    dongjoon-hyun dongjoon-hyun commented on code on Oct 30, 2026 03:50 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:1
    @@ -0,0 +1,117 @@
    +/*
    + * 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.
    + */
    +
    +package org.apache.spark.sql.execution.streaming.runtime
    +
    +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, AttributeSet, NamedExpression}
    +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, Distinct, LogicalPlan, SetOperation, UnionBase}
    +import org.apache.spark.sql.catalyst.types.DataTypeUtils
    +import org.apache.spark.sql.connector.catalog.SupportsRead
    +import org.apache.spark.sql.connector.read.{Scan, SupportsPushDownRequiredColumns}
    +import org.apache.spark.sql.connector.read.streaming.SparkDataStream
    +import org.apache.spark.sql.util.CaseInsensitiveStringMap
    +
    +/**
    + * Prunes the top-level columns that the scans of Data Source V2 streaming sources read to those
    + * that a streaming query needs, as `V2ScanRelationPushDown` does for batch scans. The scan of a
    + * streaming source is built once, when the query starts, from its analyzed plan, so the required
    + * columns are taken from that plan: the optimizer prunes the columns of each micro-batch further,
    + * so stateful operators keep getting the same columns as without this pruning.
    + */
    +private[sql] object StreamingV2ColumnPruning {
    +
    +  /**
    +   * Returns the attributes of its sources that a query needs: those in its output, those that its
    +   * operators reference, and every column of the children of the operators that need all of them,
    +   * such as a distinct, or that map the columns of a child to their output by position rather
    +   * than by attribute, such as a union of any kind or the definition of a common table expression.
    +   */
    +  def requiredAttributes(plan: LogicalPlan): AttributeSet = {
    +    var required = plan.outputSet
    +    plan.foreach { node =>
    +      required ++= node.references
    +      val needsAllColumns = node match {
    +        case _: UnionBase | _: SetOperation | _: Distinct | _: CTERelationDef => true
    +        case _ => mapsColumnsByPosition(node)
    +      }
    +      if (needsAllColumns) {
    +        node.children.foreach(child => required ++= child.outputSet)
    +      }
    +    }
    +    required
    +  }
    +
    +  /**
    +   * Returns whether a node outputs attributes that are neither of its children, nor produced or
    +   * defined by its expressions, which it then maps from the columns of its children by position.
    +   */
    +  private def mapsColumnsByPosition(node: LogicalPlan): Boolean = node.children.nonEmpty && {
    +    val known = AttributeSet(node.children.flatMap(_.output)) ++ node.producedAttributes ++
    +      AttributeSet(node.expressions.collect { case named: NamedExpression => named.toAttribute })
    +    node.output.exists(attribute => !known.contains(attribute))
    +  }
    +
    +  /**
    +   * Builds the scan of a streaming source that reads the columns of `output` in `required`, when
    +   * its scan builder supports column pruning, and creates its stream with `createStream`.
    +   * Returns the scan, its stream and its output: the columns of `output` that it reads, in the
    +   * order of its read schema when the scan prunes them, and otherwise `output` as it is. A scan
    +   * that does not read the required columns, as named in `output`, is replaced by one of all the
    +   * columns, as without pruning.
    +   *
    +   * The read schema of the scan is asked once its stream is created, since a scan may only know
    +   * then what it reads for a stream.
    +   *
    +   * @param output the output of the source, with the metadata columns that the query reads, which
    +   *               the analyzer added to it
    +   * @param required the attributes that the query needs, or None to read all the columns
    +   */
    +  def buildScan[S <: SparkDataStream](
    +      table: SupportsRead,
    +      options: CaseInsensitiveStringMap,
    +      output: Seq[AttributeReference],
    +      required: Option[AttributeSet])(
    +      createStream: Scan => S): (Scan, S, Seq[AttributeReference]) = {
    +    def build(columns: Seq[AttributeReference]): (Scan, Boolean) = {
    +      val builder = table.newScanBuilder(options)
    +      val prunes = builder match {
    +        case pruning: SupportsPushDownRequiredColumns =>
    +          pruning.pruneColumns(DataTypeUtils.fromAttributes(columns))
    +          true
    +        case _ => false
    +      }
    +      (builder.build(), prunes)
    +    }
    +    val requiredOutput = required.map(r => output.filter(r.contains)).getOrElse(output)
    +    val (scan, prunes) = build(requiredOutput)
    +    val stream = createStream(scan)

    4. [Low] The first stream is not stopped when the check or the second scan fails

    The stream is created before the read schema is checked. If scan.readSchema() (L106), build(output) or createStream(fullScan) (L112-113) throws, nothing stops stream. It is not in sources yet, so StreamExecution does not stop it either when the query fails, and whatever the stream holds stays open. Could the check and the rebuild run in a try that stops stream on a failure?

    dongjoon-hyun dongjoon-hyun commented on code on Oct 30, 2026 03:50 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarTable.scala:1
    @@ -165,11 +183,12 @@ class ColumnarScan(
       override def toBatch: Batch = batch
     
       override def toMicroBatchStream(checkpointLocation: String): MicroBatchStream = {
    +    streaming = true

    5. [Low] No test reads some of the columns of a columnar stream

    ColumnarScanBuilder.pruneColumns now gets the pruned columns of streaming queries too. A stream then returns the right columns only because readSchema() returns fullSchema once streaming is set. The streaming read test of ColumnarDataSourceSuite reads all the columns, so it still passes if this regresses. Could the suite have a streaming counterpart of its pruning test (L76-79 of ColumnarDataSourceSuite.scala)? For example:

        val query = spark.readStream.format(format).option("end", "5").load().select("name")
          .writeStream.format("memory").queryName("pruned_stream").start()
        try query.processAllAvailable() finally query.stop()
        checkAnswer(spark.table("pruned_stream"), (0L until 5L).map(id => Row(s"name$id")))
    

    dongjoon-hyun dongjoon-hyun commented on code on Oct 30, 2026 03:50 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:1
    @@ -0,0 +1,117 @@
    +/*
    + * 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.
    + */
    +
    +package org.apache.spark.sql.execution.streaming.runtime
    +
    +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, AttributeSet, NamedExpression}
    +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, Distinct, LogicalPlan, SetOperation, UnionBase}
    +import org.apache.spark.sql.catalyst.types.DataTypeUtils
    +import org.apache.spark.sql.connector.catalog.SupportsRead
    +import org.apache.spark.sql.connector.read.{Scan, SupportsPushDownRequiredColumns}
    +import org.apache.spark.sql.connector.read.streaming.SparkDataStream
    +import org.apache.spark.sql.util.CaseInsensitiveStringMap
    +
    +/**
    + * Prunes the top-level columns that the scans of Data Source V2 streaming sources read to those
    + * that a streaming query needs, as `V2ScanRelationPushDown` does for batch scans. The scan of a
    + * streaming source is built once, when the query starts, from its analyzed plan, so the required
    + * columns are taken from that plan: the optimizer prunes the columns of each micro-batch further,
    + * so stateful operators keep getting the same columns as without this pruning.
    + */
    +private[sql] object StreamingV2ColumnPruning {
    +
    +  /**
    +   * Returns the attributes of its sources that a query needs: those in its output, those that its
    +   * operators reference, and every column of the children of the operators that need all of them,
    +   * such as a distinct, or that map the columns of a child to their output by position rather
    +   * than by attribute, such as a union of any kind or the definition of a common table expression.
    +   */
    +  def requiredAttributes(plan: LogicalPlan): AttributeSet = {
    +    var required = plan.outputSet
    +    plan.foreach { node =>
    +      required ++= node.references
    +      val needsAllColumns = node match {
    +        case _: UnionBase | _: SetOperation | _: Distinct | _: CTERelationDef => true
    +        case _ => mapsColumnsByPosition(node)
    +      }
    +      if (needsAllColumns) {
    +        node.children.foreach(child => required ++= child.outputSet)
    +      }
    +    }
    +    required
    +  }
    +
    +  /**
    +   * Returns whether a node outputs attributes that are neither of its children, nor produced or
    +   * defined by its expressions, which it then maps from the columns of its children by position.
    +   */
    +  private def mapsColumnsByPosition(node: LogicalPlan): Boolean = node.children.nonEmpty && {
    +    val known = AttributeSet(node.children.flatMap(_.output)) ++ node.producedAttributes ++
    +      AttributeSet(node.expressions.collect { case named: NamedExpression => named.toAttribute })
    +    node.output.exists(attribute => !known.contains(attribute))
    +  }
    +
    +  /**
    +   * Builds the scan of a streaming source that reads the columns of `output` in `required`, when
    +   * its scan builder supports column pruning, and creates its stream with `createStream`.
    +   * Returns the scan, its stream and its output: the columns of `output` that it reads, in the
    +   * order of its read schema when the scan prunes them, and otherwise `output` as it is. A scan
    +   * that does not read the required columns, as named in `output`, is replaced by one of all the
    +   * columns, as without pruning.
    +   *
    +   * The read schema of the scan is asked once its stream is created, since a scan may only know
    +   * then what it reads for a stream.
    +   *
    +   * @param output the output of the source, with the metadata columns that the query reads, which
    +   *               the analyzer added to it
    +   * @param required the attributes that the query needs, or None to read all the columns
    +   */
    +  def buildScan[S <: SparkDataStream](
    +      table: SupportsRead,
    +      options: CaseInsensitiveStringMap,
    +      output: Seq[AttributeReference],
    +      required: Option[AttributeSet])(
    +      createStream: Scan => S): (Scan, S, Seq[AttributeReference]) = {
    +    def build(columns: Seq[AttributeReference]): (Scan, Boolean) = {
    +      val builder = table.newScanBuilder(options)
    +      val prunes = builder match {
    +        case pruning: SupportsPushDownRequiredColumns =>
    +          pruning.pruneColumns(DataTypeUtils.fromAttributes(columns))
    +          true
    +        case _ => false
    +      }
    +      (builder.build(), prunes)
    +    }
    +    val requiredOutput = required.map(r => output.filter(r.contains)).getOrElse(output)
    +    val (scan, prunes) = build(requiredOutput)
    +    val stream = createStream(scan)
    +    if (!prunes || requiredOutput.length == output.length) {
    +      (scan, stream, output)
    +    } else {
    +      val byName = output.map(attribute => attribute.name -> attribute).toMap
    +      val readSchema = scan.readSchema()
    +      val scanOutput = readSchema.fieldNames.toSeq.flatMap(byName.get)

    6. [Low] The output follows the order of the read schema, not of output

    Before this PR, ColumnPruning put Project(output.filter(required)) over the relation, so an operator right above it got the columns in the order of output. Now the relation itself is pruned and takes the order of readSchema(), and no Project is added when the read schema has exactly the required columns.

    Some connectors return the pruned columns in another order than they were asked for, e.g. with their key columns first. Over such a scan, a stateful operator (for example a side of a stream-stream join) gets its input in another layout. A query restarted from an existing checkpoint then fails the state schema check. If the reordered columns have the same types, the check passes instead, because StateSchemaCompatibilityChecker ignores the names, and the query reads the stored rows with the fields swapped.

    SupportsPushDownRequiredColumns does not say that the order is kept. Would it be safer to keep the order of requiredOutput, for example with a Project in that order over the relation, or by falling back when the orders differ?

    dongjoon-hyun dongjoon-hyun commented on code on Oct 30, 2026 03:50 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:1
    @@ -0,0 +1,117 @@
    +/*
    + * 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.
    + */
    +
    +package org.apache.spark.sql.execution.streaming.runtime
    +
    +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, AttributeSet, NamedExpression}
    +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, Distinct, LogicalPlan, SetOperation, UnionBase}
    +import org.apache.spark.sql.catalyst.types.DataTypeUtils
    +import org.apache.spark.sql.connector.catalog.SupportsRead
    +import org.apache.spark.sql.connector.read.{Scan, SupportsPushDownRequiredColumns}
    +import org.apache.spark.sql.connector.read.streaming.SparkDataStream
    +import org.apache.spark.sql.util.CaseInsensitiveStringMap
    +
    +/**
    + * Prunes the top-level columns that the scans of Data Source V2 streaming sources read to those
    + * that a streaming query needs, as `V2ScanRelationPushDown` does for batch scans. The scan of a
    + * streaming source is built once, when the query starts, from its analyzed plan, so the required
    + * columns are taken from that plan: the optimizer prunes the columns of each micro-batch further,
    + * so stateful operators keep getting the same columns as without this pruning.
    + */
    +private[sql] object StreamingV2ColumnPruning {
    +
    +  /**
    +   * Returns the attributes of its sources that a query needs: those in its output, those that its
    +   * operators reference, and every column of the children of the operators that need all of them,
    +   * such as a distinct, or that map the columns of a child to their output by position rather
    +   * than by attribute, such as a union of any kind or the definition of a common table expression.
    +   */
    +  def requiredAttributes(plan: LogicalPlan): AttributeSet = {
    +    var required = plan.outputSet
    +    plan.foreach { node =>
    +      required ++= node.references
    +      val needsAllColumns = node match {
    +        case _: UnionBase | _: SetOperation | _: Distinct | _: CTERelationDef => true
    +        case _ => mapsColumnsByPosition(node)
    +      }
    +      if (needsAllColumns) {
    +        node.children.foreach(child => required ++= child.outputSet)
    +      }
    +    }
    +    required
    +  }
    +
    +  /**
    +   * Returns whether a node outputs attributes that are neither of its children, nor produced or
    +   * defined by its expressions, which it then maps from the columns of its children by position.
    +   */
    +  private def mapsColumnsByPosition(node: LogicalPlan): Boolean = node.children.nonEmpty && {
    +    val known = AttributeSet(node.children.flatMap(_.output)) ++ node.producedAttributes ++
    +      AttributeSet(node.expressions.collect { case named: NamedExpression => named.toAttribute })
    +    node.output.exists(attribute => !known.contains(attribute))
    +  }
    +
    +  /**
    +   * Builds the scan of a streaming source that reads the columns of `output` in `required`, when
    +   * its scan builder supports column pruning, and creates its stream with `createStream`.
    +   * Returns the scan, its stream and its output: the columns of `output` that it reads, in the
    +   * order of its read schema when the scan prunes them, and otherwise `output` as it is. A scan
    +   * that does not read the required columns, as named in `output`, is replaced by one of all the
    +   * columns, as without pruning.
    +   *
    +   * The read schema of the scan is asked once its stream is created, since a scan may only know
    +   * then what it reads for a stream.
    +   *
    +   * @param output the output of the source, with the metadata columns that the query reads, which
    +   *               the analyzer added to it
    +   * @param required the attributes that the query needs, or None to read all the columns
    +   */
    +  def buildScan[S <: SparkDataStream](
    +      table: SupportsRead,
    +      options: CaseInsensitiveStringMap,
    +      output: Seq[AttributeReference],
    +      required: Option[AttributeSet])(
    +      createStream: Scan => S): (Scan, S, Seq[AttributeReference]) = {
    +    def build(columns: Seq[AttributeReference]): (Scan, Boolean) = {
    +      val builder = table.newScanBuilder(options)
    +      val prunes = builder match {
    +        case pruning: SupportsPushDownRequiredColumns =>
    +          pruning.pruneColumns(DataTypeUtils.fromAttributes(columns))
    +          true
    +        case _ => false
    +      }
    +      (builder.build(), prunes)
    +    }
    +    val requiredOutput = required.map(r => output.filter(r.contains)).getOrElse(output)
    +    val (scan, prunes) = build(requiredOutput)
    +    val stream = createStream(scan)
    +    if (!prunes || requiredOutput.length == output.length) {
    +      (scan, stream, output)
    +    } else {
    +      val byName = output.map(attribute => attribute.name -> attribute).toMap
    +      val readSchema = scan.readSchema()
    +      val scanOutput = readSchema.fieldNames.toSeq.flatMap(byName.get)
    +      if (scanOutput.length == readSchema.length && requiredOutput.forall(scanOutput.contains)) {
    +        (scan, stream, scanOutput)
    +      } else {
    +        stream.stop()

    7. [Low] The fallback to all the columns is silent

    When the read schema does not have the required columns, the scan is replaced without a log. That means the connector does not follow SupportsPushDownRequiredColumns, and it costs a second scan and a second stream at every start. Could this log a warning with the source and the missing columns?

    The check also compares only the names. A read schema that has a column twice passes it (scanOutput.length == readSchema.length), and the relation then outputs the same attribute twice. Could it also require distinct names?

    dongjoon-hyun dongjoon-hyun commented on code on Oct 30, 2026 03:50 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:1
    @@ -0,0 +1,117 @@
    +/*
    + * 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.
    + */
    +
    +package org.apache.spark.sql.execution.streaming.runtime
    +
    +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, AttributeSet, NamedExpression}
    +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, Distinct, LogicalPlan, SetOperation, UnionBase}
    +import org.apache.spark.sql.catalyst.types.DataTypeUtils
    +import org.apache.spark.sql.connector.catalog.SupportsRead
    +import org.apache.spark.sql.connector.read.{Scan, SupportsPushDownRequiredColumns}
    +import org.apache.spark.sql.connector.read.streaming.SparkDataStream
    +import org.apache.spark.sql.util.CaseInsensitiveStringMap
    +
    +/**
    + * Prunes the top-level columns that the scans of Data Source V2 streaming sources read to those
    + * that a streaming query needs, as `V2ScanRelationPushDown` does for batch scans. The scan of a
    + * streaming source is built once, when the query starts, from its analyzed plan, so the required
    + * columns are taken from that plan: the optimizer prunes the columns of each micro-batch further,
    + * so stateful operators keep getting the same columns as without this pruning.
    + */
    +private[sql] object StreamingV2ColumnPruning {
    +
    +  /**
    +   * Returns the attributes of its sources that a query needs: those in its output, those that its
    +   * operators reference, and every column of the children of the operators that need all of them,
    +   * such as a distinct, or that map the columns of a child to their output by position rather
    +   * than by attribute, such as a union of any kind or the definition of a common table expression.
    +   */
    +  def requiredAttributes(plan: LogicalPlan): AttributeSet = {
    +    var required = plan.outputSet
    +    plan.foreach { node =>
    +      required ++= node.references
    +      val needsAllColumns = node match {
    +        case _: UnionBase | _: SetOperation | _: Distinct | _: CTERelationDef => true
    +        case _ => mapsColumnsByPosition(node)
    +      }
    +      if (needsAllColumns) {
    +        node.children.foreach(child => required ++= child.outputSet)
    +      }
    +    }
    +    required
    +  }
    +
    +  /**
    +   * Returns whether a node outputs attributes that are neither of its children, nor produced or
    +   * defined by its expressions, which it then maps from the columns of its children by position.
    +   */
    +  private def mapsColumnsByPosition(node: LogicalPlan): Boolean = node.children.nonEmpty && {
    +    val known = AttributeSet(node.children.flatMap(_.output)) ++ node.producedAttributes ++
    +      AttributeSet(node.expressions.collect { case named: NamedExpression => named.toAttribute })
    +    node.output.exists(attribute => !known.contains(attribute))
    +  }
    +
    +  /**
    +   * Builds the scan of a streaming source that reads the columns of `output` in `required`, when
    +   * its scan builder supports column pruning, and creates its stream with `createStream`.
    +   * Returns the scan, its stream and its output: the columns of `output` that it reads, in the
    +   * order of its read schema when the scan prunes them, and otherwise `output` as it is. A scan
    +   * that does not read the required columns, as named in `output`, is replaced by one of all the
    +   * columns, as without pruning.
    +   *
    +   * The read schema of the scan is asked once its stream is created, since a scan may only know
    +   * then what it reads for a stream.
    +   *
    +   * @param output the output of the source, with the metadata columns that the query reads, which
    +   *               the analyzer added to it
    +   * @param required the attributes that the query needs, or None to read all the columns
    +   */
    +  def buildScan[S <: SparkDataStream](
    +      table: SupportsRead,
    +      options: CaseInsensitiveStringMap,
    +      output: Seq[AttributeReference],
    +      required: Option[AttributeSet])(
    +      createStream: Scan => S): (Scan, S, Seq[AttributeReference]) = {
    +    def build(columns: Seq[AttributeReference]): (Scan, Boolean) = {
    +      val builder = table.newScanBuilder(options)
    +      val prunes = builder match {
    +        case pruning: SupportsPushDownRequiredColumns =>
    +          pruning.pruneColumns(DataTypeUtils.fromAttributes(columns))
    +          true
    +        case _ => false
    +      }
    +      (builder.build(), prunes)
    +    }
    +    val requiredOutput = required.map(r => output.filter(r.contains)).getOrElse(output)
    +    val (scan, prunes) = build(requiredOutput)
    +    val stream = createStream(scan)
    +    if (!prunes || requiredOutput.length == output.length) {
    +      (scan, stream, output)
    +    } else {
    +      val byName = output.map(attribute => attribute.name -> attribute).toMap

    8. [Nit] This remapping repeats PushDownUtils.toOutputAttrs

    Batch scans map the read schema back to the attributes of the relation by name in PushDownUtils.toOutputAttrs. That function also takes the data types and the CHAR/VARCHAR metadata of the read schema, while this code keeps the attributes of output. So the same scan can get different attributes in batch and streaming queries. toOutputAttrs only uses relation.output, so it could take the attributes as a parameter and be shared, once the names are checked as they are here.

    dongjoon-hyun dongjoon-hyun commented on code on Oct 30, 2026 03:50 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:1
    @@ -0,0 +1,117 @@
    +/*
    + * 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.
    + */
    +
    +package org.apache.spark.sql.execution.streaming.runtime
    +
    +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, AttributeSet, NamedExpression}
    +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, Distinct, LogicalPlan, SetOperation, UnionBase}
    +import org.apache.spark.sql.catalyst.types.DataTypeUtils
    +import org.apache.spark.sql.connector.catalog.SupportsRead
    +import org.apache.spark.sql.connector.read.{Scan, SupportsPushDownRequiredColumns}
    +import org.apache.spark.sql.connector.read.streaming.SparkDataStream
    +import org.apache.spark.sql.util.CaseInsensitiveStringMap
    +
    +/**
    + * Prunes the top-level columns that the scans of Data Source V2 streaming sources read to those
    + * that a streaming query needs, as `V2ScanRelationPushDown` does for batch scans. The scan of a
    + * streaming source is built once, when the query starts, from its analyzed plan, so the required
    + * columns are taken from that plan: the optimizer prunes the columns of each micro-batch further,
    + * so stateful operators keep getting the same columns as without this pruning.
    + */
    +private[sql] object StreamingV2ColumnPruning {
    +
    +  /**
    +   * Returns the attributes of its sources that a query needs: those in its output, those that its
    +   * operators reference, and every column of the children of the operators that need all of them,
    +   * such as a distinct, or that map the columns of a child to their output by position rather
    +   * than by attribute, such as a union of any kind or the definition of a common table expression.
    +   */
    +  def requiredAttributes(plan: LogicalPlan): AttributeSet = {
    +    var required = plan.outputSet
    +    plan.foreach { node =>
    +      required ++= node.references
    +      val needsAllColumns = node match {
    +        case _: UnionBase | _: SetOperation | _: Distinct | _: CTERelationDef => true
    +        case _ => mapsColumnsByPosition(node)
    +      }
    +      if (needsAllColumns) {
    +        node.children.foreach(child => required ++= child.outputSet)
    +      }
    +    }
    +    required
    +  }
    +
    +  /**
    +   * Returns whether a node outputs attributes that are neither of its children, nor produced or
    +   * defined by its expressions, which it then maps from the columns of its children by position.
    +   */
    +  private def mapsColumnsByPosition(node: LogicalPlan): Boolean = node.children.nonEmpty && {
    +    val known = AttributeSet(node.children.flatMap(_.output)) ++ node.producedAttributes ++
    +      AttributeSet(node.expressions.collect { case named: NamedExpression => named.toAttribute })
    +    node.output.exists(attribute => !known.contains(attribute))
    +  }
    +
    +  /**
    +   * Builds the scan of a streaming source that reads the columns of `output` in `required`, when
    +   * its scan builder supports column pruning, and creates its stream with `createStream`.
    +   * Returns the scan, its stream and its output: the columns of `output` that it reads, in the
    +   * order of its read schema when the scan prunes them, and otherwise `output` as it is. A scan
    +   * that does not read the required columns, as named in `output`, is replaced by one of all the
    +   * columns, as without pruning.
    +   *
    +   * The read schema of the scan is asked once its stream is created, since a scan may only know
    +   * then what it reads for a stream.
    +   *
    +   * @param output the output of the source, with the metadata columns that the query reads, which
    +   *               the analyzer added to it
    +   * @param required the attributes that the query needs, or None to read all the columns
    +   */
    +  def buildScan[S <: SparkDataStream](
    +      table: SupportsRead,
    +      options: CaseInsensitiveStringMap,
    +      output: Seq[AttributeReference],
    +      required: Option[AttributeSet])(
    +      createStream: Scan => S): (Scan, S, Seq[AttributeReference]) = {
    +    def build(columns: Seq[AttributeReference]): (Scan, Boolean) = {
    +      val builder = table.newScanBuilder(options)
    +      val prunes = builder match {
    +        case pruning: SupportsPushDownRequiredColumns =>
    +          pruning.pruneColumns(DataTypeUtils.fromAttributes(columns))
    +          true
    +        case _ => false
    +      }
    +      (builder.build(), prunes)
    +    }
    +    val requiredOutput = required.map(r => output.filter(r.contains)).getOrElse(output)
    +    val (scan, prunes) = build(requiredOutput)
    +    val stream = createStream(scan)
    +    if (!prunes || requiredOutput.length == output.length) {
    +      (scan, stream, output)
    +    } else {
    +      val byName = output.map(attribute => attribute.name -> attribute).toMap
    +      val readSchema = scan.readSchema()
    +      val scanOutput = readSchema.fieldNames.toSeq.flatMap(byName.get)
    +      if (scanOutput.length == readSchema.length && requiredOutput.forall(scanOutput.contains)) {

    9. [Nit] forall(scanOutput.contains) is quadratic in the number of columns

    Seq.contains compares the whole AttributeReference (name, exprId, data type, metadata and qualifier) with each element. So a source with thousands of columns makes millions of comparisons when the query starts. An AttributeSet does the same check in linear time:

          if (scanOutput.length == readSchema.length &&
              AttributeSet(requiredOutput).subsetOf(AttributeSet(scanOutput))) {
    

    dongjoon-hyun dongjoon-hyun commented on code on Oct 30, 2026 03:50 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarTable.scala:1
    @@ -123,39 +124,56 @@ class ColumnarScanBuilder(
     
       override def pruneColumns(requiredSchema: StructType): Unit = {
         // Only top-level columns are pruned by the data source. Spark prunes the nested fields of the
    -    // columns it reads.
    +    // columns it reads. A batch scan asks its planner to prune them when it is planned, while a
    +    // streaming scan, which Spark also prunes, has no batch planner and reads all the columns.
         val required =
           StructType(requiredSchema.fieldNames.flatMap(name => schema.find(_.name == name)))
    -    if (required.length < schema.length && batchPlanner.pruneColumns(required)) {
    -      readSchema = required
    +    if (required.length < schema.length) {
    +      this.requiredSchema = Some(required)
         }
       }
     
       // The scan takes over the planner, so it is built once.
       private lazy val scan = new ColumnarScan(
    -    shortName, schema, readSchema, dataSource, Option(planner), pushedLimit)
    +    shortName, schema, requiredSchema, dataSource, Option(planner), pushedLimit)
     
       override def build(): Scan = scan
     }
     
     /**
    + * @param requiredSchema the top-level columns that the query needs, if fewer than those of the
    + *                       full schema. A batch scan asks its planner to prune the other columns,
    + *                       while a streaming scan reads all the columns of the full schema, which is
    + *                       the schema that a stream reader gets.
      * @param pushedDownPlanner the planner that the operations were pushed down to, if any. Otherwise,
    - *                          the scan creates one when its batch is planned.
    + *                          the scan creates one when its batch is planned or pruned.
      */
     class ColumnarScan(
         shortName: String,
         fullSchema: StructType,
    -    prunedSchema: StructType,
    +    requiredSchema: Option[StructType],
         dataSource: ColumnarDataSource,
         pushedDownPlanner: Option[ColumnarBatchPlanner],
         pushedLimit: Option[Int])
       extends Scan with SupportsMetadata {
     
    -  // Spark may call `toBatch` more than once for the same scan; the partitions are planned once.
    -  private lazy val batch = new ColumnarBatchScan(
    -    pushedDownPlanner.getOrElse(dataSource.batchPlanner(fullSchema)))
    +  private lazy val planner = pushedDownPlanner.getOrElse(dataSource.batchPlanner(fullSchema))
     
    -  override def readSchema(): StructType = prunedSchema
    +  // The columns that the batch reads: the required ones if the planner prunes the others.
    +  private lazy val batchSchema = requiredSchema.filter(planner.pruneColumns).getOrElse(fullSchema)
    +
    +  // Spark may call `toBatch` more than once for the same scan; the partitions are planned once,
    +  // after the columns are pruned.
    +  private lazy val batch = {
    +    batchSchema

    10. [Nit] batchSchema is evaluated only for its side effect

    The bare batchSchema makes the planner prune the columns before the batch is planned, but it reads like a leftover. If it were removed, the batch would read all the columns while readSchema() reports the pruned ones. Could the dependency be explicit? For example:

      private lazy val batch = {
        // The planner prunes the columns before it plans the partitions.
        val _ = batchSchema
        new ColumnarBatchScan(planner)
      }
    

    HeartSaVioR HeartSaVioR commented on Oct 30, 2026 03:52 UTC
    Contributor

    I'm not sure I understand the change. If I read the code correctly, we prune the columns "before" we run optimizer to inform the data source (Scan) that which columns are needed? That's weird. What are preventing us to push the column pruning down to the streaming source on optimization phase, so that we don't need to do this here? Also, does analyzer also prune the columns?
    (Honestly I thought we already supported it. I even missed we do manual application on column pruning on initial planning today. Maybe I'm behind on recent changes I missed.)

    HeartSaVioR HeartSaVioR commented on Oct 30, 2026 04:05 UTC
    Contributor

    I just read through the recent commit - so the commit was not really to prune the columns but to fix the issue with metadata column. (I feel like something is maybe messed up, or the lifecycle of batch source and stream source are different and we have to take special care of stream source, if we had to do this.)

    https://github.com/apache/spark/commit/2adc69aca3de7415d011fbe4b3dedaa3a987e8d5

    3. This change fixes metadata column reads only, not column pruning.

    We call pruneColumns(output.toStructType) where output is the full analyzed relation

    output — all data columns plus any metadata columns added by AddMetadataColumns. This

    communicates required metadata columns to the scan builder so they appear in readSchema(),

    but does not prune data columns. Full column pruning in streaming, along with filter and

    aggregate pushdown, is deferred to the existing TODO.

    I see this PR could prune the columns based on the result of analyzer, but it doesn't still seem to address the TODO the commit message of 2adc69aca3de7415d011fbe4b3dedaa3a987e8d5 stated. Also IIUC, we are replicating the complicated logic of tracking the lineage of the columns again from the optimizer. Maybe it could still give some value based on analysis result, but we are yet to run optimizer. Is there a way we can request optimizer to do this rather than streaming engine to do some custom thing? Is batch data source really doing the same thing, pruning columns based on analysis result rather than optimization?

    HeartSaVioR HeartSaVioR commented on Oct 30, 2026 04:16 UTC
    Contributor

    cc. @zikangh since you've authored the relevant change; you may be interested with the change.
    Also cc. @gengliangwang since you've reviewed and merged the relevant change.

    HeartSaVioR HeartSaVioR commented on Oct 30, 2026 04:53 UTC
    Contributor

    1. Personally I prefer we do prune the columns in optimization phase. Let's check with the possibility, and if there is technical challenge that we can't, let's probably list it out.
    2. If we reach consensus that we want to prune the columns based on analysis result (or run some simple logic to track the columns, which the PR seems to do now) due to the fact there is no (easy) way to let the optimizer do it, tests against the logic must be exhaustive. E.g. multiple transformations with and without expressions which do calculation and/or SQL function call, multiple phases of assigning alias, from_json and sibling functions (though maybe from_json would be fine), parsing variant, struct and de-struct, etcetc. Basically we have lots of operators in the query, so if we want to correlate the query output and source's columns, we have to be 100% sure the logic correctly tracks all the lineage of the columns, and we do not hit anything on operators on top of the source. We are touching the area which could get into correctness/dataloss.

    spark-test spark-test commented on Oct 30, 2026 15:23 UTC
    Reviewer

    Review summary

    None of the findings below makes a query over the in-repo sources fail or return wrong rows today. The most serious one is a test gap: the union test is a self-union, whose deduplication Project already references every column, so it passes without the UnionBase case it is meant to cover. When the all-columns cases get tests, note three limits. Of the SetOperation nodes, streaming allows only Except, and only with spark.sql.streaming.allowExceptOnStreamingDataFrame. A CTE case needs a definition without a projection of its own, such as TABLE v, because a projection in the definition already references every column. And a streaming Distinct may only appear over a projection or a union, so a comment may serve it better than a test.

    The other defects are minor:

  • The micro-batch read of the kill switch races with session changes made after start() returns.

  • A readSchema() failure leaves the created stream running.

  • The full-scan fallback is not logged, and it also fires for read-schema fields that do not map to the output.

  • The migration guide and the conf doc claim a parity with batch pruning that common query shapes do not get.

  • Two query-start steps grow faster than linearly with plan and schema width.

  • Continuous mode, pruned columnar streams, queries that need no source column, and restarts across the two conf values each lack a test.
  • Questions for the author follow.

    Review-level concerns

  • Author input: It is still open whether the streaming column requirements should keep coming from a hand-maintained pass over the analyzed plan or be derived by the optimizer, as batch pruning does, and that choice decides several follow-ups. The current pass treats every operator outside its list of all-columns operators as safe. It reads every column for common shapes such as withColumn chains, nested selects and window aggregations. The migration guide and the conf doc describe parity with batch scans that it does not deliver. The author's input is needed on one of two directions. One is to explain why the optimizer cannot provide these columns and keep the pass; then it should fail safe for unknown operators, have lineage tests that each case is needed for, and be documented as analysis-time pruning. The other is to move to optimizer-derived columns, in which case the parity statement can stay. The documentation fix is minor and does not block on its own.

  • Author input: How existing checkpoints should behave on upgrade is undecided. The pruning conf is not pinned in the offset log, and the pruned relation takes the column order of the connector's read schema. So a stateful query over a pruning-capable source switches to pruned scans on its first restart, and keeps its state layout only when the connector returns the requested order. The author should choose one of three behaviors: keep the requested column order above the relation, pin the conf for existing checkpoints, or rely on connectors to keep the order. Restart tests across the two pruning modes, with rows that match stored state, should then verify the chosen behavior. The missing test is a minor gap and does not block on its own.
  • Cross-cutting observations

  • Default-on activation relies on two connector behaviors that the Data Source V2 contract does not pin down for streaming scans: stream readers that honor the pruned read schema they report, and a pruned read schema that keeps the requested column order. The in-repo pruning-capable streaming readers comply only because this change adjusted them or because they happen to keep the order. The name check in streaming scan building can detect neither deviation.

  • Separation: The two behaviors have different consequences and remedies. Readers that ignore the pruned schema misalign rows in every micro-batch, which calls for connector documentation or capability gating. A reordered read schema misreads state after a restart, which calls for order preservation or conf pinning. So each stays its own author decision.
  • The new coverage runs every scenario against one fixture: the in-memory table in micro-batch mode, which keeps the requested column order and is always restarted in the same pruning mode. As a result, none of these is exercised: unions of independent reads, columnar streams, continuous mode, queries that need no column, and restarts across the pruning modes.

  • Separation: Each gap needs its own test with its own source or scenario, and none of these tests depends on another, so the shared fixture is context rather than a common owner.

    Findings

    11 total: 0 P0, 0 P1, 1 P2, 10 P3.

    Non-blocking (P2)

  • The union test is a self-union that passes without the UnionBase case — sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ColumnPruningSuite.scala:128 — unresolved in existing discussion.
  • Nit (P3)

  • Micro-batch queries read the pruning kill switch from the live session after start() returns — sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:265 — see inline.

  • A readSchema() failure leaves the created stream running — sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:106 — unresolved in existing discussion.

  • No test reads only some columns of a columnar stream — sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarTable.scala:186 — unresolved in existing discussion.

  • Continuous-mode column pruning has no test — sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/continuous/ContinuousExecution.scala:104 — see inline.

  • No restart crosses the two conf values or reads restored join state — sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ColumnPruningSuite.scala:218 — see inline.

  • The migration guide and the conf doc claim parity with batch pruning — docs/streaming/ss-migration-guide.md:43 — see inline.

  • The fallback to a full scan is not logged — sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:111 — see inline.

  • The read-schema check is quadratic in the number of columns — sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:108 — unresolved in existing discussion.

  • requiredAttributes copies the accumulated set at every node — sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:46 — see inline.

  • No test covers a streaming query that needs no source column — sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:99 — see inline.
  • Existing discussions

  • existing discussion — raises an issue this review reports as a finding.
  • Decision challenges

    Deriving the streaming scan columns from the analyzed plan rather than the optimizer

    This review checked the pass against the operators that can reach it today. No in-repo streaming operator defeats the list. Of the SetOperation nodes, streaming allows only Except, and only behind spark.sql.streaming.allowExceptOnStreamingDataFrame; the SetOperation case covers it. The optimizer sets the positional unrequiredChildIndex of Generate per batch, and the analyzed one that ResolveChangelogTable builds sits over an Aggregate. ReplaceDeduplicateWithAggregate skips streaming children. So the exposure is to operators and per-batch rules added later or through SparkSessionExtensions, which reach the attribute-mapped default. The pass also keeps every column when an analyzed Project passes columns through (withColumn, chained selects, the window rewrites), so common shapes prune less than in batch.

    Two things remain open. Is there a concrete obstacle to taking these columns from an optimized plan, for example by optimizing once at query start, given that each micro-batch is optimized again? And if the analysis-time pass stays, should an operator outside the list keep all the columns of its children, so that a missing case only costs pruning?

    This follows up on existing discussions 1, 2, 3, 4, 5.

    Default-on pruning for connectors whose stream readers ignore the pruned schema

    By default, the streaming scan of any connector whose scan builder implements SupportsPushDownRequiredColumns now gets only the required columns, and the relation output is bound to the names in readSchema() (buildScan in StreamingV2ColumnPruning). The check there sees only the schema that the scan reports, not the rows that its stream readers emit. Consider a connector whose readSchema() reflects the pruning, as its batch path requires, but whose micro-batch or continuous readers still emit full rows. It used to work, because streaming always requested every column. After an upgrade, with no change to the query, it returns values from the wrong columns, silently when the types line up. Both in-repo readers of this shape had to change in this PR (ColumnarScan and the InMemoryBaseTable micro-batch reader). Nothing in the SupportsPushDownRequiredColumns, Scan or stream Javadoc tells implementors that streaming readers now receive pruned schemas, and the repository cannot show how many external connectors have this shape.

    Do you accept this risk, with the internal conf as the only mitigation? Or would you document the requirement in the connector Javadoc, or gate streaming pruning on an explicit connector capability or an opt-in conf?

    The read-schema column order becoming the stateful input layout across restarts

    This review confirmed the restart path that the inline comment describes. Stream-stream join state stores left.output and right.output. Its value schema is checked by position with DataType.equalsIgnoreNameAndCompatibleNullability, because the name-based Avro evolution path is off for that operator (schemaEvolutionEnabledForOperator is false). spark.sql.streaming.v2ColumnPruning.enabled is not in OffsetSeqMetadata.relevantSQLConfs, unlike PRUNE_FILTERS_CAN_PRUNE_STREAMING_SUBPLAN and DROP_DUPLICATES_DETERMINISTIC_KEY_ORDER, so an existing checkpoint switches to pruned scans on its first restart after the upgrade. For connectors that return the requested order, which both in-repo ones do, the layout matches the projection that ColumnPruning built before this change, so nothing breaks today.

    What remains open: may a supported connector return a pruned read schema in another order? If so, which guard do you prefer: a Project in the order of requiredOutput, a fallback when the orders differ, or pinning the conf in the offset log with a legacy default for existing checkpoints?

    This follows up on existing discussions 1, 2.

    Generated by Omnigent on Databricks
    <!-- SPARK_OSS_REVIEW_REQUEST 34684766770 -->

    <!-- SPARK_DEV_REVIEW_CODE {"findings":[{"delivery":"inline","fingerprint":"240a8c753b5af7430e74","id":"pass-a:pruning-conf-read-from-live-session"},{"delivery":"suppress","fingerprint":"6f6e666092a8988a8a39","id":"pass-b:abandoned-stream-not-stopped-on-read-schema-failure","thread_id":"inline:4420266627"},{"delivery":"suppress","fingerprint":"ccf436063db9539a4e83","id":"pass-b:columnar-pruned-stream-untested","thread_id":"inline:4420266634"},{"delivery":"inline","fingerprint":"106108761cd6b7f3b294","id":"pass-b:continuous-pruning-untested"},{"delivery":"inline","fingerprint":"d3984883ea3d49b85f26","id":"pass-b:cross-mode-stateful-restart-untested"},{"delivery":"inline","fingerprint":"8bc7b59de71819584747","id":"pass-b:pruning-docs-overstate-batch-parity"},{"delivery":"inline","fingerprint":"b90ff35d3fd6d135fd92","id":"pass-b:pruning-fallback-is-silent"},{"delivery":"suppress","fingerprint":"855b02083f476444f585","id":"pass-b:read-schema-check-quadratic-contains","thread_id":"inline:4420266671"},{"delivery":"inline","fingerprint":"67248419321242962cd0","id":"pass-b:required-attributes-copies-growing-set"},{"delivery":"suppress","fingerprint":"1c8ee36438092ff6f6f7","id":"pass-b:union-test-does-not-reach-unionbase-case","thread_id":"inline:4420266595"},{"delivery":"inline","fingerprint":"a36f995dc5793295066a","id":"pass-b:zero-required-columns-untested"}],"head_sha":"097f204040539a8ed84b95d240b361cce2ccc5f8","verdict_sha256":"47797de47bd65cbfd3847ccf0e02bbd7369be6decd21961eb9c690f16e33de78"} -->

    spark-test spark-test commented on code on Oct 30, 2026 15:23 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:1
    @@ -261,6 +260,13 @@ class MicroBatchExecution(
         }
     
         import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Implicits._
    +    // The columns of the Data Source V2 sources that the query needs, which their scans read.
    +    val requiredAttributes =
    +      if (sparkSession.sessionState.conf.streamingV2ColumnPruningEnabled) {

    Nit (P3): The conf is read from the caller's live session, but logicalPlan is initialized lazily on the query thread after start() has returned: runStream calls startLatch.countDown() before it forces logicalPlan, and the offset log is listed before this line. If a user turns the conf off around start() to work around a connector and restores it afterwards, the query can still build pruned scans, and the reverse can happen too. The other per-query reads in this initializer go through streamConf, the clone taken when the query is created (line 242); reading streamConf.streamingV2ColumnPruningEnabled here would bind the value at creation. Continuous queries read the conf during construction, so only micro-batch is affected.

    Verification:

  • Behavior: A micro-batch query started with streaming column pruning disabled keeps reading all source columns even when the session conf is set back to true right after start() returns, and a query started with pruning enabled keeps pruning when the conf is then disabled.
  • spark-test spark-test commented on code on Oct 30, 2026 15:23 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/continuous/ContinuousExecution.scala:1
    @@ -93,19 +99,13 @@ class ContinuousExecution(
                 log"from DataSourceV2 named '${MDC(STREAMING_DATA_SOURCE_NAME, sourceName)}' " +
                 log"${MDC(STREAMING_DATA_SOURCE_DESCRIPTION, dsStr)}")
               // TODO: operator pushdown.
    -          // Passes the full output schema (not a pruned subset) so that connectors
    -          // implementing SupportsMetadataColumns can include metadata columns in readSchema().
    -          val scanBuilder = table.newScanBuilder(options)
    -          scanBuilder match {
    -            case r: SupportsPushDownRequiredColumns =>
    -              r.pruneColumns(output.toStructType)
    -            case _ =>
    -          }
    -          val scan = scanBuilder.build()
    -          val stream = scan.toContinuousStream(metadataPath)
    +          // The output includes the metadata columns that the query reads, so that connectors
    +          // implementing SupportsMetadataColumns include them in readSchema().
    +          val (scan, stream, scanOutput) = StreamingV2ColumnPruning.buildScan(

    Nit (P3): This path is on by default for continuous queries, but nothing tests it: InMemoryBaseTable declares only MICRO_BATCH_READ, the continuous-capable built-in sources do not prune, and StreamingV2ColumnPruningSuite runs only micro-batch queries. A mistake that only continuous mode hits, such as binding the scan relation to output instead of scanOutput, taking the required columns from another plan, or breaking the fallback and its stream stop, would leave every test green. A small test source that supports CONTINUOUS_READ and column pruning could cover a pruned projection and the fallback.

    Verification:

  • Behavior: A continuous query over a source that supports continuous reads and column pruning reads only the columns it needs and returns the right rows.

  • Regression: In continuous mode, a scan whose read schema lacks a required column is replaced by a scan of all the columns, and the replaced stream is stopped.
  • spark-test spark-test commented on code on Oct 30, 2026 15:23 UTC
    Code Review
    sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ColumnPruningSuite.scala:1
    @@ -0,0 +1,237 @@
    +/*
    + * 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.
    + */
    +
    +package org.apache.spark.sql.streaming
    +
    +import org.scalatest.BeforeAndAfter
    +
    +import org.apache.spark.sql.Row
    +import org.apache.spark.sql.connector.catalog.{Identifier, InMemoryBaseTable, InMemoryTableCatalog}
    +import org.apache.spark.sql.execution.datasources.v2.StreamingDataSourceV2ScanRelation
    +import org.apache.spark.sql.internal.SQLConf
    +
    +class StreamingV2ColumnPruningSuite extends StreamTest with BeforeAndAfter {
    +
    +  private val tbl = "testcat.t"
    +
    +  before {
    +    spark.conf.set("spark.sql.catalog.testcat", classOf[InMemoryTableCatalog].getName)
    +  }
    +
    +  after {
    +    spark.sessionState.catalogManager.reset()
    +    spark.conf.unset("spark.sql.catalog.testcat")
    +  }
    +
    +  private def withSourceTable(properties: String = "")(f: => Unit): Unit = {
    +    withTable(tbl) {
    +      sql(s"CREATE TABLE $tbl (id bigint, data string, extra int) $properties")
    +      sql(s"INSERT INTO $tbl VALUES (1, 'a', 10), (2, 'b', 20)")
    +      f
    +    }
    +  }
    +
    +  private def insert(values: String): StreamAction = Execute { _ =>
    +    sql(s"INSERT INTO $tbl VALUES $values")
    +  }
    +
    +  private def assertReadSchema(columns: String*): StreamAction = AssertOnQuery { query =>
    +    val readSchemas = query.logicalPlan.collect {
    +      case relation: StreamingDataSourceV2ScanRelation =>
    +        relation.scan.readSchema().fieldNames.toSeq
    +    }
    +    assert(readSchemas.nonEmpty)
    +    readSchemas.foreach(readSchema => assert(readSchema === columns))
    +    true
    +  }
    +
    +  test("read only the columns that a streaming query needs, also after a restart") {
    +    withSourceTable() {
    +      val df = spark.readStream.table(tbl).where("extra > 10").select("data")
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        assertReadSchema("data", "extra"),
    +        CheckAnswer(Row("b")),
    +        StopStream,
    +        insert("(3, 'c', 30), (4, 'd', 5)"),
    +        StartStream(),
    +        ProcessAllAvailable(),
    +        assertReadSchema("data", "extra"),
    +        CheckAnswer(Row("b"), Row("c")))
    +    }
    +  }
    +
    +  test("read only the columns of a streaming aggregation, also after a restart") {
    +    withSourceTable() {
    +      val df = spark.readStream.table(tbl).groupBy("data").count()
    +      testStream(df, OutputMode.Complete())(
    +        ProcessAllAvailable(),
    +        assertReadSchema("data"),
    +        CheckAnswer(Row("a", 1L), Row("b", 1L)),
    +        StopStream,
    +        insert("(3, 'a', 30)"),
    +        StartStream(),
    +        ProcessAllAvailable(),
    +        assertReadSchema("data"),
    +        CheckAnswer(Row("a", 2L), Row("b", 1L)))
    +    }
    +  }
    +
    +  test("read only the columns of a streaming deduplication, also after a restart") {
    +    withSourceTable() {
    +      val df = spark.readStream.table(tbl).dropDuplicates("data").select("id")
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        assertReadSchema("id", "data"),
    +        CheckAnswer(Row(1L), Row(2L)),
    +        StopStream,
    +        insert("(3, 'a', 30), (4, 'c', 40)"),
    +        StartStream(),
    +        ProcessAllAvailable(),
    +        assertReadSchema("id", "data"),
    +        CheckAnswer(Row(1L), Row(2L), Row(4L)))
    +    }
    +  }
    +
    +  test("read the metadata columns that a streaming query needs") {
    +    withSourceTable() {
    +      val df = spark.readStream.table(tbl).select("data", "index")
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        assertReadSchema("data", "index"),
    +        CheckAnswerRowsByFunc(rows => {
    +          assert(rows.map(_.getString(0)).sorted === Seq("a", "b"))
    +          assert(rows.forall(!_.isNullAt(1)))
    +        }, lastOnly = false))
    +    }
    +  }
    +
    +  test("read all the columns of the children of a union") {
    +    withSourceTable() {
    +      val source = spark.readStream.table(tbl)
    +      // A union maps the columns of its children by position, and its output is the one of its
    +      // first child, so the query does not reference the columns of its other children.
    +      val df = source.union(source).select("data")
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        assertReadSchema("id", "data", "extra"),
    +        CheckAnswer(Row("a"), Row("b"), Row("a"), Row("b")))
    +    }
    +  }
    +
    +  test("read the columns that a scan returns when it reads more than the required ones") {
    +    withSourceTable(
    +        s"TBLPROPERTIES ('${InMemoryBaseTable.SIMULATE_PARTIAL_COLUMN_PRUNING}' = 'true')") {
    +      val df = spark.readStream.table(tbl).select("data", "index")
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        assertReadSchema("id", "data", "extra", "index"),
    +        CheckAnswerRowsByFunc(rows => {
    +          assert(rows.map(_.getString(0)).sorted === Seq("a", "b"))
    +          assert(rows.forall(!_.isNullAt(1)))
    +        }, lastOnly = false))
    +    }
    +  }
    +
    +  test("read all the columns when a scan does not read the required ones") {
    +    withSourceTable(
    +        s"TBLPROPERTIES ('${InMemoryBaseTable.SIMULATE_INCOMPLETE_COLUMN_PRUNING}' = 'true')") {
    +      val table = spark.sessionState.catalogManager.catalog("testcat")
    +        .asInstanceOf[InMemoryTableCatalog].liveTable(Identifier.of(Array.empty, "t"))
    +        .asInstanceOf[InMemoryBaseTable]
    +      val df = spark.readStream.table(tbl).select("data")
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        // The scan that does not read "data" is replaced by one of all the columns, and the
    +        // stream of the replaced scan is stopped.
    +        assertReadSchema("id", "data", "extra"),
    +        AssertOnQuery(_ => table.stoppedMicroBatchStreams.get() == 1),
    +        CheckAnswer(Row("a"), Row("b")))
    +    }
    +  }
    +
    +  test("read the event-time column of a watermark that the query does not output") {
    +    withTable(tbl) {
    +      sql(s"CREATE TABLE $tbl (id bigint, data string, ts timestamp)")
    +      sql(s"INSERT INTO $tbl VALUES " +
    +        "(1, 'a', timestamp_seconds(0)), (2, 'b', timestamp_seconds(10))")
    +      val df = spark.readStream.table(tbl).withWatermark("ts", "5 seconds").select("data")
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        assertReadSchema("data", "ts"),
    +        CheckAnswer(Row("a"), Row("b")),
    +        // The watermark gets the event times of the rows.
    +        AssertOnQuery { query =>
    +          query.recentProgress.filter(_.numInputRows > 0).map(_.eventTime.get("max")).toSeq ==
    +            Seq("1970-01-01T00:00:10.000Z")
    +        })
    +    }
    +  }
    +
    +  test("read only the columns of a stream-static join") {
    +    withSourceTable() {
    +      val static = spark.range(2, 4).toDF("sid")
    +      val source = spark.readStream.table(tbl)
    +      val df = source.join(static, source("id") === static("sid")).select("data")
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        assertReadSchema("id", "data"),
    +        CheckAnswer(Row("b")),
    +        insert("(3, 'c', 30), (4, 'd', 40)"),
    +        ProcessAllAvailable(),
    +        CheckAnswer(Row("b"), Row("c")))
    +    }
    +  }
    +
    +  test("read only the columns of each side of a stream-stream join, also after a restart") {
    +    withSourceTable() {
    +      val left = spark.readStream.table(tbl).select("id", "data")
    +      val right = spark.readStream.table(tbl).selectExpr("id AS rid", "extra")
    +      val df = left.join(right, left("id") === right("rid")).select("data", "extra")
    +      val readSchemas = AssertOnQuery { query =>
    +        val schemas = query.logicalPlan.collect {
    +          case relation: StreamingDataSourceV2ScanRelation =>
    +            relation.scan.readSchema().fieldNames.toSeq
    +        }
    +        assert(schemas.sortBy(_.mkString(",")) === Seq(Seq("id", "data"), Seq("id", "extra")))
    +        true
    +      }
    +      testStream(df)(
    +        ProcessAllAvailable(),
    +        readSchemas,
    +        CheckAnswer(Row("a", 10), Row("b", 20)),
    +        StopStream,
    +        insert("(3, 'c', 30)"),

    Nit (P3): This restart inserts only the new key 3, so no row restored from the join state reaches the output, and every restart in the suite keeps pruning on in both runs. Since spark.sql.streaming.v2ColumnPruning.enabled is read at each start and is not pinned in the offset log, every existing checkpoint over a pruning-capable source moves to pruned scans on its first restart after the upgrade, and turning the conf off moves it back. Restarting a stream-stream join and a streaming aggregation across the two values, with new rows whose keys match stored state, would verify that the input layout of the stateful operators is the same in both modes.

    Verification:

  • Compatibility: A stream-stream join and a streaming aggregation restarted with streaming column pruning enabled from a checkpoint written with it disabled, and the reverse, produce the same results as a run without the toggle when new rows match keys held in state.
  • spark-test spark-test commented on code on Oct 30, 2026 15:23 UTC
    Code Review
    docs/streaming/ss-migration-guide.md:1
    @@ -38,6 +38,11 @@ Please refer [Migration Guide: SQL, Datasets and DataFrame](../sql-migration-gui
       To recover, write to a new table location with a new checkpoint location, or rewrite the
       committed files with the partition columns of the table.
     
    +- Since Spark 4.4, the scan of a Data Source V2 streaming source whose scan builder implements
    +  `SupportsPushDownRequiredColumns` only reads the top-level columns that the streaming query
    +  needs, as the scans of batch queries do. Before, it read all the columns of the source. To

    Nit (P3): "as the scans of batch queries do" does not hold for common query shapes. The required columns come from the references of every node of the analyzed plan, in which the analyzer has not collapsed Projects, so spark.readStream.table(t).withColumn("x", lit(1)).select("data") reads every column of t, while V2ScanRelationPushDown prunes the batch scan of the same query to data. Chained selects, SELECT * subqueries and the time and session window rewrites behave the same way, and the conf doc in SQLConf makes the same claim ("as for batch scans"). Could both texts say that the scan reads the top-level columns that the analyzed query references?

    Verification:

  • Inspection: The migration-guide entry and the conf documentation describe the pruned columns as those that the analyzed streaming query references and no longer state that streaming scans prune as batch scans do.
  • spark-test spark-test commented on code on Oct 30, 2026 15:23 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:1
    @@ -0,0 +1,117 @@
    +/*
    + * 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.
    + */
    +
    +package org.apache.spark.sql.execution.streaming.runtime
    +
    +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, AttributeSet, NamedExpression}
    +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, Distinct, LogicalPlan, SetOperation, UnionBase}
    +import org.apache.spark.sql.catalyst.types.DataTypeUtils
    +import org.apache.spark.sql.connector.catalog.SupportsRead
    +import org.apache.spark.sql.connector.read.{Scan, SupportsPushDownRequiredColumns}
    +import org.apache.spark.sql.connector.read.streaming.SparkDataStream
    +import org.apache.spark.sql.util.CaseInsensitiveStringMap
    +
    +/**
    + * Prunes the top-level columns that the scans of Data Source V2 streaming sources read to those
    + * that a streaming query needs, as `V2ScanRelationPushDown` does for batch scans. The scan of a
    + * streaming source is built once, when the query starts, from its analyzed plan, so the required
    + * columns are taken from that plan: the optimizer prunes the columns of each micro-batch further,
    + * so stateful operators keep getting the same columns as without this pruning.
    + */
    +private[sql] object StreamingV2ColumnPruning {
    +
    +  /**
    +   * Returns the attributes of its sources that a query needs: those in its output, those that its
    +   * operators reference, and every column of the children of the operators that need all of them,
    +   * such as a distinct, or that map the columns of a child to their output by position rather
    +   * than by attribute, such as a union of any kind or the definition of a common table expression.
    +   */
    +  def requiredAttributes(plan: LogicalPlan): AttributeSet = {
    +    var required = plan.outputSet
    +    plan.foreach { node =>
    +      required ++= node.references
    +      val needsAllColumns = node match {
    +        case _: UnionBase | _: SetOperation | _: Distinct | _: CTERelationDef => true
    +        case _ => mapsColumnsByPosition(node)
    +      }
    +      if (needsAllColumns) {
    +        node.children.foreach(child => required ++= child.outputSet)
    +      }
    +    }
    +    required
    +  }
    +
    +  /**
    +   * Returns whether a node outputs attributes that are neither of its children, nor produced or
    +   * defined by its expressions, which it then maps from the columns of its children by position.
    +   */
    +  private def mapsColumnsByPosition(node: LogicalPlan): Boolean = node.children.nonEmpty && {
    +    val known = AttributeSet(node.children.flatMap(_.output)) ++ node.producedAttributes ++
    +      AttributeSet(node.expressions.collect { case named: NamedExpression => named.toAttribute })
    +    node.output.exists(attribute => !known.contains(attribute))
    +  }
    +
    +  /**
    +   * Builds the scan of a streaming source that reads the columns of `output` in `required`, when
    +   * its scan builder supports column pruning, and creates its stream with `createStream`.
    +   * Returns the scan, its stream and its output: the columns of `output` that it reads, in the
    +   * order of its read schema when the scan prunes them, and otherwise `output` as it is. A scan
    +   * that does not read the required columns, as named in `output`, is replaced by one of all the
    +   * columns, as without pruning.
    +   *
    +   * The read schema of the scan is asked once its stream is created, since a scan may only know
    +   * then what it reads for a stream.
    +   *
    +   * @param output the output of the source, with the metadata columns that the query reads, which
    +   *               the analyzer added to it
    +   * @param required the attributes that the query needs, or None to read all the columns
    +   */
    +  def buildScan[S <: SparkDataStream](
    +      table: SupportsRead,
    +      options: CaseInsensitiveStringMap,
    +      output: Seq[AttributeReference],
    +      required: Option[AttributeSet])(
    +      createStream: Scan => S): (Scan, S, Seq[AttributeReference]) = {
    +    def build(columns: Seq[AttributeReference]): (Scan, Boolean) = {
    +      val builder = table.newScanBuilder(options)
    +      val prunes = builder match {
    +        case pruning: SupportsPushDownRequiredColumns =>
    +          pruning.pruneColumns(DataTypeUtils.fromAttributes(columns))
    +          true
    +        case _ => false
    +      }
    +      (builder.build(), prunes)
    +    }
    +    val requiredOutput = required.map(r => output.filter(r.contains)).getOrElse(output)
    +    val (scan, prunes) = build(requiredOutput)
    +    val stream = createStream(scan)
    +    if (!prunes || requiredOutput.length == output.length) {
    +      (scan, stream, output)
    +    } else {
    +      val byName = output.map(attribute => attribute.name -> attribute).toMap
    +      val readSchema = scan.readSchema()
    +      val scanOutput = readSchema.fieldNames.toSeq.flatMap(byName.get)
    +      if (scanOutput.length == readSchema.length && requiredOutput.forall(scanOutput.contains)) {
    +        (scan, stream, scanOutput)
    +      } else {
    +        stream.stop()

    Nit (P3): The scan is replaced without any log, both when the read schema lacks a required column and when it has a field that does not map to output, such as a name in another case or an extra internal column: byName is an exact-case map, so scanOutput.length == readSchema.length then fails. Such a connector loses pruning and costs an extra builder, scan and stream at every start, and nothing tells its owner. A warning that names the source, the missing required columns and the unmapped read-schema fields would make this diagnosable; a warning that lists only the missing columns would show nothing for an extra field. The doc of this method (lines 72-74) also mentions only the first trigger.

    Verification:

  • Behavior: Starting a query over a scan whose read schema lacks a required column, or has a field that does not map to the output, logs one warning that names the source and those columns, and the query still reads all the columns.
  • spark-test spark-test commented on code on Oct 30, 2026 15:23 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:1
    @@ -0,0 +1,117 @@
    +/*
    + * 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.
    + */
    +
    +package org.apache.spark.sql.execution.streaming.runtime
    +
    +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, AttributeSet, NamedExpression}
    +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, Distinct, LogicalPlan, SetOperation, UnionBase}
    +import org.apache.spark.sql.catalyst.types.DataTypeUtils
    +import org.apache.spark.sql.connector.catalog.SupportsRead
    +import org.apache.spark.sql.connector.read.{Scan, SupportsPushDownRequiredColumns}
    +import org.apache.spark.sql.connector.read.streaming.SparkDataStream
    +import org.apache.spark.sql.util.CaseInsensitiveStringMap
    +
    +/**
    + * Prunes the top-level columns that the scans of Data Source V2 streaming sources read to those
    + * that a streaming query needs, as `V2ScanRelationPushDown` does for batch scans. The scan of a
    + * streaming source is built once, when the query starts, from its analyzed plan, so the required
    + * columns are taken from that plan: the optimizer prunes the columns of each micro-batch further,
    + * so stateful operators keep getting the same columns as without this pruning.
    + */
    +private[sql] object StreamingV2ColumnPruning {
    +
    +  /**
    +   * Returns the attributes of its sources that a query needs: those in its output, those that its
    +   * operators reference, and every column of the children of the operators that need all of them,
    +   * such as a distinct, or that map the columns of a child to their output by position rather
    +   * than by attribute, such as a union of any kind or the definition of a common table expression.
    +   */
    +  def requiredAttributes(plan: LogicalPlan): AttributeSet = {
    +    var required = plan.outputSet
    +    plan.foreach { node =>
    +      required ++= node.references

    Nit (P3): AttributeSet.++ builds a new set from baseSet ++ other.baseSet, so each required ++= ... here and at line 52 copies everything accumulated so far, which makes the pass O(nodes x attributes) at every query start. This only matters for wide plans with many sources, such as a union of many wide streams, and the fix is local: collect the output set, the references of each node and the child output sets of the all-columns nodes, then combine them once with AttributeSet.fromAttributeSets, as QueryPlan.inputSet does. The membership and order stay the same.

    Verification:

  • Behavior: The required attributes, and therefore the read schemas of every existing pruning scenario, are unchanged.
  • spark-test spark-test commented on code on Oct 30, 2026 15:23 UTC
    Code Review
    sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:1
    @@ -0,0 +1,117 @@
    +/*
    + * 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.
    + */
    +
    +package org.apache.spark.sql.execution.streaming.runtime
    +
    +import org.apache.spark.sql.catalyst.expressions.{AttributeReference, AttributeSet, NamedExpression}
    +import org.apache.spark.sql.catalyst.plans.logical.{CTERelationDef, Distinct, LogicalPlan, SetOperation, UnionBase}
    +import org.apache.spark.sql.catalyst.types.DataTypeUtils
    +import org.apache.spark.sql.connector.catalog.SupportsRead
    +import org.apache.spark.sql.connector.read.{Scan, SupportsPushDownRequiredColumns}
    +import org.apache.spark.sql.connector.read.streaming.SparkDataStream
    +import org.apache.spark.sql.util.CaseInsensitiveStringMap
    +
    +/**
    + * Prunes the top-level columns that the scans of Data Source V2 streaming sources read to those
    + * that a streaming query needs, as `V2ScanRelationPushDown` does for batch scans. The scan of a
    + * streaming source is built once, when the query starts, from its analyzed plan, so the required
    + * columns are taken from that plan: the optimizer prunes the columns of each micro-batch further,
    + * so stateful operators keep getting the same columns as without this pruning.
    + */
    +private[sql] object StreamingV2ColumnPruning {
    +
    +  /**
    +   * Returns the attributes of its sources that a query needs: those in its output, those that its
    +   * operators reference, and every column of the children of the operators that need all of them,
    +   * such as a distinct, or that map the columns of a child to their output by position rather
    +   * than by attribute, such as a union of any kind or the definition of a common table expression.
    +   */
    +  def requiredAttributes(plan: LogicalPlan): AttributeSet = {
    +    var required = plan.outputSet
    +    plan.foreach { node =>
    +      required ++= node.references
    +      val needsAllColumns = node match {
    +        case _: UnionBase | _: SetOperation | _: Distinct | _: CTERelationDef => true
    +        case _ => mapsColumnsByPosition(node)
    +      }
    +      if (needsAllColumns) {
    +        node.children.foreach(child => required ++= child.outputSet)
    +      }
    +    }
    +    required
    +  }
    +
    +  /**
    +   * Returns whether a node outputs attributes that are neither of its children, nor produced or
    +   * defined by its expressions, which it then maps from the columns of its children by position.
    +   */
    +  private def mapsColumnsByPosition(node: LogicalPlan): Boolean = node.children.nonEmpty && {
    +    val known = AttributeSet(node.children.flatMap(_.output)) ++ node.producedAttributes ++
    +      AttributeSet(node.expressions.collect { case named: NamedExpression => named.toAttribute })
    +    node.output.exists(attribute => !known.contains(attribute))
    +  }
    +
    +  /**
    +   * Builds the scan of a streaming source that reads the columns of `output` in `required`, when
    +   * its scan builder supports column pruning, and creates its stream with `createStream`.
    +   * Returns the scan, its stream and its output: the columns of `output` that it reads, in the
    +   * order of its read schema when the scan prunes them, and otherwise `output` as it is. A scan
    +   * that does not read the required columns, as named in `output`, is replaced by one of all the
    +   * columns, as without pruning.
    +   *
    +   * The read schema of the scan is asked once its stream is created, since a scan may only know
    +   * then what it reads for a stream.
    +   *
    +   * @param output the output of the source, with the metadata columns that the query reads, which
    +   *               the analyzer added to it
    +   * @param required the attributes that the query needs, or None to read all the columns
    +   */
    +  def buildScan[S <: SparkDataStream](
    +      table: SupportsRead,
    +      options: CaseInsensitiveStringMap,
    +      output: Seq[AttributeReference],
    +      required: Option[AttributeSet])(
    +      createStream: Scan => S): (Scan, S, Seq[AttributeReference]) = {
    +    def build(columns: Seq[AttributeReference]): (Scan, Boolean) = {
    +      val builder = table.newScanBuilder(options)
    +      val prunes = builder match {
    +        case pruning: SupportsPushDownRequiredColumns =>
    +          pruning.pruneColumns(DataTypeUtils.fromAttributes(columns))
    +          true
    +        case _ => false
    +      }
    +      (builder.build(), prunes)
    +    }
    +    val requiredOutput = required.map(r => output.filter(r.contains)).getOrElse(output)

    Nit (P3): When the query needs no source column, as spark.readStream.table(t).groupBy().count() or select(lit(1)) do, requiredOutput is empty: pruneColumns gets an empty struct, the forall at line 108 accepts an empty read schema, and both relations get no output. The engine never built an empty streaming scan before, and every test in StreamingV2ColumnPruningSuite needs at least one source column. A regression on this path, in buildScan, the per-batch LocalRelation substitution or a reader, would go unnoticed. A global count and a constant projection, including a restart, would cover it.

    Verification:

  • Behavior: groupBy().count() and a constant projection over a pruning-capable streaming source read no source column and return the right counts and rows across micro-batches and after a restart.
  • zikangh zikangh commented on Oct 30, 2026 23:57 UTC
    Contributor

    Hi @HeartSaVioR & @HyukjinKwon:

    The reason streaming cannot perform column pruning during optimizer is due to a fundamental streaming lifecycle issue:

  • We need MicrobatchStream to call latestOffset (this needs to happen before Optimizer)

  • to get MicrobatchStream, we need Scan scan = ScanBuilder.build()

  • By the time the optimizer runs, the Scan is already built and frozen, we cannot do pushdowns anymore (those require a ScanBuilder).
  • it is very tricky to fix this, but my preference would be to fix it properly (not duplicating the optimizer logic).

    Reviewers
    Assignees
    HyukjinKwon HyukjinKwon
    Labels
    risk: low confidence: 92% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 50.6% (MEDIUM) · Higher = larger blast radius
    50.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 92% · Lower = rushed or shallow review
    92%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4% · Safe to merge
    4%
    Repository