HeartSaVioR commented on code in PR #59910: URL: https://github.com/apache/spark/pull/59910#discussion_r4532140099
########## sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/PrepareExternalLookupJoin.scala: ########## @@ -0,0 +1,334 @@ +/* + * 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.datasources.v2 + +import java.util.{Collections, IdentityHashMap} + +import org.apache.spark.sql.catalyst.expressions.{Alias, And, Attribute, AttributeMap, Coalesce, + EqualNullSafe, EqualTo, Expression, ExprUtils, ExternalUserDefinedFunction, Literal, + PredicateHelper, PythonUDF} +import org.apache.spark.sql.catalyst.plans.LeftOuter +import org.apache.spark.sql.catalyst.plans.logical.{ExternalLookupJoin, ExternalLookupKeyTypes, + Filter, LogicalPlan, PreparedExternalLookupJoin, Project} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.trees.TreePattern.{DATA_SOURCE_V2_RELATION, EXTERNAL_LOOKUP_JOIN} +import org.apache.spark.sql.catalyst.util.CharVarcharUtils +import org.apache.spark.sql.connector.catalog.{SupportsRead, TableCapability} +import org.apache.spark.sql.connector.expressions.{Expression => V2Expression, FieldReference} +import org.apache.spark.sql.connector.expressions.filter.{Predicate => V2Predicate} +import org.apache.spark.sql.connector.read.{LookupParameter, SupportsExternalLookup} +import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryErrorsBase} +import org.apache.spark.sql.types.{ArrayType, BooleanType, DataType, MapType, StructType} + +/** Finalizes an optimized external lookup side immediately before ordinary V2 scan preparation. */ +object PrepareExternalLookupJoin extends Rule[LogicalPlan] with PredicateHelper + with QueryErrorsBase { + override def apply(plan: LogicalPlan): LogicalPlan = { + val prepared = plan.transformUpWithPruning(_.containsPattern(EXTERNAL_LOOKUP_JOIN)) { + case join: ExternalLookupJoin if provablyEmpty(join) => emptyJoinResult(join) + case join: ExternalLookupJoin => prepare(join) + } + // Prepared lookup joins no longer contain their lookup relation, so a lookup-only table that + // is still read here cannot run. + if (prepared.containsPattern(DATA_SOURCE_V2_RELATION)) { + prepared.foreach { node => + ExternalLookupRelations.lookupOnlyTable(node).foreach { table => + throw QueryCompilationErrors.unsupportedBatchReadError(table) + } + } + } + prepared + } + + // The optimizer folds `WHERE false` on the lookup side into an empty relation, and a condition + // such as `s.id = r.id AND false` into `false`. Such a join needs no connector call. + private def provablyEmpty(join: ExternalLookupJoin): Boolean = + join.right.maxRows.contains(0L) || (join.condition match { + case Some(Literal(value, BooleanType)) => value == null || value == false + case _ => false + }) + + private def emptyJoinResult(join: ExternalLookupJoin): LogicalPlan = { + val nullLookupColumns = join.right.output.map { attr => + Alias(Literal(null, attr.dataType), attr.name)(attr.exprId) + } + val unmatched = Project(join.left.output ++ nullLookupColumns, join.left) + join.joinType match { + case LeftOuter => unmatched + // The stream side is kept under a false filter rather than replaced by an empty relation, + // so that its sources, watermarks and stateful operators still run in every micro-batch. + // PruneFilters decides whether a streaming subplan may be pruned. + case _ => Filter(Literal.FalseLiteral, unmatched) + } + } + + private def prepare(join: ExternalLookupJoin): LogicalPlan = { + val relation = extractLookupPlan(join.right).getOrElse { + throw QueryCompilationErrors.unsupportedExternalLookupJoinError("LOOKUP_PLAN") + } + val tableName = relation.table.name() + val supportsRead = relation.table match { + case table: SupportsRead + if table.capabilities().contains(TableCapability.EXTERNAL_LOOKUP) => table + case _ => + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "TABLE", Map("table" -> toSQLId(tableName))) + } + val conjuncts = join.condition.toSeq.flatMap(splitConjunctivePredicates) + // A Python or external UDF over lookup columns cannot run in the residual. The rules that move + // one out of a join condition match only Join and run later, so this rule does it: an inner + // join evaluates the conjunct in a filter above the join, and an outer join is rejected. + if (join.joinType == LeftOuter) { + conjuncts.flatMap(lookupSideUDF(join, _)).headOption.foreach { + case _: ExternalUserDefinedFunction => + throw QueryCompilationErrors.useExternalUDFInJoinConditionUnsupportedError(join.joinType) + case _ => + throw QueryCompilationErrors.usePythonUDFInJoinConditionUnsupportedError(join.joinType) + } + } + val offeredCandidates = conjuncts.zipWithIndex.collect { + case (EqualTo(leftExpr, rightAttr: Attribute), index) + if isLookupEquality(join, leftExpr, rightAttr) => + OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false) + case (EqualTo(rightAttr: Attribute, leftExpr), index) + if isLookupEquality(join, leftExpr, rightAttr) => + OfferedLookupPredicate(leftExpr, rightAttr, index, "=", false) + } + if (offeredCandidates.isEmpty) { + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "NO_LOOKUP_CANDIDATE", Map("table" -> toSQLId(tableName))) + } + + val scanBuilder = supportsRead.newScanBuilder(relation.options) + val lookupBuilder = scanBuilder match { + case builder: SupportsExternalLookup => builder + case _ => + throw QueryCompilationErrors.unsupportedExternalLookupJoinError( + "SCAN_BUILDER", Map("table" -> toSQLId(tableName))) + } + // A column is offered under the table's name for it. Under case-insensitive analysis, the + // condition may spell it in another case, as `ID` for `id`, with the same exprId; filter + // pushdown renames it the same way, with DataSourceStrategy.normalizeExprs. + val columnNames = AttributeMap(relation.output.map(attr => attr -> attr.name)) + val offeredPredicates = offeredCandidates.map { candidate => + new V2Predicate(candidate.predicateName, Array[V2Expression]( + FieldReference.column(columnNames(candidate.projectedField)), + new LookupParameter(candidate.parameter.dataType))) + }.toArray + val selectedPredicates = selectedCandidates(tableName, offeredPredicates, offeredCandidates, + lookupBuilder.selectLookupPredicates(offeredPredicates)) + val selectedConjuncts = selectedPredicates.map(_.conjunctIndex).toSet + // As a hash join matches its keys before it evaluates its other conditions, the residual + // evaluates the equalities between the two sides first, together with the conjuncts that + // cannot fail. A conjunct that can fail then runs only for rows that pass them. Each group + // keeps the written order. + val (residualConjuncts, joinFilter) = conjuncts.zipWithIndex.collect { + case (conjunct, index) if !selectedConjuncts.contains(index) => conjunct + }.partition(lookupSideUDF(join, _).isEmpty) + val (residualFirst, residualRest) = residualConjuncts.partition { conjunct => + isJoinKeyEquality(join, conjunct) || ExprUtils.canEvaluateUnconditionally(conjunct) Review Comment: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Thanks for the example. This PR doesn't change, because the ordinary join behaves this way only through predicate pushdown, which the stack adds in #60198. There, a deterministic conjunct of the condition that reads only lookup columns moves onto the lookup side, as for an ordinary join, so your `RLIKE` guard runs as a lookup-side stage before the residual. A new test in #60198 ([6d508fd7d9b](https://github.com/apache/spark/commit/6d508fd7d9b7100414eb18ff5c6388d6a24f8b69)) runs your example under ANSI mode: the connector selects only `id = ?` and returns the codes `7` and `abc`. Inner and left outer joins, with the guard written before or after the cast key, return the right rows, and no task fails. Until then, this PR doesn't push predicates, as its scope says. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/joins/ExternalLookupJoinEvaluatorFactory.scala: ########## @@ -0,0 +1,656 @@ +/* + * 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.joins + +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference} + +import scala.collection.mutable + +import org.apache.spark.{PartitionEvaluator, PartitionEvaluatorFactory, SparkException, + SparkIllegalStateException, TaskContext} +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.{Attribute, Expression, GenericInternalRow, + JoinedRow, Predicate, SpecializedGetters, UnsafeProjection, UnsafeRow} +import org.apache.spark.sql.catalyst.plans.{Inner, JoinType, LeftOuter} +import org.apache.spark.sql.catalyst.util.ArrayData +import org.apache.spark.sql.connector.metric.CustomTaskMetric +import org.apache.spark.sql.connector.read.{ExternalLookupReader, ExternalLookupReaderFactory, + ExternalLookupResultCursor} +import org.apache.spark.sql.errors.QueryExecutionErrors +import org.apache.spark.sql.execution.metric.{CustomMetrics, SQLMetric} +import org.apache.spark.sql.types.{ArrayType, DataType, Decimal, DecimalType, MapType, + StructType} +import org.apache.spark.util.Utils + +/** + * Creates the partition evaluators of an [[ExternalLookupJoinExec]]. The factory is sent to the + * tasks, so it holds only what they need; the plan node and its scan stay on the driver. + * + * An evaluator joins its partition one batch of up to `maxParameterRowsPerRequest` stream rows at + * a time. For each batch it sends one request with the distinct parameters that can match, and + * streams the connector's result rows into output rows. Parameters are deduplicated per request, + * that is within one batch: a key repeated in a later batch is requested again. + * + * Spark does not trust the connector with the selected lookup predicates: it evaluates + * `lookupKeyCheck` on every row that the connector returns, against the request row that the row + * answers, and drops a row that fails it, before it joins the row. The stream rows that share a + * request row have Spark-equal parameters, so one check serves all of them. + * + * The join condition comes in two parts: `streamCondition` reads only stream columns and is + * evaluated on each stream row before the request, and `residualCondition` is evaluated on the + * joined rows. A stream row that fails `streamCondition` cannot match, so its parameters are not + * sent. + */ +class ExternalLookupJoinEvaluatorFactory( + tableName: String, + lookupParameters: Seq[Expression], + nullSafeParameters: Seq[Boolean], + lookupKeyCheck: Option[Expression], + streamOutput: Seq[Attribute], + lookupInput: Seq[Attribute], + output: Seq[Attribute], + joinType: JoinType, + streamCondition: Option[Expression], + residualCondition: Option[Expression], + readerFactory: ExternalLookupReaderFactory, + maxParameterRowsPerRequest: Int, + maxBatchBytes: Long, + metrics: ExternalLookupJoinMetrics, + readerMetrics: ExternalLookupReaderMetrics) + extends PartitionEvaluatorFactory[InternalRow, InternalRow] { + + require(lookupParameters.length == nullSafeParameters.length, + "Every external lookup parameter must define its null semantics") + + override def createEvaluator(): PartitionEvaluator[InternalRow, InternalRow] = + new ExternalLookupJoinEvaluator + + private class ExternalLookupJoinEvaluator extends PartitionEvaluator[InternalRow, InternalRow] { + override def eval( + partitionIndex: Int, + inputs: Iterator[InternalRow]*): Iterator[InternalRow] = { + assert(inputs.length == 1) + new PartitionJoinIterator(inputs.head, partitionIndex) + } + } + + /** Joins one partition batch by batch, and closes its reader after the last batch. */ + private class PartitionJoinIterator(input: Iterator[InternalRow], partitionIndex: Int) + extends Iterator[InternalRow] { + private val reader = new LookupReader + private val parameters = new LookupParameters(partitionIndex) + private val resultRows = new LookupResultRows + private val joinOutput = new JoinOutput(partitionIndex) + private var batch: Iterator[InternalRow] = Iterator.empty + private var inputExhausted = false + + override def hasNext: Boolean = { + tryAdvance() + batch.hasNext + } + + override def next(): InternalRow = { + tryAdvance() + if (!batch.hasNext) { + throw new SparkIllegalStateException( + errorClass = "INTERNAL_ERROR", + messageParameters = Map("message" -> "External lookup join exhausted")) + } + batch.next() + } + + /** Reads more only when nothing is buffered; safe to call repeatedly. */ + private def tryAdvance(): Unit = { + while (!batch.hasNext && !inputExhausted) { + val rows = readBatch() + if (rows.nonEmpty) { + batch = new BatchJoinIterator(rows, parameters, resultRows, joinOutput, reader) + } + inputExhausted = !input.hasNext + } + if (inputExhausted && !batch.hasNext) reader.close() + } + + private lazy val toUnsafe = UnsafeProjection.create(streamOutput, streamOutput) + + // An inner join emits nothing for a stream row that cannot match, because it fails the stream + // condition or has a null parameter that is not null-safe, as an ordinary inner join filters + // such a row out before it joins. So the row takes no place in a batch and is not copied: it + // counts only as an input row. A left outer join emits it, so a batch keeps it. + private val keepsRowsThatCannotMatch = joinType != Inner + + private def canMatch(row: InternalRow): Boolean = + joinOutput.canMatch(row) && !parameters.matchesNothing(parameters.requestRow(row)) + + // An array, because a batch's rows are read by position for every key, match and output row. + // The batch holds its rows until its request is read, so it stops once their copies reach + // maxBatchBytes, keeping the row that reaches it, as well as at maxParameterRowsPerRequest + // rows. It always keeps one row, when one remains. + private def readBatch(): Array[InternalRow] = { + val rows = mutable.ArrayBuffer.empty[InternalRow] + var bytes = 0L + while (rows.length < maxParameterRowsPerRequest && bytes < maxBatchBytes && input.hasNext) { + val next = input.next() + if (keepsRowsThatCannotMatch || canMatch(next)) { + val row = next match { + case unsafe: UnsafeRow => unsafe.copy() + case other => toUnsafe(other).copy() + } + bytes += row.getSizeInBytes + rows += row + } else { + metrics.inputRows += 1 + } + } + rows.toArray + } + } + + /** The stream rows that share a key, and the one request row sent for them. */ + private case class KeyEntry(requestRow: UnsafeRow, rowIndexes: mutable.ArrayBuffer[Int]) + + /** + * Joins one batch of stream rows. Rows whose parameters are equal under Spark equality share + * one request row, and every result row for a request row that satisfies the selected lookup + * predicates joins all the stream rows sharing it. A stream row is finished, which may emit its + * unmatched output row, once no more result rows can match it. + * + * Output rows are projected into a reused row on `next()`, so the consumer copies the rows it + * retains, as with other join iterators. + */ + private class BatchJoinIterator( + rows: Array[InternalRow], + parameters: LookupParameters, + resultRows: LookupResultRows, + joinOutput: JoinOutput, + reader: LookupReader) extends Iterator[InternalRow] { + metrics.inputRows += rows.length + metrics.inputBatches += 1 + + private val matched = Array.fill(rows.length)(false) + private val finished = mutable.BitSet.empty + // Output rows not yet returned: a stream row index and the lookup row it is joined with. + private val pending = mutable.Queue.empty[(Int, InternalRow)] + + // One entry for each distinct request row that can match, in the order of first occurrence. + // A row that can never match, because it fails the stream condition or has a null parameter, + // is finished right away, and its parameters are not requested. The stream condition is + // checked before the parameters are evaluated, so that it can guard their expressions. + private val keyEntries = { + val entries = mutable.LinkedHashMap.empty[UnsafeRow, KeyEntry] + rows.indices.foreach { index => + lazy val requestRow = parameters.requestRow(rows(index)) + if (!joinOutput.canMatch(rows(index)) || parameters.matchesNothing(requestRow)) { + finish(index) + } else { + entries.get(requestRow) match { + case Some(entry) => entry.rowIndexes += index + case None => + val retained = requestRow.copy() + entries.put(retained, KeyEntry(retained, mutable.ArrayBuffer(index))) + } + } + } + entries.values.toArray + } + + // No connector request, and no reader, when no key can match. + private var cursor: ExternalLookupResultCursor = + if (keyEntries.isEmpty) EmptyLookupCursor + else connectorCall(reader.lookup(keyEntries.map(_.requestRow))) + + override def hasNext: Boolean = { + tryFillPending() + pending.nonEmpty + } + + override def next(): InternalRow = { + tryFillPending() + if (pending.isEmpty) throw new NoSuchElementException("external lookup result") + val (index, lookupRow) = pending.dequeue() + joinOutput.project(rows(index), lookupRow) + } + + /** Reads more only when nothing is buffered; safe to call repeatedly. */ + private def tryFillPending(): Unit = { + try { + while (pending.isEmpty && advanceCursor()) { + reader.resultRowRead() + // The join checks for a close() before each connector call, so it makes none after it + // has seen one. + val start = System.nanoTime() + reader.ensureOpen() + val ordinal = cursor.inputOrdinal() + reader.ensureOpen() + val connectorRow = cursor.get() + metrics.lookupTime += System.nanoTime() - start + if (connectorRow == null) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, "NULL_RESULT", Map("method" -> "ExternalLookupResultCursor.get()")) + } + val entry = requestedEntry(ordinal) + reader.ensureOpen() + val resultRow = resultRows.validatedCopy(connectorRow) + if (parameters.selectedPredicatesHold(entry.requestRow, resultRow)) { + entry.rowIndexes.foreach(joinMatch(_, resultRow)) + } + } + if (pending.isEmpty) finishCursor(completed = true) + } catch { + case error: Throwable => + Utils.tryWithSafeFinally(throw error) { + finishCursor(completed = false) + } + } + } + + /** + * Advances the connector's cursor, unless the reader was closed meanwhile. A close() while + * next() ran fails the read once next() returns: Spark then reads no row from the closed + * cursor, and does not take a missing row for a complete result. + */ + private def advanceCursor(): Boolean = (cursor ne EmptyLookupCursor) && { + reader.ensureOpen() + val advanced = connectorCall(cursor.next()) + reader.ensureOpen() + advanced + } + + /** + * Runs a connector call and adds its time to the lookup time metric, which counts only the + * time in the connector, not that of the work above the join while a cursor is open. + */ + private def connectorCall[T](call: => T): T = { + val start = System.nanoTime() + try call finally metrics.lookupTime += System.nanoTime() - start + } + + private def requestedEntry(ordinal: Int): KeyEntry = { + if (ordinal < 0 || ordinal >= keyEntries.length) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, + "INVALID_INPUT_ORDINAL", + Map("ordinal" -> ordinal.toString, "numParameterRows" -> keyEntries.length.toString)) + } + keyEntries(ordinal) + } + + private def joinMatch(index: Int, lookupRow: InternalRow): Unit = { + if (joinOutput.matches(rows(index), lookupRow)) { + matched(index) = true + joinOutput.matched(lookupRow).foreach(emit(index, _)) + } + } + + /** + * Closes the cursor once. After a complete read, finishes every stream row that was waiting for + * its results. After a failure or a close, the results may be partial, so it finishes none: + * a row without a match could be a row whose match was never read. Once the reader is closed, + * its close owns the cursor and the reader's metrics, so the join makes no further connector + * call. + */ + private def finishCursor(completed: Boolean): Unit = if (cursor ne EmptyLookupCursor) { + cursor = EmptyLookupCursor + if (!reader.isClosed) { + try { + connectorCall(reader.closeCursor()) + } finally { + reader.updateMetrics() + } + } + if (completed) keyEntries.foreach(_.rowIndexes.foreach(finish)) + } + + private def finish(index: Int): Unit = if (!finished.contains(index)) { + finished += index + if (!matched(index)) joinOutput.unmatched.foreach(emit(index, _)) + } + + private def emit(index: Int, lookupRow: InternalRow): Unit = { + pending.enqueue(index -> lookupRow) + metrics.outputRows += 1 + } + } + + /** The cursor of a batch that sends no request, or whose cursor is finished. */ + private object EmptyLookupCursor extends ExternalLookupResultCursor { + override def next(): Boolean = false + override def inputOrdinal(): Int = throw new NoSuchElementException("external lookup result") + override def get(): InternalRow = throw new NoSuchElementException("external lookup result") + override def close(): Unit = {} + } + + /** A check of one value slot: a field of a row, or an element of an array. */ + private type SlotCheck = (SpecializedGetters, Int) => Unit + + /** + * Validates each row that the connector returns, and copies it once into Spark's own row before + * Spark checks, joins or keeps it. A connector may reuse its row and its buffers, byte arrays + * included, so a row that Spark still holds must not share them. A value that breaks its type + * fails the task, at any nested level: a null in a field, array element or map value that the + * table or the read schema declares NOT NULL, or a decimal that does not fit its precision and + * scale. Spark already relied on them while it optimized the query. The checks are built once + * from the read schema, and a field whose type has nothing to check costs nothing per row. + */ + private class LookupResultRows { + private val copy = UnsafeProjection.create(lookupInput, lookupInput) + private val fieldChecks = lookupInput.zipWithIndex.flatMap { case (field, ordinal) => + slotCheck(field.dataType, field.nullable, Seq(field.name)).map(ordinal -> _) + } + + /** The row, validated and copied into a row that Spark owns. */ + def validatedCopy(resultRow: InternalRow): UnsafeRow = { + fieldChecks.foreach { case (ordinal, check) => check(resultRow, ordinal) } + copy(resultRow).copy() + } + + /** The check of a slot of this type, at this field path, or None if it has nothing to check. */ + private def slotCheck( + dataType: DataType, + nullable: Boolean, + path: Seq[String]): Option[SlotCheck] = { + val valueCheck = nonNullValueCheck(dataType, path) + if (nullable && valueCheck.isEmpty) { + None + } else { + Some { (values, ordinal) => + if (!values.isNullAt(ordinal)) { + valueCheck.foreach(_(values, ordinal)) + } else if (!nullable) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, + "NULL_IN_NOT_NULL_FIELD", + Map("field" -> QueryExecutionErrors.toSQLId(path))) + } + } + } + } + + /** The check of a value that is not null, or None if its type has nothing to check. */ + private def nonNullValueCheck(dataType: DataType, path: Seq[String]): Option[SlotCheck] = + dataType match { + case decimalType: DecimalType => Some { (values, ordinal) => + val value = values.getDecimal(ordinal, decimalType.precision, decimalType.scale) + if (!fits(value, decimalType)) { + throw QueryExecutionErrors.invalidDataSourceExternalLookupError( + tableName, + "DECIMAL_OUT_OF_RANGE", + Map( + "field" -> QueryExecutionErrors.toSQLId(path), + "type" -> QueryExecutionErrors.toSQLType(decimalType))) + } + } + case structType: StructType => + val checks = structType.fields.toSeq.zipWithIndex.flatMap { case (field, ordinal) => + slotCheck(field.dataType, field.nullable, path :+ field.name).map(ordinal -> _) + } + Option.when(checks.nonEmpty) { (values, ordinal) => + val struct = values.getStruct(ordinal, structType.length) + checks.foreach { case (fieldOrdinal, check) => check(struct, fieldOrdinal) } + } + case arrayType: ArrayType => + slotCheck(arrayType.elementType, arrayType.containsNull, path :+ "element").map { + check => (values, ordinal) => eachElement(values.getArray(ordinal), check) + } + case mapType: MapType => + // A map key is never null, whatever the value's nullability. + val keyCheck = slotCheck(mapType.keyType, nullable = false, path :+ "key") + val valueCheck = + slotCheck(mapType.valueType, mapType.valueContainsNull, path :+ "value") + Option.when(keyCheck.nonEmpty || valueCheck.nonEmpty) { (values, ordinal) => + val map = values.getMap(ordinal) + keyCheck.foreach(eachElement(map.keyArray(), _)) + valueCheck.foreach(eachElement(map.valueArray(), _)) + } + case _ => None Review Comment: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Fixed in [d61e9e647d9](https://github.com/apache/spark/commit/d61e9e647d97088f545d3774f128f828c9d1a302): a UDT value is now checked as its `sqlType`, at every nested level. The tests use a UDT whose `sqlType` is a struct with a NOT NULL INT, a NOT NULL STRING and a DECIMAL(5,2). It appears on its own and inside an array, a map and a struct, in inner and left outer joins. Valid values are joined unchanged. A struct of nulls, a null label and an out-of-range decimal each fail with the named error, which names the nested field. ########## sql/core/src/main/scala/org/apache/spark/sql/execution/streaming/runtime/ExternalLookupJoinStartupCheck.scala: ########## @@ -0,0 +1,139 @@ +/* + * 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 scala.util.control.NonFatal + +import org.apache.spark.SparkThrowable +import org.apache.spark.internal.Logging +import org.apache.spark.sql.catalyst.analysis.ExternalLookupJoinEligibility +import org.apache.spark.sql.catalyst.analysis.ExternalLookupJoinEligibility.NotLookupJoin +import org.apache.spark.sql.catalyst.plans.logical.{Join, LogicalPlan} +import org.apache.spark.sql.classic.SparkSession +import org.apache.spark.sql.execution.QueryExecution +import org.apache.spark.sql.execution.streaming.checkpointing.{OffsetSeqMetadata, + OffsetSeqMetadataBase} +import org.apache.spark.sql.internal.SQLConf + +/** + * Plans the external lookup joins of a streaming query when its execution starts, in the query + * thread before it creates its sources, so that a join that cannot be planned stops the query at + * once instead of failing the first micro-batch that runs, which may come much later. `start()` + * has returned by then, so a planning call to the connector that takes long does not block it. + * Whether a join has a lookup predicate, and which ones the connector selects, depend on the + * condition as the optimizer leaves it, for example after it simplifies the condition. So the + * query is optimized once here, with the optimizer of its micro-batches and with their + * configuration, and the result is discarded. + * + * Only the lookup sides are planned. The other subtrees without a streaming relation, and the + * subtrees of subquery plans without an outer reference, become placeholders of their outputs, as + * in the optimization for the column pruning of streaming scans (see + * `StreamingV2ScanPushDown.forStartup`), so that their scans are neither built nor planned at the + * start, as for a query without a lookup join. + * + * Only the planning errors of the lookup join and of its connector contract stop the query. Any + * other error, such as one that an ordinary join raises too, is left to the micro-batch, which + * plans the query as before. + */ +private[sql] object ExternalLookupJoinStartupCheck extends Logging { + private val lookupErrorClasses = Set( + "EXTERNAL_LOOKUP_JOIN_UNSUPPORTED", + "INVALID_EXTERNAL_LOOKUP_HINT", Review Comment: > [!NOTE] > **DISCLAIMER:** This comment was written by an LLM, Claude Opus 5.5 (`claude-opus-5-5`, 1M context), posting on behalf of @HeartSaVioR. Fixed: this PR no longer lists it ([d61e9e647d9](https://github.com/apache/spark/commit/d61e9e647d97088f545d3774f128f828c9d1a302)). #60019, which defines the error class, adds it back ([afe85d777aa](https://github.com/apache/spark/commit/afe85d777aa47e289b05ceca6f06e06118fc763c)). -- 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]
