Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/source/user-guide/latest/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -624,8 +624,8 @@ The type-name conversion functions (`bigint`, `binary`, `boolean`, `date`, `deci

| Function | Status | Implementation | Notes |
| --- | --- | --- | --- |
| `named_struct` | ✅ | Native | Duplicate field names fall back |
| `struct` | ✅ | Native | |
| `named_struct` | ✅ | Hybrid | Duplicate field names route through the JVM codegen dispatcher |
| `struct` | ✅ | Hybrid | Duplicate field names route through the JVM codegen dispatcher |

---

Expand Down
12 changes: 11 additions & 1 deletion spark/src/main/java/org/apache/arrow/c/ArrowImporter.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

package org.apache.arrow.c;

import java.util.function.Function;

import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.util.AutoCloseables;
import org.apache.arrow.vector.FieldVector;
Expand Down Expand Up @@ -53,11 +55,19 @@ Field importField(ArrowSchema schema, CDataDictionaryProvider provider) {

public FieldVector importVector(
ArrowArray array, ArrowSchema schema, CDataDictionaryProvider provider) {
return importVector(array, schema, provider, field -> field.createVector(allocator));
}

public FieldVector importVector(
ArrowArray array,
ArrowSchema schema,
CDataDictionaryProvider provider,
Function<Field, FieldVector> vectorFactory) {
Field field = null;
FieldVector vector = null;
try {
field = importField(schema, provider);
vector = field.createVector(allocator);
vector = vectorFactory.apply(field);
ArrayImporter importer = new ArrayImporter(allocator, vector, provider);
importer.importArray(array);
return vector;
Expand Down
9 changes: 8 additions & 1 deletion spark/src/main/java/org/apache/comet/udf/CometUdfBridge.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,22 @@
package org.apache.comet.udf;

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

import org.apache.arrow.c.ArrowArray;
import org.apache.arrow.c.ArrowImporter;
import org.apache.arrow.c.ArrowSchema;
import org.apache.arrow.c.Data;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.vector.FieldVector;
import org.apache.arrow.vector.ValueVector;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.spark.TaskContext;
import org.apache.spark.comet.CometTaskContextShim;
import org.apache.spark.util.TaskCompletionListener;

import org.apache.comet.util.ClassLoaders;
import org.apache.comet.vector.NativeUtil$;

/**
* JNI entry point for native execution to invoke a {@link CometUDF}. Matches the static-method
Expand Down Expand Up @@ -210,14 +214,17 @@ private static void evaluateInternal(
assert udf != null : "reflective instantiation returned null for " + udfClassName;

BufferAllocator allocator = org.apache.comet.package$.MODULE$.CometArrowAllocator();
ArrowImporter importer = new ArrowImporter(allocator);
Function<Field, FieldVector> vectorFactory =
field -> NativeUtil$.MODULE$.createVectorForImport(field, allocator);

ValueVector[] inputs = new ValueVector[inputArrayPtrs.length];
ValueVector result = null;
try {
for (int i = 0; i < inputArrayPtrs.length; i++) {
ArrowArray inArr = ArrowArray.wrap(inputArrayPtrs[i]);
ArrowSchema inSch = ArrowSchema.wrap(inputSchemaPtrs[i]);
inputs[i] = Data.importVector(allocator, inArr, inSch, null);
inputs[i] = importer.importVector(inArr, inSch, null, vectorFactory);
}

result = udf.evaluate(inputs, numRows);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ package org.apache.comet.codegen
import scala.jdk.CollectionConverters._
import scala.util.control.NonFatal

import org.apache.arrow.memory.BufferAllocator
import org.apache.arrow.vector._
import org.apache.arrow.vector.complex.{ListVector, MapVector, StructVector}
import org.apache.arrow.vector.types.pojo.{ArrowType, Field}
Expand All @@ -32,6 +31,7 @@ import org.apache.spark.sql.types._

import org.apache.comet.CometArrowAllocator
import org.apache.comet.shims.CometTypeShim
import org.apache.comet.vector.NativeUtil

/**
* Output-side emitters for the codegen kernel: [[allocateOutput]], [[emitOutputWriter]]
Expand All @@ -43,8 +43,8 @@ private[codegen] object CometBatchKernelCodegenOutput extends CometTypeShim {
/**
* Spark `DataType` to an Arrow `Field` with names Comet expects on FFI export. Spark's
* `Utils.toArrowField` names list children `"element"`; this rewrites them to `"item"`. Pair
* with the [[RenamedListVector]] / [[RenamedMapVector]] / [[RenamedStructVector]] subclasses in
* [[allocateOutput]], which pin `getField()` so the cached Field actually reaches export.
* with [[NativeUtil.createVector]], whose complex-vector wrappers pin `getField()` so the
* cached Field actually reaches export.
*/
def toFfiArrowField(name: String, dataType: DataType, nullable: Boolean): Field =
renameForArrowRustFfi(Utils.toArrowField(name, dataType, nullable, "UTC"))
Expand All @@ -71,8 +71,8 @@ private[codegen] object CometBatchKernelCodegenOutput extends CometTypeShim {
* Allocate an Arrow output vector from a pre-built `Field`. Callers cache the Field per
* `(expression, schema)` and pass it on every batch.
*
* Complex top-level types route through a [[RenamedListVector]] / [[RenamedMapVector]] /
* [[RenamedStructVector]] (see those for the runtime-vs-export naming gap).
* Complex top-level types route through [[NativeUtil.createVector]] to bridge runtime child
* names and the exported schema.
*
* `estimatedBytes` pre-sizes the data buffer for variable-length scalar outputs. Ignored for
* other root types, and not propagated into nested var-width children (their `allocateNew` runs
Expand All @@ -87,22 +87,7 @@ private[codegen] object CometBatchKernelCodegenOutput extends CometTypeShim {
* Closes the vector on any failure so a partially-initialized tree doesn't leak buffers.
*/
def allocateOutput(field: Field, numRows: Int, estimatedBytes: Int): FieldVector = {
val vec: FieldVector = field.getType match {
case _: ArrowType.List | _: ArrowType.LargeList | _: ArrowType.FixedSizeList =>
val v = new RenamedListVector(field, CometArrowAllocator)
v.initializeChildrenFromFields(field.getChildren)
v
case _: ArrowType.Map =>
val v = new RenamedMapVector(field, CometArrowAllocator)
v.initializeChildrenFromFields(field.getChildren)
v
case _: ArrowType.Struct =>
val v = new RenamedStructVector(field, CometArrowAllocator)
v.initializeChildrenFromFields(field.getChildren)
v
case _ =>
field.createVector(CometArrowAllocator).asInstanceOf[FieldVector]
}
val vec = NativeUtil.createVector(field, CometArrowAllocator)
try {
vec.setInitialCapacity(numRows)
vec match {
Expand All @@ -122,27 +107,6 @@ private[codegen] object CometBatchKernelCodegenOutput extends CometTypeShim {
}
}

/**
* Pin `getField()` to the cached Field so FFI export carries the names Comet expects.
* `ListVector.getField` rebuilds child labels from the runtime data vector, which
* `addOrGetVector` hardcodes to `"$data$"`. Applied to `MapVector` and `StructVector` too
* because their `getField` recurses and can pick up a buried `ListVector`'s `"$data$"`.
*/
private final class RenamedListVector(exportField: Field, allocator: BufferAllocator)
extends ListVector(exportField, allocator, null) {
override def getField: Field = exportField
}

private final class RenamedMapVector(exportField: Field, allocator: BufferAllocator)
extends MapVector(exportField, allocator, null) {
override def getField: Field = exportField
}

private final class RenamedStructVector(exportField: Field, allocator: BufferAllocator)
extends StructVector(exportField, allocator, null) {
override def getField: Field = exportField
}

/**
* Returns `(concreteVectorClassName, batchSetup, perRowSnippet)`. `output` is cast to the
* concrete class in `process`'s prelude so `emitWrite`'s complex-type branches can hoist child
Expand Down
10 changes: 7 additions & 3 deletions spark/src/main/scala/org/apache/comet/serde/structs.scala
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,16 @@ import org.apache.comet.CometSparkSessionExtensions.withFallbackReason
import org.apache.comet.DataTypeSupport
import org.apache.comet.serde.QueryPlanSerde.{exprToProtoInternal, serializeDataType}

object CometCreateNamedStruct extends CometExpressionSerde[CreateNamedStruct] {
object CometCreateNamedStruct
extends CometExpressionSerde[CreateNamedStruct]
with CodegenDispatchFallback {
Comment thread
RRXXZZYY marked this conversation as resolved.

private val duplicateNamesReason =
Comment thread
RRXXZZYY marked this conversation as resolved.
"`CreateNamedStruct` with duplicate field names is not supported"
"`CreateNamedStruct` with duplicate field names cannot use native execution"

override def getUnsupportedReasons(): Seq[String] = Seq(duplicateNamesReason)
override def getUnsupportedReasons(): Seq[String] = Seq(
"Duplicate field names are routed through the JVM codegen dispatcher " +
"(Spark's own `doGenCode`).")

override def getSupportLevel(expr: CreateNamedStruct): SupportLevel = {
if (expr.names.length != expr.names.distinct.length) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
/*
* 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.comet.vector

import java.nio.channels.ReadableByteChannel
import java.util

import scala.collection.JavaConverters._

import org.apache.arrow.memory.BufferAllocator
import org.apache.arrow.util.AutoCloseables
import org.apache.arrow.vector.{FieldVector, VectorLoader, VectorSchemaRoot}
import org.apache.arrow.vector.compression.CompressionCodec
import org.apache.arrow.vector.dictionary.Dictionary
import org.apache.arrow.vector.ipc.{ArrowStreamReader, ReadChannel}
import org.apache.arrow.vector.ipc.message.{ArrowDictionaryBatch, ArrowRecordBatch, MessageChannelReader}
import org.apache.arrow.vector.types.pojo.{Field, Schema}
import org.apache.arrow.vector.util.{DictionaryUtility, VectorBatchAppender}

/**
* Arrow IPC reader that keeps struct children positional when a schema contains duplicate names.
*
* ArrowReader normally allocates each field with `Field.createVector`, which indexes direct
* struct children by name and collapses duplicates. Reuse NativeUtil's import factory here so IPC
* and C Data imports have the same physical layout and the ordinary no-duplicate path stays
* unchanged.
*/
final class CometArrowStreamReader(
messageReader: MessageChannelReader,
allocator: BufferAllocator,
compressionFactory: CompressionCodec.Factory)
extends ArrowStreamReader(messageReader, allocator, compressionFactory) {

def this(messageReader: MessageChannelReader, allocator: BufferAllocator) =
this(messageReader, allocator, CompressionCodec.Factory.INSTANCE)

def this(channel: ReadableByteChannel, allocator: BufferAllocator) =
this(
new MessageChannelReader(new ReadChannel(channel), allocator),
allocator,
CompressionCodec.Factory.INSTANCE)

private var cometInitialized = false
private var cometResourcesClosed = false
private var cometSourceClosed = false
private var cometRoot: VectorSchemaRoot = _
private var cometLoader: VectorLoader = _

override protected def initialize(): Unit = {
val originalSchema = readSchema()
val fields = new util.ArrayList[Field](originalSchema.getFields.size())
val vectors = new util.ArrayList[FieldVector](originalSchema.getFields.size())
val importedDictionaries = new util.HashMap[java.lang.Long, Dictionary]()

try {
originalSchema.getFields.asScala.foreach { field =>
val updated = DictionaryUtility.toMemoryFormat(field, allocator, importedDictionaries)
fields.add(updated)
vectors.add(NativeUtil.createVectorForImport(updated, allocator))
}
cometRoot =
new VectorSchemaRoot(new Schema(fields, originalSchema.getCustomMetadata), vectors, 0)
cometLoader = new VectorLoader(cometRoot, compressionFactory)
dictionaries = util.Collections.unmodifiableMap(importedDictionaries)
cometInitialized = true
} catch {
case failure: Throwable =>
AutoCloseables.close(failure, vectors)
AutoCloseables.close(
failure,
importedDictionaries.values().asScala.map(_.getVector).asJava)
cometRoot = null
cometLoader = null
throw failure
}
}

override protected def ensureInitialized(): Unit = {
if (!cometInitialized) initialize()
}

override def getVectorSchemaRoot: VectorSchemaRoot = {
ensureInitialized()
cometRoot
}

override def getDictionaryVectors: util.Map[java.lang.Long, Dictionary] = {
ensureInitialized()
dictionaries
}

override def lookup(id: Long): Dictionary = {
if (!cometInitialized) {
throw new IllegalStateException("Unable to lookup until reader has been initialized")
}
dictionaries.get(id)
}

override def getDictionaryIds: util.Set[java.lang.Long] = {
if (!cometInitialized) {
throw new IllegalStateException(
"Unable to list dictionaries until reader has been initialized")
}
dictionaries.keySet()
}

override protected def prepareLoadNextBatch(): Unit = {
ensureInitialized()
cometRoot.setRowCount(0)
}

override protected def loadRecordBatch(batch: ArrowRecordBatch): Unit = {
try cometLoader.load(batch)
finally batch.close()
}

override protected def loadDictionary(dictionaryBatch: ArrowDictionaryBatch): Unit = {
val dictionary = dictionaries.get(dictionaryBatch.getDictionaryId)
if (dictionary == null) {
throw new IllegalArgumentException(
s"Dictionary ID ${dictionaryBatch.getDictionaryId} not defined in schema")
}

val vector = dictionary.getVector
if (dictionaryBatch.isDelta) {
val deltaVector = NativeUtil.createVectorForImport(vector.getField, allocator)
try {
loadDictionaryBatch(dictionaryBatch, deltaVector)
VectorBatchAppender.batchAppend(vector, deltaVector)
} finally {
deltaVector.close()
}
} else {
loadDictionaryBatch(dictionaryBatch, vector)
}
}

private def loadDictionaryBatch(
dictionaryBatch: ArrowDictionaryBatch,
vector: FieldVector): Unit = {
val root = new VectorSchemaRoot(
util.Collections.singletonList(vector.getField),
util.Collections.singletonList(vector),
0)
val loader = new VectorLoader(root, compressionFactory)
try loader.load(dictionaryBatch.getDictionary)
finally dictionaryBatch.close()
}

override def close(): Unit = close(closeReadSource = true)

override def close(closeReadSource: Boolean): Unit = {
val resources = new util.ArrayList[AutoCloseable]()
if (!cometResourcesClosed) {
cometResourcesClosed = true
if (cometRoot != null) resources.add(cometRoot)
if (dictionaries != null) {
dictionaries.values().asScala.foreach(dictionary => resources.add(dictionary.getVector))
}
}
if (closeReadSource && !cometSourceClosed) {
cometSourceClosed = true
resources.add(new AutoCloseable {
override def close(): Unit = CometArrowStreamReader.super.closeReadSource()
})
}
AutoCloseables.close(resources)
}
}
Loading