[SPARK-60734][SS] Prune the columns that the scans of Data Source V2 streaming sources read #59943
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 -->
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.
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:
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)
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:
batchSchema, which creates a batch planner for a data source that may not support batch scans (L91-92).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.
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:
Union does.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.
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?
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")))
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?
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?
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.
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))) {
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)
}
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.)
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 callpruneColumns(output.toStructType)whereoutputis 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?
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.
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.
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:
start() returns.readSchema() failure leaves the created stream running.Questions for the author follow.
Review-level concerns
Cross-cutting observations
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.
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)
sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ColumnPruningSuite.scala:128 — unresolved in existing discussion.Nit (P3)
sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/MicroBatchExecution.scala:265 — see inline.sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:106 — unresolved in existing discussion.sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/columnar/ColumnarTable.scala:186 — unresolved in existing discussion.sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/continuous/ContinuousExecution.scala:104 — see inline.sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingV2ColumnPruningSuite.scala:218 — see inline.docs/streaming/ss-migration-guide.md:43 — see inline.sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:111 — see inline.sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:108 — unresolved in existing discussion.sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:46 — see inline.sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/StreamingV2ColumnPruning.scala:99 — see inline.Existing discussions
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"} -->
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:
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:
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:
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:
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:
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:
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:
Hi @HeartSaVioR & @HyukjinKwon:
The reason streaming cannot perform column pruning during optimizer is due to a fundamental streaming lifecycle issue:
Scan scan = ScanBuilder.build()
it is very tricky to fix this, but my preference would be to fix it properly (not duplicating the optimizer logic).
dongjoon-hyun
HyukjinKwon
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, asV2ScanRelationPushDowndoes 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.MicroBatchExecutionandContinuousExecutioncallpruneColumnson the scan builder with those columns, and use thereadSchemathat the scan returns, so a source that reads more columns than required still works. A scan whosereadSchemadoes not have the required columns is replaced by a scan of all the columns, and the stream of the replaced scan is stopped. TheTODO: operator pushdownstays, 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.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
SupportsPushDownRequiredColumnsread only the columns that they need. So a third-party streaming source of this kind now gets a pruned schema inpruneColumns, 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 thatspark.sql.streaming.v2ColumnPruning.enabled=falserestores the previous behavior.How was this patch tested?
New
StreamingV2ColumnPruningSuite, which checks thereadSchemaof the streaming scans of an in-memory table, whose micro-batch reader now reads only the columns of that schema: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,NativeDataSourceSuiteandDataSourceV2Suitepass 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.