comphead commented on code in PR #7826: URL: https://github.com/apache/datafusion-comet/pull/7826#discussion_r4778317759
########## docs/source/user-guide/latest/compatibility/index.md: ########## @@ -169,6 +169,15 @@ the first remain affected. These limitations and the investigation of already-or `TakeOrderedAndProject` inputs are tracked in [#7147](https://github.com/apache/datafusion-comet/issues/7147). +Spark can also evaluate rows that a `LIMIT` doesn't return. Under a root `LIMIT`, when Spark runs +`explode` or `posexplode` and the projection above it in one codegen stage, it finishes the current +array, so a later element of that array can raise an error even after the array supplied enough +rows. Comet does the same for a deterministic projection without user-defined functions directly +over `explode` or `posexplode`. Other plans can still return a result where Spark raises, such as a Review Comment: This reads as covering every deterministic projection without user-defined functions directly over `explode` or `posexplode`. `fusedExplodeProjection` also requires ANSI mode, whole-stage codegen with the default `spark.sql.codegen.hugeMethodLimit` or higher, a projection that can raise, and a generator that reads from a file scan or a range. A generator over a shuffle read or a V2 scan keeps the cap and still returns a row where Spark raises. Could the note name the conditions that remain after the other comments here are resolved? ########## spark/src/main/scala/org/apache/comet/rules/CometExecRule.scala: ########## @@ -795,6 +814,66 @@ case class CometExecRule(session: SparkSession, queryStagePrep: Boolean = false) case _ => false } + private def fusedExplodeProjection(child: SparkPlan): Boolean = { + def original(p: SparkPlan): SparkPlan = p match { + case c: CometExec => c.originalPlan + case other => other + } + + @tailrec + def singleInputRow(p: SparkPlan): Boolean = p match { + case c: CometExec => singleInputRow(c.originalPlan) + case f: FilterExec => singleInputRow(f.child) + case p: ProjectExec => singleInputRow(p.child) + case _: RangeExec | _: FileSourceScanExec | _: CometScanExec => true + case _ => false + } + + // A chunk whose projection raises is projected again to find the first row that raises, + // so the projection must give the same answer twice. + def replayable(exprs: Seq[Expression]): Boolean = + exprs.forall(_.deterministic) && !exprs.exists(_.exists { + case _: UserDefinedExpression | _: NativeUdfCall | _: InvokeLike => true + case e => e.stateful + }) + + // A projection that cannot raise needs only the rows the limit returns. + def canRaise(exprs: Seq[NamedExpression]): Boolean = exprs.exists { + case a: Alias => !QueryPlanSerde.cannotFail(a.child) + case e => !QueryPlanSerde.cannotFail(e) + } + + def canFuse(p: CodegenSupport): Boolean = + p.supportCodegen && !WholeStageCodegenExec.isTooManyFields(conf, p.schema) && + !p.children.exists(c => WholeStageCodegenExec.isTooManyFields(conf, c.schema)) && + !p.expressions.exists(_.exists { + case _: LeafExpression => false + case _: CodegenFallback => true + case _ => false + }) + + original(child) match { + case p: ProjectExec + if conf.ansiEnabled && conf.wholeStageEnabled && Review Comment: `canRaise` goes through `QueryPlanSerde.cannotFail`, which already reads each expression's eval mode, so an add or a cast with ANSI off already counts as safe. The extra `conf.ansiEnabled` keeps the cap for expressions that raise in every mode, the ones `raisesInAnyMode` lists, such as `element_at(array, 0)`, `slice` with a zero start, or `sequence` with mismatched bounds. For example, with ANSI off and `a = array('1', '0')`, I expect `SELECT element_at(array(10, 20), CAST(x AS INT)) FROM t LATERAL VIEW explode(a) e AS x LIMIT 1` to raise `INVALID_INDEX_OF_ZERO` in Spark with codegen, while this rule keeps the cap and Comet returns a row. Dropping the condition covers both modes. I did not run this. ########## native/operators/src/explode.rs: ########## @@ -305,6 +334,207 @@ impl ExecutionPlan for ExplodeExec { } } +/// Evaluate a projection through the end of the fetched explode row, even if it spans batches. +#[derive(Debug)] +pub struct ExplodeProjectionExec { Review Comment: The module header says this fork holds only performance work and can be deleted once that is upstreamed. `source_row_fetch` and `ExplodeProjectionExec` are now behavior that DataFusion's `UnnestExec` and `ProjectionExec` lack, so going back to `UnnestExec` would silently drop this fix. Please update the "Why this fork exists" and "Deleting this file" sections. Since `ExplodeProjectionExec` is a projection, `native/operators/src/projection.rs` next to `CometProjectionExec` may be a better home. ########## native/operators/src/explode.rs: ########## @@ -305,6 +334,207 @@ impl ExecutionPlan for ExplodeExec { } } +/// Evaluate a projection through the end of the fetched explode row, even if it spans batches. +#[derive(Debug)] +pub struct ExplodeProjectionExec { + project: ProjectionExec, + fetch: usize, + metrics: ExecutionPlanMetricsSet, +} + +impl ExplodeProjectionExec { + pub fn wrap(project: ProjectionExec) -> Arc<dyn ExecutionPlan> { + match project + .input() + .downcast_ref::<ExplodeExec>() + .and_then(|e| e.source_row_fetch) + { + Some(fetch) => Arc::new(Self { + project, + fetch, + metrics: ExecutionPlanMetricsSet::new(), + }), + None => Arc::new(project), + } + } +} + +impl DisplayAs for ExplodeProjectionExec { + fn fmt_as(&self, t: DisplayFormatType, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "FinishExplodeRow(fetch={}): ", self.fetch)?; + self.project.fmt_as(t, f) + } +} + +impl ExecutionPlan for ExplodeProjectionExec { + fn name(&self) -> &str { + "ExplodeProjectionExec" + } + + fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> { + self.project.children() + } + + fn properties(&self) -> &Arc<PlanProperties> { + self.project.properties() + } + + fn metrics(&self) -> Option<MetricsSet> { + Some(self.metrics.clone_inner()) + } + + fn apply_expressions( + &self, + f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>, + ) -> Result<TreeNodeRecursion> { + self.project.apply_expressions(f) + } + + fn with_new_children( + self: Arc<Self>, + children: Vec<Arc<dyn ExecutionPlan>>, + ) -> Result<Arc<dyn ExecutionPlan>> { + let [child] = children.as_slice() else { + return internal_err!("ExplodeProjectionExec expects one child"); + }; + if child + .downcast_ref::<ExplodeExec>() + .and_then(|e| e.source_row_fetch) + != Some(self.fetch) + { + return internal_err!("ExplodeProjectionExec lost its bounded explode input"); + } + Ok(Self::wrap(ProjectionExec::try_new( + self.project.expr().iter().cloned(), + Arc::clone(child), + )?)) + } + + fn execute( + &self, + partition: usize, + context: Arc<TaskContext>, + ) -> Result<SendableRecordBatchStream> { + let Some(explode) = self.project.input().downcast_ref::<ExplodeExec>() else { + return internal_err!("Expected an explode below the projection"); + }; + let projector = self + .project + .projection_expr() + .make_projector(&explode.schema())? + .with_metrics(&self.metrics, partition); + let reservation = MemoryConsumer::new(format!("ExplodeProjectionExec[{partition}]")) + .register(context.memory_pool()); + let state = ExplodeProjectionStream { + input: explode.explode_stream(partition, context)?, + projector, + remaining: self.fetch, + buffered: VecDeque::new(), + buffered_memory: RecordBatchMemoryCounter::new(), + reservation, + metrics: BaselineMetrics::new(&self.metrics, partition), + }; + let output = stream::try_unfold(state, |mut state| async move { + let batch = state.next_batch().await?; + if let Some(batch) = &batch { + batch.record_output(&state.metrics); + } + Ok(batch.map(|batch| (batch, state))) + }); + Ok(Box::pin(RecordBatchStreamAdapter::new( + self.schema(), + output, + ))) + } +} + +struct ExplodeProjectionStream { + input: ExplodeStream, + projector: Projector, + remaining: usize, + /// Exploded rows the limit takes from an array that spans chunks, held until the whole array + /// has been projected without an error. + buffered: VecDeque<RecordBatch>, + /// The batches in `buffered` can be slices of the same buffers, so each buffer is counted + /// once, and the reservation is freed when `buffered` empties. + buffered_memory: RecordBatchMemoryCounter, + reservation: MemoryReservation, + metrics: BaselineMetrics, +} + +impl ExplodeProjectionStream { + /// Projects `chunk`. When that raises, returns the error of the first row that raises, + /// since Spark projects one row at a time: a later row's error from one expression must not + /// win over an earlier row's error from another. A prefix of the chunk raises once it holds + /// that row, so a binary search over prefix lengths finds it. + fn project(&self, chunk: &RecordBatch) -> Result<RecordBatch> { + let error = match self.projector.project_batch(chunk) { + Ok(projected) => return Ok(projected), + Err(error) => error, + }; + // The prefix of length `clean` projects without an error, and the prefix of length + // `raising` raises. + let mut clean = 0; + let mut raising = chunk.num_rows(); + while raising - clean > 1 { + let length = clean + (raising - clean) / 2; + match self.projector.project_batch(&chunk.slice(0, length)) { + Ok(_) => clean = length, + Err(_) => raising = length, + } + } + match self.projector.project_batch(&chunk.slice(clean, 1)) { + Err(row_error) => Err(row_error), + // The chunk raised, but the row after the clean prefix doesn't raise alone. + Ok(_) => Err(error), + } + } Review Comment: This bisection decides which error wins when two expressions fail on different rows, which is not specific to `LIMIT`. With no `LIMIT`, `SELECT CAST(x AS INT), 10 DIV (length(x) - 1) FROM explode_limit LATERAL VIEW explode(a) e AS x WHERE g = 'order'` evaluates the `CAST` column over the whole batch first. I expect Comet on main to report `CAST_INVALID_INPUT` there while Spark reports `DIVIDE_BY_ZERO`, and every `CometProjectExec` has the same difference. I did not run this. Could the PR drop the bisection and the `order` case in `limit_explode.sql`, and track error order for all projections in its own issue? `project` would then be a single `project_batch` call. ########## spark/src/main/scala/org/apache/comet/rules/CometExecRule.scala: ########## @@ -795,6 +814,66 @@ case class CometExecRule(session: SparkSession, queryStagePrep: Boolean = false) case _ => false } + private def fusedExplodeProjection(child: SparkPlan): Boolean = { + def original(p: SparkPlan): SparkPlan = p match { + case c: CometExec => c.originalPlan + case other => other + } + + @tailrec + def singleInputRow(p: SparkPlan): Boolean = p match { + case c: CometExec => singleInputRow(c.originalPlan) + case f: FilterExec => singleInputRow(f.child) + case p: ProjectExec => singleInputRow(p.child) + case _: RangeExec | _: FileSourceScanExec | _: CometScanExec => true + case _ => false Review Comment: Why only a file scan or a range below the generator? Spark fuses `GenerateExec` the same way over an `InputAdapter` for a shuffle read, a `BatchScanExec` such as Iceberg, or a join in the same stage, and the generated loop still finishes the array there. If one of those breaks the fetch, a comment that says which one and why would help. If none does, the generator's child could be anything Spark puts in the same codegen stage. `singleInputRow` also reads as a row property rather than a check on the source operator. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
