This is an automated email from the ASF dual-hosted git repository.
gengliangwang pushed a commit to branch branch-4.x
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/branch-4.x by this push:
new dacba4776333 [SPARK-60753][SQL] Read the columns of native data
sources from their Arrow buffers, and their decimals as longs
dacba4776333 is described below
commit dacba47763337a4ad10170cec1ada979b50e800b
Author: Gengliang Wang <[email protected]>
AuthorDate: Wed Nov 11 20:22:32 2026 -0800
[SPARK-60753][SQL] Read the columns of native data sources from their Arrow
buffers, and their decimals as longs
### What changes were proposed in this pull request?
`NativePartitionReader` imports every batch of a native data source
(#59424) into the same Arrow vectors, which Spark reads through
`ReusedArrowColumnVector`. This PR adds `NativeColumnVector`, a
`ReusedArrowColumnVector` for the top-level columns of the reader, which reads
their values at the addresses of the buffers of each batch:
- After each import, the reader calls `refresh()` on each column, which
reads the addresses of the buffers of the batch, and whether it has nulls. The
vector then reads booleans, integers, floats, dates, timestamps, decimals, and
`Utf8` and `Utf8View` strings with `Platform`, and the nulls from the validity
bitmap, or none when the batch has no null.
- It returns the decimals that fit their precision in a long, of a scale
from 0 to their precision, as long-backed `Decimal`s, as Spark's own column
vectors return them. The other decimals, which do not fit their precision or a
long, or are read at another scale, or have a negative scale, whose integral
conversions long-backed decimals do not support, still read through
`ArrowColumnVector`, and fail or read in full as before.
- Large strings, binary values, structs, lists and maps, and the fields of
structs read through `ArrowColumnVector`, as before.
- Since the vectors read the buffers at their addresses, a late read of a
batch whose buffers were freed would read freed memory, where
`ArrowColumnVector` failed a check. Script transformation, for example, gets
its first batch on the task thread and reads its rows on a thread of its own,
which may still read it when the task completes and `DataSourceRDD` closes the
reader. So `close()` frees the buffers of the batch, and the allocator, at once
only if `next()` was called again since [...]
- Script transformation registers a task completion listener, as `PipedRDD`
does: once a task completes before it read the whole output of the script, it
sends the script SIGTERM, closes the output of the script and interrupts the
writer thread, which catches the `InterruptedException` of `proc.waitFor()` so
that it does not exit the executor (SPARK-25158). Otherwise the script blocks
on writing its output and the writer thread on writing the input, which now
keeps the last batch of a [...]
- `ColumnarArrowEvalPythonEvaluatorFactory` sends the batches whose columns
are `ReusedArrowColumnVector`s, such as those of native data sources and the
results of Python UDFs, down the path that copies the pass-through rows, rather
than the Arrow path, which holds the pass-through columns of a batch until
Python returns its results, past the next batch.
### Why are the changes needed?
`ArrowColumnVector` reads each value through Arrow Java, which by default
checks on each access the bounds and the reference count of the buffer, and
whether the value is null: for a value of a nullable `BIGINT` column,
`isNullAt` and `getLong` make three checked reads of buffers. The reader does
not need these checks. Spark reads only the rows of a batch, whose buffers
Arrow Java sizes by the lengths of the arrays, which the reader checks before
it imports them; the buffers stay allo [...]
Reading a batch of 8192 rows of nullable columns without nulls, as the
generated code reads them (`isNullAt`, then the value), on Java 17, with each
column vector in its own JVM so that the call sites see one class, as they do
in the code of a query (a local benchmark, not part of this PR):
| Columns | `ReusedArrowColumnVector` | `NativeColumnVector` |
| --- | --- | --- |
| `BIGINT`, `INT`, `DECIMAL(15,2)` and `STRING`, summed | 43.7 ns/row |
16.0 ns/row |
| `BIGINT`, summed | 4.6 ns/row | 0.3 ns/row |
| `DECIMAL(15,2)`, summed with `Decimal.+` | 22.7 ns/row | 14.0 ns/row |
| `STRING` views of 64 bytes, their `numBytes` summed | 9.4 ns/row | 0.5
ns/row |
End to end, the native data source framework of master cannot run the
Parquet source of the Rust SDK of #59692, whose ABI is that of 74aa0dffc53 of
#59424, before predicate pushdown was left out. On that framework, with the
same column vector, the queries of that source take this fraction of the time
of Spark's own Parquet reader, which alternates with it in the same session,
with `local[4]` on a shared 32-thread Linux host and Java 25:
| Query | Before | After |
| --- | --- | --- |
| `sum` of 4 `DECIMAL(15,2)` columns, 30M rows | 2.29 | 0.96 |
| `sum` of 3 `BIGINT` and 1 `INT` columns, 30M rows | 1.26 | 0.68 |
| TPC-H Q1 on a table with the columns of TPC-H lineitem, 30M rows | 1.04 |
0.98 |
| `count(*), sum(l_quantity) ... WHERE l_shipmode = 'AIR'`, same table |
1.05 | 0.74 |
| `count(payload)` of a 64-character string, 50M rows | 0.79 | 0.54 |
| `sum(id)`, 50M rows | 0.94 | 0.70 |
The queries that drop most rows in the source change less, since Spark
reads few values: `TPC-H Q6` 0.71 and 0.67, `l_comment LIKE 'ab%'` 0.51 and
0.52.
### Does this PR introduce _any_ user-facing change?
Yes.
- Script transformation (`TRANSFORM`), whatever its input, now stops its
script once its task completes before it read the whole output of the script,
as under a LIMIT. Before, the script and the writer thread could block on each
other forever. With a Hive serde, the task sees the end of the output only when
it asks for a row after the last one, so a LIMIT that takes exactly all the
rows of the output also stops a script that still runs after it closed its
output.
- Within master and branch-4.x, since native data sources (#59424) are not
released yet: the top-level decimal columns of up to 18 digits of native data
sources now read as long-backed `Decimal`s, as those of Spark's own data
sources do, so that their integral casts truncate exactly. With ANSI on,
`CAST(d AS INT)` of a `DECIMAL(18,9)` 123456789.999999999 returns 123456789
rather than 123456790, and `CAST(d AS TINYINT)` of a `DECIMAL(18,15)`
127.999999999999999 returns 127 rather than [...]
### How was this patch tested?
- The new `NativeColumnVectorSuite` compares `NativeColumnVector` with
`ArrowColumnVector` on the same Arrow vectors: booleans, integers, floats with
NaN and -0.0, dates and timestamps, with nulls over several bytes of the
bitmap; strings and string views, in the views and in data buffers, over
several batches; decimals of every precision from 1 to 18, at the bounds of
their precision, out of it and out of a long, read at other precisions and
scales, and of a negative scale with `spar [...]
- New tests in `NativeDataSourceSuite`: `close a reader while another
thread reads the batch that it returned` checks that a close on another thread
releases the stream and the task at once but keeps the buffers, that the other
thread still reads the values of the batch, that `next()` then fails on both
threads, and that a GC frees the buffers and the allocator once the reader is
unreachable. `free the buffers of a reader closed at the end of its stream
without a GC` checks that a rea [...]
- `TRANSFORM destroys the script when its task completes before reading all
its output` in `BaseScriptTransformationSuite`, run by the Spark and the Hive
suites: `cat` over 1M rows, while the task reads one row of its output. It
checks that the writer threads of the test end, that they log no ERROR, and
that the uncaught-exception handler of the suite saw nothing.
- `build/sbt 'sql/testOnly *NativeColumnVectorSuite
*ArrowColumnVectorSuite'` on Java 17: 38 passed, on an earlier revision.
- `NativeDataSourceSuite` and `NativeColumnVectorSuite`: 98 passed, and 2
canceled, a test for the Java versions before 22 and one that needs the Python
dependencies of pandas UDFs. `SparkScriptTransformationSuite`: 34 passed, and
the new test of `HiveScriptTransformationSuite` passed.
`ColumnarDataSourceSuite`: 26 passed, and the three tests of the reader's close
passed 5 more times, each in a new JVM, on an earlier revision. Master now
needs Java 21 or later, and the Java 25 of this [...]
- `build/sbt sql/checkstyle sql/scalastyle sql/Test/scalastyle
catalyst/checkstyle`.
- On the framework of 74aa0dffc53, with the same column vector, the Spark
smoke scripts of the Parquet and Range examples of the Rust SDK, which compare
their reads with those of Spark.
### 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.
Closes #59961 from gengliangwang/native-column-vector.
Authored-by: Gengliang Wang <[email protected]>
Signed-off-by: Gengliang Wang <[email protected]>
(cherry picked from commit 9a1d78d53945df08333a2376bb3c6e3bb6e2cc0f)
Signed-off-by: Gengliang Wang <[email protected]>
skip-checks: true
---
.../connector/read/SupportsArrowStreamRead.java | 5 +-
.../datasources/v2/ffi/NativeColumnVector.java | 359 ++++++++++++++++++
.../apache/spark/sql/datasource/spark_datasource.h | 8 +-
.../execution/BaseScriptTransformationExec.scala | 73 +++-
.../execution/SparkScriptTransformationExec.scala | 2 +-
.../datasources/v2/ffi/NativeDataSource.scala | 176 +++++++--
.../native-datasource/test_native_datasource.cc | 47 +--
.../execution/BaseScriptTransformationSuite.scala | 39 ++
.../v2/ffi/NativeColumnVectorSuite.scala | 420 +++++++++++++++++++++
.../datasources/v2/ffi/NativeDataSourceSuite.scala | 303 ++++++++++++++-
.../execution/HiveScriptTransformationExec.scala | 13 +-
11 files changed, 1353 insertions(+), 92 deletions(-)
diff --git
a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsArrowStreamRead.java
b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsArrowStreamRead.java
index 7b772a6d9951..d3a84490b1bf 100644
---
a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsArrowStreamRead.java
+++
b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/SupportsArrowStreamRead.java
@@ -49,7 +49,10 @@ public interface SupportsArrowStreamRead extends
PartitionReaderFactory {
* data and fail. The caller owns
* the stream, which it may move, and releases it, which may happen after
the task ended: Spark
* frees what the stream uses, such as the context of the task, once the
stream is released. A
- * stream that is never released leaks.
+ * stream that is never released leaks. The arrays and the schemas that the
stream returns may
+ * outlive it, as the C stream interface allows: the caller may keep them
after it released the
+ * stream, and release them later, since their release uses neither the
stream nor the context of
+ * the task.
*
* @param partition a partition of the scan, as the scan planned it
* @param streamAddress the address of a {@code struct ArrowArrayStream}
that the caller
diff --git
a/sql/core/src/main/java/org/apache/spark/sql/execution/datasources/v2/ffi/NativeColumnVector.java
b/sql/core/src/main/java/org/apache/spark/sql/execution/datasources/v2/ffi/NativeColumnVector.java
new file mode 100644
index 000000000000..999d74887c7d
--- /dev/null
+++
b/sql/core/src/main/java/org/apache/spark/sql/execution/datasources/v2/ffi/NativeColumnVector.java
@@ -0,0 +1,359 @@
+/*
+ * 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.ffi;
+
+import java.nio.ByteOrder;
+import java.util.List;
+
+import org.apache.arrow.memory.ArrowBuf;
+import org.apache.arrow.vector.BaseVariableWidthViewVector;
+import org.apache.arrow.vector.BigIntVector;
+import org.apache.arrow.vector.BitVector;
+import org.apache.arrow.vector.DateDayVector;
+import org.apache.arrow.vector.DecimalVector;
+import org.apache.arrow.vector.Float4Vector;
+import org.apache.arrow.vector.Float8Vector;
+import org.apache.arrow.vector.IntVector;
+import org.apache.arrow.vector.SmallIntVector;
+import org.apache.arrow.vector.TimeStampMicroTZVector;
+import org.apache.arrow.vector.TimeStampMicroVector;
+import org.apache.arrow.vector.TinyIntVector;
+import org.apache.arrow.vector.ValueVector;
+import org.apache.arrow.vector.VarCharVector;
+import org.apache.arrow.vector.ViewVarCharVector;
+
+import org.apache.spark.sql.execution.vectorized.ReusedArrowColumnVector;
+import org.apache.spark.sql.types.Decimal;
+import org.apache.spark.sql.vectorized.ArrowColumnVector;
+import org.apache.spark.unsafe.Platform;
+import org.apache.spark.unsafe.types.UTF8String;
+
+/**
+ * The column vector of a top-level column of a {@code NativePartitionReader},
which imports every
+ * batch into the same Arrow vectors.
+ *
+ * <p>After each import, the reader calls {@link #refresh(long)}, and the
vector then reads
+ * booleans, integers, floats, dates, timestamps, decimals, and the strings of
the Arrow types Utf8
+ * and Utf8View at the addresses of the buffers of the batch. {@link
ArrowColumnVector} reads each
+ * value through Arrow Java, which by default checks on each access the bounds
and the reference
+ * count of the buffer, and whether the value is null.
+ * Spark does not need these checks here: it reads only the rows of the batch,
whose buffers Arrow
+ * Java sizes by the lengths of the arrays, which the reader checks before it
imports them, and
+ * the buffers of a batch stay allocated while the batch may be read: until
next is called again,
+ * and if the reader is closed before then, until the reader is unreachable,
which the vector keeps
+ * it from being. The strings, arrays, maps and child vectors that the vector
returns do not refer
+ * to the reader, so this holds for them only while the vector is reachable
too. Spark reads a
+ * value of a nullable column only after {@link #isNullAt(int)}, and the
reader checks that the
+ * columns that the schema declares not nullable have no null, so that the
vector of such a
+ * column does not count the nulls of each batch. The vector of a nullable
+ * column takes the null_count that the library exported, and only counts the
nulls when the
+ * library did not.
+ *
+ * <p>As the vector does not check the bounds and the reference count of the
buffers, a consumer
+ * must read only the rows of the current batch, below its number of rows, and
only until next is
+ * called again, as for the other column vectors that Spark reuses across
batches: a read of
+ * another row, e.g. through a row of the batch that the consumer kept after
next, reads out of
+ * range or freed memory, and may crash the JVM rather than throw. The vector
does not free its
+ * Arrow vector on {@link #close()}, which the reader frees with the other
vectors of the batch, so
+ * that a consumer that closes the batch, rather than releasing it with
+ * {@link #closeIfFreeable()}, does not free the buffers that the vector reads.
+ *
+ * <p>The vector keeps the addresses of the buffers from one import to the
next, whereas
+ * {@link ArrowColumnVector} reads the buffers of its Arrow vector on each
access. So nothing may
+ * reallocate the buffers of the Arrow vectors of the reader between two
imports, e.g. by growing
+ * them: a consumer that writes them through {@link #getValueVector()}, as by
setting their value
+ * count, must keep it at the length of the batch.
+ *
+ * <p>The vector returns the decimals that fit their precision in a long, of a
scale from 0 to
+ * their precision, as the unscaled longs that Spark's own column vectors
hold, which Spark adds as
+ * longs, rather than as BigDecimals. The other decimals, large strings,
binary values, structs,
+ * lists and maps, and the fields of structs are read through {@link
ArrowColumnVector}.
+ */
+class NativeColumnVector extends ReusedArrowColumnVector {
+
+ // The reader, which the vector keeps reachable: a reader closed while its
batch may still be
+ // read frees the buffers of the batch only once it is unreachable. Nothing
reads the field, but
+ // it must stay: each constructor takes the reader so that no column vector
misses it.
+ private final Object reader;
+
+ /**
+ * The column vector of a top-level Arrow vector of {@code reader}, of a
column that the schema to
+ * read declares {@code nullable} or not.
+ */
+ static NativeColumnVector create(ValueVector vector, boolean nullable,
Object reader) {
+ if (vector instanceof BitVector) {
+ return new Booleans(vector, nullable, reader);
+ } else if (vector instanceof TinyIntVector) {
+ return new Bytes(vector, nullable, reader);
+ } else if (vector instanceof SmallIntVector) {
+ return new Shorts(vector, nullable, reader);
+ } else if (vector instanceof IntVector || vector instanceof DateDayVector)
{
+ return new Ints(vector, nullable, reader);
+ } else if (vector instanceof BigIntVector || vector instanceof
TimeStampMicroTZVector ||
+ vector instanceof TimeStampMicroVector) {
+ return new Longs(vector, nullable, reader);
+ } else if (vector instanceof Float4Vector) {
+ return new Floats(vector, nullable, reader);
+ } else if (vector instanceof Float8Vector) {
+ return new Doubles(vector, nullable, reader);
+ } else if (vector instanceof DecimalVector decimalVector) {
+ return new Decimals(decimalVector, nullable, reader);
+ } else if (vector instanceof VarCharVector) {
+ return new Strings(vector, nullable, reader);
+ } else if (vector instanceof ViewVarCharVector) {
+ return new StringViews(vector, nullable, reader);
+ } else {
+ return new NativeColumnVector(vector, reader);
+ }
+ }
+
+ NativeColumnVector(ValueVector vector, Object reader) {
+ super(vector);
+ this.reader = reader;
+ }
+
+ @Override
+ public void close() {
+ // no-op: the reader frees the Arrow vector, whose buffers the vector
reads at their addresses.
+ }
+
+ /**
+ * Reads the addresses of the buffers of the batch that the reader imported
last, whose array of
+ * this column the library exported with a null_count of {@code nullCount}.
+ */
+ void refresh(long nullCount) {
+ }
+
+ /**
+ * Whether {@code vector} has a null, given the null_count {@code nullCount}
that the library
+ * exported for its array, or -1 if it is not known. The C data interface
requires a null_count
+ * other than -1 to be exact, so the nulls are only counted, which Arrow
Java does in the
+ * validity bitmap on each call, for a negative one.
+ */
+ static boolean hasNulls(ValueVector vector, long nullCount) {
+ return nullCount < 0 ? vector.getNullCount() > 0 : nullCount > 0;
+ }
+
+ /** A vector that reads its values and their validity at the addresses of
its buffers. */
+ private abstract static class Direct extends NativeColumnVector {
+ // Whether the schema to read declares the column nullable. The reader
checks that the batches
+ // of a column that it does not declare nullable have no null.
+ private final boolean nullable;
+ // The address of the validity bitmap of the batch, or 0 if the batch has
no null.
+ private long validity;
+ // The address of the data buffer of the batch.
+ long data;
+
+ Direct(ValueVector vector, boolean nullable, Object reader) {
+ super(vector, reader);
+ this.nullable = nullable;
+ }
+
+ @Override
+ void refresh(long nullCount) {
+ ValueVector vector = getValueVector();
+ boolean hasNulls = nullable && hasNulls(vector, nullCount);
+ validity = hasNulls ? vector.getValidityBuffer().memoryAddress() : 0;
+ data = vector.getDataBuffer().memoryAddress();
+ }
+
+ @Override
+ public final boolean isNullAt(int rowId) {
+ return validity != 0 && !bit(validity, rowId);
+ }
+
+ /** The bit of a bitmap, whose bits Arrow orders from the least
significant of each byte. */
+ static boolean bit(long address, int index) {
+ return (Platform.getByte(null, address + (index >> 3)) & (1 << (index &
7))) != 0;
+ }
+ }
+
+ private static final class Booleans extends Direct {
+ Booleans(ValueVector vector, boolean nullable, Object reader) {
+ super(vector, nullable, reader);
+ }
+
+ @Override
+ public boolean getBoolean(int rowId) {
+ return bit(data, rowId);
+ }
+ }
+
+ private static final class Bytes extends Direct {
+ Bytes(ValueVector vector, boolean nullable, Object reader) {
+ super(vector, nullable, reader);
+ }
+
+ @Override
+ public byte getByte(int rowId) {
+ return Platform.getByte(null, data + rowId);
+ }
+ }
+
+ private static final class Shorts extends Direct {
+ Shorts(ValueVector vector, boolean nullable, Object reader) {
+ super(vector, nullable, reader);
+ }
+
+ @Override
+ public short getShort(int rowId) {
+ return Platform.getShort(null, data + 2L * rowId);
+ }
+ }
+
+ private static final class Ints extends Direct {
+ Ints(ValueVector vector, boolean nullable, Object reader) {
+ super(vector, nullable, reader);
+ }
+
+ @Override
+ public int getInt(int rowId) {
+ return Platform.getInt(null, data + 4L * rowId);
+ }
+ }
+
+ private static final class Longs extends Direct {
+ Longs(ValueVector vector, boolean nullable, Object reader) {
+ super(vector, nullable, reader);
+ }
+
+ @Override
+ public long getLong(int rowId) {
+ return Platform.getLong(null, data + 8L * rowId);
+ }
+ }
+
+ private static final class Floats extends Direct {
+ Floats(ValueVector vector, boolean nullable, Object reader) {
+ super(vector, nullable, reader);
+ }
+
+ @Override
+ public float getFloat(int rowId) {
+ return Platform.getFloat(null, data + 4L * rowId);
+ }
+ }
+
+ private static final class Doubles extends Direct {
+ Doubles(ValueVector vector, boolean nullable, Object reader) {
+ super(vector, nullable, reader);
+ }
+
+ @Override
+ public double getDouble(int rowId) {
+ return Platform.getDouble(null, data + 8L * rowId);
+ }
+ }
+
+ private static final class Decimals extends Direct {
+ // Arrow stores the 128 bits of a decimal in native byte order, as
ArrowColumnVector reads it.
+ private static final int LOW_WORD = ByteOrder.nativeOrder() ==
ByteOrder.LITTLE_ENDIAN ? 0 : 8;
+ private static final int HIGH_WORD = 8 - LOW_WORD;
+
+ // The scale of the Arrow type.
+ private final int scale;
+
+ Decimals(DecimalVector vector, boolean nullable, Object reader) {
+ super(vector, nullable, reader);
+ this.scale = vector.getScale();
+ }
+
+ @Override
+ public Decimal getDecimal(int rowId, int precision, int scale) {
+ if (isNullAt(rowId)) return null;
+ // The integral conversions of a decimal that a long holds, such as
Decimal.toLong, only
+ // support the scales from 0 to 18, which those of Spark's own column
vectors have.
+ if (precision <= Decimal.MAX_LONG_DIGITS() && scale == this.scale &&
scale >= 0 &&
+ scale <= precision) {
+ long address = data + (long) DecimalVector.TYPE_WIDTH * rowId;
+ long unscaled = Platform.getLong(null, address + LOW_WORD);
+ if (Platform.getLong(null, address + HIGH_WORD) == unscaled >> 63) {
+ // Null if the value does not fit its precision.
+ Decimal decimal = new Decimal().setOrNull(unscaled, precision,
scale);
+ if (decimal != null) return decimal;
+ }
+ }
+ // Wider decimals, other scales, and the values that do not fit their
precision, which
+ // ArrowColumnVector reads in full or rejects.
+ return super.getDecimal(rowId, precision, scale);
+ }
+ }
+
+ private static final class Strings extends Direct {
+ // The address of the offsets of the values of the batch.
+ private long offsets;
+
+ Strings(ValueVector vector, boolean nullable, Object reader) {
+ super(vector, nullable, reader);
+ }
+
+ @Override
+ void refresh(long nullCount) {
+ super.refresh(nullCount);
+ offsets = getValueVector().getOffsetBuffer().memoryAddress();
+ }
+
+ @Override
+ public UTF8String getUTF8String(int rowId) {
+ if (isNullAt(rowId)) return null;
+ long offset = offsets + 4L * rowId;
+ int start = Platform.getInt(null, offset);
+ int length = Platform.getInt(null, offset + 4) - start;
+ return UTF8String.fromAddress(null, data + start, length);
+ }
+ }
+
+ private static final class StringViews extends Direct {
+ // The addresses of the data buffers of the batch, which hold the values
that a view does not.
+ private long[] buffers = new long[0];
+
+ StringViews(ValueVector vector, boolean nullable, Object reader) {
+ super(vector, nullable, reader);
+ }
+
+ @Override
+ void refresh(long nullCount) {
+ super.refresh(nullCount);
+ List<ArrowBuf> dataBuffers = ((ViewVarCharVector)
getValueVector()).getDataBuffers();
+ if (buffers.length != dataBuffers.size()) {
+ buffers = new long[dataBuffers.size()];
+ }
+ for (int i = 0; i < buffers.length; i++) {
+ buffers[i] = dataBuffers.get(i).memoryAddress();
+ }
+ }
+
+ @Override
+ public UTF8String getUTF8String(int rowId) {
+ if (isNullAt(rowId)) return null;
+ // A view of 16 bytes: the length of the value, then the value if it
fits in the other 12
+ // bytes, or its first 4 bytes, the index of the data buffer that holds
it, and its offset
+ // in that buffer.
+ long view = data + (long) BaseVariableWidthViewVector.ELEMENT_SIZE *
rowId;
+ int length = Platform.getInt(null, view);
+ long inline = view + BaseVariableWidthViewVector.LENGTH_WIDTH;
+ if (length <= BaseVariableWidthViewVector.INLINE_SIZE) {
+ return UTF8String.fromAddress(null, inline, length);
+ }
+ long bufferIndex = inline + BaseVariableWidthViewVector.PREFIX_WIDTH;
+ long buffer = buffers[Platform.getInt(null, bufferIndex)];
+ int start = Platform.getInt(null, bufferIndex +
BaseVariableWidthViewVector.BUF_INDEX_WIDTH);
+ return UTF8String.fromAddress(null, buffer + start, length);
+ }
+ }
+}
diff --git
a/sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h
b/sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h
index 5cfe42b73e84..821e68ca36cc 100644
---
a/sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h
+++
b/sql/core/src/main/resources/org/apache/spark/sql/datasource/spark_datasource.h
@@ -538,8 +538,12 @@ typedef struct SparkDsCommitOffsetInfo {
* Spark itself may read a stream on a thread that the task does not wait for,
for example the one
* of a PipedRDD. The task stays valid until then too, and for a read,
is_interrupted then also
* returns true once the task failed or completed, so the library may stop
reading then. Such an
- * engine may also keep the arrays and the schemas of the stream after it
released the stream, so
- * the release of an array or a schema must not use the stream or the task.
+ * engine may also keep the arrays and the schemas of the stream after it
released the stream, and
+ * so may Spark: when a query stops reading a stream before its end, as with a
LIMIT, Spark may
+ * release the last array that it read only once it no longer references the
batch, from a JVM
+ * Cleaner thread. So the release of an array or a schema must not use the
stream or the task. It
+ * should also be quick and not block, e.g. on a lock or on a runtime that
another thread holds:
+ * Spark shares that thread with the release of the other objects that it no
longer references.
*/
typedef struct SparkDsTaskContext {
/* The size of this struct in the header that Spark was built with, as in
SparkDsHost. */
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/BaseScriptTransformationExec.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/BaseScriptTransformationExec.scala
index 98d775102043..7a5ddf1c41f3 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/BaseScriptTransformationExec.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/BaseScriptTransformationExec.scala
@@ -108,6 +108,21 @@ trait BaseScriptTransformationExec extends UnaryExecNode {
(outputStream, proc, inputStream, stderrBuffer)
}
+ /**
+ * Starts the thread that writes the input rows to the process, and once the
task completes
+ * before it reads the whole output of the process, destroys the process and
interrupts the
+ * thread, as `PipedRDD` does. Otherwise, as under a LIMIT, the process
blocks on writing its
+ * output, and the thread on writing the rest of the input or on reading it,
e.g. from a shuffle
+ * fetch that the completed task no longer serves, so that neither ends. A
process whose whole
+ * output the task read runs to its end, as it may still do work after it
closes its output.
+ */
+ protected def startWriterThread(writerThread:
BaseScriptTransformationWriterThread): Unit = {
+ writerThread.taskContext.addTaskCompletionListener[Unit] { context =>
+ writerThread.stopOnTaskCompletion(context.isFailed())
+ }
+ writerThread.start()
+ }
+
protected def processIterator(
inputIterator: Iterator[InternalRow],
hadoopConf: Configuration): Iterator[InternalRow]
@@ -146,6 +161,7 @@ trait BaseScriptTransformationExec extends UnaryExecNode {
curLine = reader.readLine()
if (curLine == null) {
checkFailureAndPropagate(writerThread, null, proc, stderrBuffer)
+ writerThread.outputReadToEnd = true
return false
}
}
@@ -166,6 +182,10 @@ trait BaseScriptTransformationExec extends UnaryExecNode {
}
val prevLine = curLine
curLine = reader.readLine()
+ if (curLine == null) {
+ // The task may not call `hasNext` again, as under a LIMIT, so
record the end here too.
+ writerThread.outputReadToEnd = true
+ }
processRowWithoutSerde(prevLine)
}
}
@@ -294,6 +314,34 @@ abstract class BaseScriptTransformationWriterThread
extends Thread with Logging
/** Contains the exception thrown while writing the parent iterator to the
external process. */
def exception: Option[Throwable] = Option(_exception)
+ // Whether the task read the output of the process to its end. The process
is then not stopped
+ // when the task completes.
+ @volatile private[sql] var outputReadToEnd = false
+
+ // Whether the process was destroyed as a task that did not fail completed
before the process
+ // ended. The task then no longer reads the output of the process, so the
failure of the thread
+ // and the exit status of the process are expected, and not logged as errors.
+ @volatile private var destroyedOnTaskCompletion = false
+
+ /**
+ * Destroys the process if it is still alive, and interrupts this thread,
once a task that did
+ * not read the whole output of the process completes, failed if
`taskFailed`.
+ */
+ private[execution] def stopOnTaskCompletion(taskFailed: Boolean): Unit = {
+ if (!outputReadToEnd) {
+ if (proc.isAlive) {
+ destroyedOnTaskCompletion = !taskFailed
+ // `Process.destroy()` would close the input of the process, which
waits for a write of
+ // this thread blocked on a full pipe, and so would block the task on
a process that
+ // ignores the signal. Only signal the process instead, and close its
output, which the
+ // completed task no longer reads, to stop a process blocked on
writing it.
+ proc.toHandle.destroy()
+ Utils.tryLogNonFatalError(proc.getInputStream.close())
+ }
+ interrupt()
+ }
+ }
+
protected def processRows(): Unit
protected def processRowsWithoutSerde(): Unit = {
@@ -342,12 +390,29 @@ abstract class BaseScriptTransformationWriterThread
extends Thread with Logging
// Javadoc this call will not throw an exception:
_exception = t
proc.destroy()
- logError(log"Thread-${MDC(CLASS_NAME,
this.getClass.getSimpleName)}-Feed " +
- log"exit cause by: ", t)
+ if (destroyedOnTaskCompletion) {
+ logDebug(s"Thread-${this.getClass.getSimpleName}-Feed exit after the
task completed", t)
+ } else {
+ logError(log"Thread-${MDC(CLASS_NAME,
this.getClass.getSimpleName)}-Feed " +
+ log"exit cause by: ", t)
+ }
} finally {
try {
- Utils.tryLogNonFatalError(outputStream.close())
- if (proc.waitFor() != 0) {
+ if (destroyedOnTaskCompletion) {
+ // The stream may still hold input, which it fails to flush to the
destroyed process.
+ try outputStream.close() catch {
+ case NonFatal(e) => logDebug("Failed to close the input of the
destroyed process", e)
+ }
+ } else {
+ Utils.tryLogNonFatalError(outputStream.close())
+ }
+ val exitCode = try proc.waitFor() catch {
+ // The task completion listener interrupts this thread once it
destroyed the process.
+ // The InterruptedException must not escape the thread, which would
exit the executor
+ // (see SPARK-25158), so wait for the destroyed process again.
+ case _: InterruptedException => proc.waitFor()
+ }
+ if (exitCode != 0 && !destroyedOnTaskCompletion) {
logError(log"${MDC(STDERR, stderrBuffer.toString)}") // log the
stderr circular buffer
}
} catch {
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkScriptTransformationExec.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkScriptTransformationExec.scala
index c79cea40ab02..79ed5d510f62 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkScriptTransformationExec.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/SparkScriptTransformationExec.scala
@@ -66,7 +66,7 @@ case class SparkScriptTransformationExec(
val outputIterator =
createOutputIteratorWithoutSerde(writerThread, inputStream, proc,
stderrBuffer)
- writerThread.start()
+ startWriterThread(writerThread)
outputIterator
}
diff --git
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSource.scala
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSource.scala
index 79850003f143..ea965dc5ab46 100644
---
a/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSource.scala
+++
b/sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSource.scala
@@ -51,7 +51,6 @@ import org.apache.spark.sql.connector.write.{DataWriter,
WriterCommitMessage}
import org.apache.spark.sql.errors.{QueryCompilationErrors,
QueryExecutionErrors}
import org.apache.spark.sql.execution.arrow.ArrowWriter
import
org.apache.spark.sql.execution.datasources.v2.columnar.{ColumnarBatchPlanner,
ColumnarDataSource, ColumnarOnlyPartitionReaderFactory, ColumnarPlannedBatch,
ColumnarStreamReader, ColumnarStreamWriter, ColumnarWriter, ColumnDomain}
-import org.apache.spark.sql.execution.vectorized.ReusedArrowColumnVector
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
import org.apache.spark.sql.util.{ArrowUtils, CaseInsensitiveStringMap}
@@ -646,9 +645,28 @@ object NativeWriterCommitMessage {
* `PipedRDD`, while `DataSourceRDD` closes the reader once the task
completes. The library must
* not get the release of the stream during get_next, and the task context
must stay valid until
* then, so [[close]] then leaves the release to [[next]], once get_next
returns, rather than wait
- * for it and keep the task from completing. That [[next]] then returns false,
or throws the error
- * of its read. A [[next]] called once the reader is closed returns false
without calling the
- * library.
+ * for it and keep the task from completing. That [[next]] then throws the
error of its read, or
+ * fails as a [[next]] called once the reader is closed does, without reading
from the library: so
+ * such a thread does not take the close for the end of the data, whether or
not it was in
+ * get_next then. Script transformation, for example, then destroys its
process.
+ *
+ * Such a thread may also still read the batch that [[next]] returned last
when another thread
+ * closes the reader: script transformation gets its first batch on the task
thread, and reads its
+ * rows on a thread of its own. The column vectors read the buffers of the
batch at their
+ * addresses, so [[close]] frees these buffers at once only if [[next]] was
called again since it
+ * returned the batch, as at the end of the stream, after which consumers no
longer read the
+ * batch. Otherwise, it releases the stream, the dictionaries and the task at
once, since the
+ * arrays of a stream may outlive it, and their release does not use the task
(see
+ * `SparkDsTaskContext` in the header). A Cleaner then frees the buffers of
the batch and the
+ * allocator once the reader is unreachable, which each of its column vectors
keeps it from being,
+ * or once a thread calls [[next]] again, which then fails: that thread no
longer reads the batch.
+ * So a reader closed before the end of its stream, as with a LIMIT, and not
called again holds the
+ * buffers of one batch until a garbage collection, which these buffers do not
trigger: the JVM
+ * does not count them. Under `DataSourceRDD`, only a garbage collection frees
them: its
+ * `PartitionIterator` drops the reader once it closes it, and never calls
[[next]] on it again,
+ * even for a thread that then asks the iterator for the next batch. That is
the only effect of
+ * `DataSourceRDD` here: however the iterator then answers that thread, the
thread does not get
+ * the batch, and a [[next]] called on the reader would free the buffers at
once and fail.
*
* @param kind the kind of the scan, `NativeLibrary.READ_BATCH` or
`READ_MICRO_BATCH`
* @param partition the partition, whose index in the scan the library gets as
`partition_id`
@@ -675,14 +693,25 @@ class NativePartitionReader(
// The task that reads the partition, which the library may use until the
stream is released.
private var task: NativeLibrary.Task = _
private var root: VectorSchemaRoot = _
+ // The column vectors of the batch, which read the buffers of each batch
that `readNext` imports.
+ private var columns: Array[NativeColumnVector] = _
private var batch: ColumnarBatch = _
@GuardedBy("this")
private var closed = false
// Whether a thread is in next. While it is, only that thread uses the
stream and the vectors,
// and it releases them if the reader was closed meanwhile. Otherwise, they
are only released
- // under the lock.
+ // under the lock, except for the buffers of a batch that may still be read
when the reader is
+ // closed, which a Cleaner frees once no thread can use them (see close).
@GuardedBy("this")
private var reading = false
+ // Whether next returned the batch and was not called again since, so that a
consumer may still
+ // read the batch.
+ @GuardedBy("this")
+ private var batchReturned = false
+ // Frees the buffers of the batch that a consumer may still read once the
reader is closed: the
+ // Cleaner does when the reader is unreachable, and next does when it is
called again.
+ @GuardedBy("this")
+ private var batchCleanable: Cleaner.Cleanable = _
// Synchronized so that a close on another thread sees the task and the
vectors.
synchronized {
@@ -691,7 +720,10 @@ class NativePartitionReader(
timeZoneId, stream.memoryAddress())(task = _)
root = VectorSchemaRoot.create(importSchema(), allocator)
checkSchema()
- batch = new
ColumnarBatch(root.getFieldVectors.asScala.map(columnVector).toArray)
+ columns = root.getFieldVectors.asScala.zip(schema.fields).map { case
(vector, field) =>
+ columnVector(vector, field.nullable)
+ }.toArray
+ batch = new ColumnarBatch(columns.toArray[ColumnVector])
} catch {
case e: Throwable =>
close()
@@ -733,22 +765,29 @@ class NativePartitionReader(
* Checks that the data agrees with the nullability of the schema to read: a
column, a field,
* an element or a map value that it declares not nullable has no null,
except where its parent
* is null. Spark relies on the nullability, for example to evaluate
`isnull` of such a column to
- * false without reading it.
+ * false without reading it. `nullCounts` are the null_counts that the
library exported for the
+ * columns.
*/
- private def checkNulls(): Unit = {
- root.getFieldVectors.asScala.zip(schema.fields).foreach { case (vector,
field) =>
- checkNulls(vector, field.dataType, field.nullable, field.name, _ => true)
+ private def checkNulls(nullCounts: Array[Long]): Unit = {
+
root.getFieldVectors.asScala.lazyZip(schema.fields).lazyZip(nullCounts).foreach
{
+ case (vector, field, nullCount) =>
+ checkNulls(vector, field.dataType, field.nullable, field.name, _ =>
true, nullCount)
}
}
- /** `referenced` tells whether a value belongs to a value of the parent that
is not null. */
+ /**
+ * `referenced` tells whether a value belongs to a value of the parent that
is not null.
+ * `nullCount` is the null_count that the library exported for the vector,
if known, and -1
+ * otherwise.
+ */
private def checkNulls(
vector: ValueVector,
dataType: DataType,
nullable: Boolean,
column: String,
- referenced: Int => Boolean): Unit = {
- if (!nullable && vector.getNullCount > 0 &&
+ referenced: Int => Boolean,
+ nullCount: Long = -1): Unit = {
+ if (!nullable && NativeColumnVector.hasNulls(vector, nullCount) &&
(0 until vector.getValueCount).exists(i => vector.isNull(i) &&
referenced(i))) {
throw error(name, "read", s"The column $column has a null, but the
schema to read " +
"declares it not nullable.")
@@ -836,14 +875,20 @@ class NativePartitionReader(
}
/**
- * Wraps a vector of the root, into which every batch is imported. It is not
freeable between
- * batches: Spark must not close it when it moves to the next batch, as
`ColumnarToRowExec` does
- * with the column vectors that are freeable, because closing a struct
column also drops its
- * child column vectors. The reader closes the Arrow vectors at the end.
+ * Wraps a vector of the root, into which every batch is imported, in a
`NativeColumnVector`,
+ * which reads the buffers of the batch that `readNext` imported last, and
keeps the reader
+ * reachable, so that a Cleaner frees these buffers only once the column
vector is unreachable
+ * too (see the class doc). Like the other `ReusedArrowColumnVector`s, it is
not freeable
+ * between batches: Spark must not close it when it moves to the next batch,
as
+ * `ColumnarToRowExec` does with the column vectors that are freeable,
because closing a struct
+ * column also drops its child column vectors. The reader closes the Arrow
vectors at the end.
+ * `nullable` is the nullability of the column in the schema to read, which
`checkNulls` enforces
+ * on each batch after the column vector is refreshed: the batch has no rows
until the check
+ * passes.
*/
- private def columnVector(vector: FieldVector): ColumnVector = {
+ private def columnVector(vector: FieldVector, nullable: Boolean):
NativeColumnVector = {
try {
- new ReusedArrowColumnVector(vector)
+ NativeColumnVector.create(vector, nullable, this)
} catch {
case NonFatal(e) =>
throw QueryExecutionErrors.nativeDataSourceError("read", name,
@@ -853,20 +898,50 @@ class NativePartitionReader(
}
override def next(): Boolean = {
- // A reader that was closed while it read has released the batch that it
read.
- startReading() && Utils.tryWithSafeFinally(readNext())(stopReading()) &&
synchronized(!closed)
+ startReading()
+ val hasBatch = Utils.tryWithSafeFinally(readNext())(stopReading())
+ synchronized {
+ // A reader that was closed while it read has released the batch that it
read, and fails as
+ // it does for a next called once it is closed (see the class doc).
+ if (closed) {
+ throw closedError()
+ }
+ batchReturned = hasBatch
+ batchReturned
+ }
}
- private def startReading(): Boolean = synchronized {
- reading = !closed
- reading
+ /**
+ * Fails once the reader is closed. In either case, the caller no longer
reads the batch that
+ * next returned last, if any, so a closed reader frees its buffers at once.
This assumes that no
+ * other thread still reads that batch, as an open reader does when it
imports the next batch,
+ * which releases the buffers of the previous one: a consumer that hands a
batch to another
+ * thread must not call next until that thread is done with the batch.
+ */
+ private def startReading(): Unit = synchronized {
+ if (closed) {
+ if (batchCleanable != null) {
+ // The Cleaner action does not refer to the batch, which then has no
rows, so that it is
+ // not read at the freed addresses.
+ batch.setNumRows(0)
+ batchCleanable.clean()
+ }
+ throw closedError()
+ }
+ reading = true
+ batchReturned = false
}
+ // Not an internal error: a thread that the task does not wait for gets it
as the task completes.
+ private def closedError(): Throwable = error(name, "read", "The partition
reader is closed.")
+
private def stopReading(): Unit = synchronized {
reading = false
if (closed) {
- // The reader was closed by another thread, which no longer gets a
failure from here.
- Utils.tryLogNonFatalError(closeResources())
+ // The reader was closed by another thread, which no longer gets a
failure from here. No
+ // consumer reads the batch: next does not return the one that it read,
and it was called
+ // since it returned the previous one.
+ Utils.tryLogNonFatalError(closeResources(freeBatch = true))
}
}
@@ -879,15 +954,19 @@ class NativePartitionReader(
// The end of the stream.
false
} else {
- try {
+ val nullCounts = try {
checkArrays(snapshot)
} catch {
case e: Throwable =>
array.release()
throw e
}
+ // The import releases the buffers of the previous batch: the batch
has no rows until the
+ // new one passes the check, and the column vectors read its buffers
before the check.
+ batch.setNumRows(0)
call(name, "read")(Data.importIntoVectorSchemaRoot(allocator, array,
root, dictionaries))
- checkNulls()
+ columns.zip(nullCounts).foreach { case (column, nullCount) =>
column.refresh(nullCount) }
+ checkNulls(nullCounts)
batch.setNumRows(root.getRowCount)
true
}
@@ -915,8 +994,9 @@ class NativePartitionReader(
* which also rejects them, the nulls are counted when the library did
not count them.
* The buffers are not checked, since the C data interface does not carry
their sizes: Arrow
* Java takes them from the lengths, so the library must export buffers that
hold every value.
+ * Returns the null_count that the library exported for each column.
*/
- private def checkArrays(batch: ArrowArray.Snapshot): Unit = {
+ private def checkArrays(batch: ArrowArray.Snapshot): Array[Long] = {
// The arrays of the children, one for each field of the type: Arrow Java
only checks their
// number when an array has children, and imports the missing columns of a
batch as nulls.
def children(
@@ -1020,15 +1100,16 @@ class NativePartitionReader(
"but Spark only reads batches without null rows: mark the values of
the columns as null " +
"instead.")
}
- val columns = root.getSchema.getFields.size
- children(batch, columns, "The batch", s"the schema has $columns columns")
- .zip(root.getSchema.getFields.asScala).foreach { case (column, field)
=>
+ val numColumns = root.getSchema.getFields.size
+ val arrays = children(batch, numColumns, "The batch", s"the schema has
$numColumns columns")
+ arrays.zip(root.getSchema.getFields.asScala).foreach { case (column,
field) =>
if (column.length < batch.length) {
throw error(name, "read", s"The column ${field.getName} has a length
of " +
s"${column.length}, but the batch has a length of ${batch.length}.")
}
checkColumn(column, field, field.getName)
}
+ arrays.map(_.null_count).toArray
}
override def get(): ColumnarBatch = batch
@@ -1036,16 +1117,27 @@ class NativePartitionReader(
override def close(): Unit = synchronized {
if (!closed) {
closed = true
+ // A thread in next releases the reader once get_next returns, see
stopReading. Otherwise, a
+ // consumer may still read the batch that next returned, unless next was
called since.
if (!reading) {
- closeResources()
+ closeResources(freeBatch = !batchReturned)
}
}
}
- private def closeResources(): Unit = {
+ /**
+ * Releases the stream, the dictionaries and the task, and frees the buffers
of the batch and then
+ * the allocator: at once with `freeBatch`, and otherwise once the reader is
unreachable or next
+ * is called again, as a consumer may still read the batch (see the class
doc).
+ */
+ private def closeResources(freeBatch: Boolean): Unit = {
Utils.tryWithSafeFinally {
Utils.tryWithSafeFinally {
- if (root != null) {
+ if (freeBatch && root != null) {
+ // The batch has no rows, so that it is not read at the freed
addresses.
+ if (batch != null) {
+ batch.setNumRows(0)
+ }
root.close()
}
dictionaries.close()
@@ -1059,7 +1151,15 @@ class NativePartitionReader(
if (task != null) {
task.close()
}
- Utils.tryLogNonFatalError(allocator.close())
+ if (freeBatch) {
+ Utils.tryLogNonFatalError(allocator.close())
+ } else {
+ // The action must not refer to the reader, which would then never
become unreachable.
+ val (batchRoot, batchAllocator) = (root, allocator)
+ batchCleanable = NativeHandle.cleaner.register(this, () =>
+ Utils.tryLogNonFatalError(
+
Utils.tryWithSafeFinally(batchRoot.close())(batchAllocator.close())))
+ }
}
}
}
@@ -1380,7 +1480,9 @@ final class NativeHandle(handle: Long, release: Long =>
Unit) {
}
object NativeHandle extends Logging {
- private val cleaner = Cleaner.create()
+ // Also frees the buffers of the batches that may still be read when their
readers are closed,
+ // see `NativePartitionReader`.
+ private[ffi] val cleaner = Cleaner.create()
// Must not refer to the handle, which would then never become unreachable.
private class State(value: Long, release: Long => Unit) extends Runnable {
diff --git
a/sql/core/src/test/resources/native-datasource/test_native_datasource.cc
b/sql/core/src/test/resources/native-datasource/test_native_datasource.cc
index 69b29ab6b940..dd3dea015bc3 100644
--- a/sql/core/src/test/resources/native-datasource/test_native_datasource.cc
+++ b/sql/core/src/test/resources/native-datasource/test_native_datasource.cc
@@ -22,21 +22,21 @@
// native_range Reads rows [0, end) with columns of several types.
Supports column and limit
// pushdown. With the option "extra", the schema has one
more column: "map" adds a
// map whose entry fields are named "keys" and "values", as
arrow-rs names them,
-// "struct" adds a struct, "decimal256" adds a decimal256,
"listview" adds a list
-// view, "largelist" adds a large list, and "dictionary"
adds a dictionary-encoded
-// string column, whose data Spark rejects before reading
it. With the option
-// "slice", the columns of the batches have an offset of 1.
With the option
-// "short", an array of the batches has one value fewer than
its parent refers to,
-// although its buffers hold them all: "id" shortens the
column id, "entries" the
-// entries of the map and their fields, and "values" the
values of the entries.
-// "children" exports the batches without their columns,
with n_children = 0,
-// "buffers" exports the map with a NULL pointer to its
buffers, and
-// "batch_buffers" the batches with one. With the option
"null_rows", the struct
-// of a batch has a validity buffer that marks its first row
as null, and a
-// null_count of 1 for "count" or -1 for "unknown";
"unknown_valid" has one
-// without nulls and a null_count of -1, and "no_buffer" a
null_count of -1
-// without a validity buffer. "column" gives the first
column, which has no
-// validity buffer, a null_count of -1 instead. With the
option
+// "struct" adds a struct, "decimal" adds a decimal128,
"decimal256" adds a
+// decimal256, "listview" adds a list view, "largelist" adds
a large list, and
+// "dictionary" adds a dictionary-encoded string column,
whose data Spark rejects
+// before reading it. With the option "slice", the columns
of the batches have an
+// offset of 1. With the option "short", an array of the
batches has one value
+// fewer than its parent refers to, although its buffers
hold them all: "id"
+// shortens the column id, "entries" the entries of the map
and their fields, and
+// "values" the values of the entries. "children" exports
the batches without
+// their columns, with n_children = 0, "buffers" exports the
map with a NULL
+// pointer to its buffers, and "batch_buffers" the batches
with one. With the
+// option "null_rows", the struct of a batch has a validity
buffer that marks its
+// first row as null, and a null_count of 1 for "count" or
-1 for "unknown";
+// "unknown_valid" has one without nulls and a null_count of
-1, and "no_buffer" a
+// null_count of -1 without a validity buffer. "column"
gives the first column,
+// which has no validity buffer, a null_count of -1 instead.
With the option
// "wait_for_interrupt", the stream of a partition creates
the file
// <wait_for_interrupt>.waiting, waits until its task is
killed, and then creates
// the file <wait_for_interrupt> and fails. With the option
"released_path",
@@ -46,10 +46,10 @@
// minute; with the option "fail" set to "slow_read", each
get_next then fails.
// After the wait, it creates the file
<slow_read>.interrupted with what
// is_interrupted returns for the task context, "true" once
the task ended.
-// Releasing the stream creates the file <slow_read>, which
says
-// whether Spark released it "during get_next", which it
must not, or "after
-// get_next" otherwise. With the option
"ignore_read_schema", read returns all
-// the columns of the reader, rather than only those of the
schema to read.
+// Releasing the stream creates the file <slow_read>, which
says whether Spark
+// released it "during get_next", which it must not, or
"after get_next"
+// otherwise. With the option "ignore_read_schema", read
returns all the columns
+// of the reader, rather than only those of the schema to
read.
// It uses the domain of id that Spark pushes to skip the
blocks of "block"
// rows, 10 by default, whose ids are not in it: it then
reads one partition
// for each block that may match, with all its rows. With
the option
@@ -197,6 +197,7 @@ const ColumnType kColumns[] = {
const std::map<std::string, ColumnType> kExtraColumns = {
{"map", {"m", "+m"}}, // map<string, bigint>: {"k<id>":
id}
{"struct", {"st", "+s"}}, // struct<a: bigint, b: string>:
{id, "s<id>"}
+ {"decimal", {"d", "d:10,2"}}, // decimal(10, 2): id
{"decimal256", {"dec", "d:10,2,256"}}, // decimal256(10, 2): id
{"listview", {"lv", "+vl"}}, // list_view<bigint>: [id]
{"largelist", {"ll", "+L"}}, // large_list<bigint>, without data
@@ -465,13 +466,15 @@ void exportColumn(const std::string& name, int64_t lo,
int64_t hi, ArrowArray* o
initArray(addChild(out), n, 0, {no_validity, toBytes(ids)});
initArray(addChild(out), n, 0,
{no_validity, toBytes(offsets),
std::vector<uint8_t>(chars.begin(), chars.end())});
- } else if (name == "dec") {
- // 256-bit little-endian unscaled values of the scale 2.
+ } else if (name == "d" || name == "dec") {
+ // 128-bit or 256-bit little-endian unscaled values of the scale 2.
std::vector<int64_t> words;
for (int64_t id = lo; id < hi; id++) {
int64_t unscaled = id * 100;
int64_t sign = unscaled < 0 ? -1 : 0;
- words.insert(words.end(), {unscaled, sign, sign, sign});
+ words.push_back(unscaled);
+ size_t high_words = name == "d" ? 1 : 3;
+ words.insert(words.end(), high_words, sign);
}
initArray(out, n, 0, {no_validity, toBytes(words)});
} else if (name == "lv") {
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/BaseScriptTransformationSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/BaseScriptTransformationSuite.scala
index e95f093c8c32..2ed4a0129431 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/BaseScriptTransformationSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/BaseScriptTransformationSuite.scala
@@ -20,11 +20,15 @@ package org.apache.spark.sql.execution
import java.sql.{Date, Timestamp}
import java.time.{Duration, Period}
+import scala.jdk.CollectionConverters._
+
+import org.apache.logging.log4j.Level
import org.json4s.DefaultFormats
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._
import org.scalatest.Assertions._
import org.scalatest.exceptions.TestFailedException
+import org.scalatest.time.SpanSugar._
import org.apache.spark.{SparkException, SparkRuntimeException,
SparkThrowable, TaskContext,
TestUtils}
@@ -432,6 +436,41 @@ abstract class BaseScriptTransformationSuite extends
QueryTest {
assert(uncaughtExceptionHandler.exception.isEmpty)
}
+ test("TRANSFORM destroys the script when its task completes before reading
all its output") {
+ assume(TestUtils.testCommandAvailable("/bin/bash"))
+
+ def writerThreads(): Set[Thread] = Thread.getAllStackTraces.keySet.asScala
+ .filter(thread => thread.getName.endsWith("WriterThread-Feed") &&
thread.isAlive).toSet
+ val before = writerThreads()
+ // The script echoes much more input than the pipes hold, while the task
reads one row of its
+ // output: the script then blocks on writing its output, and the writer
thread on writing the
+ // input, until the script is destroyed.
+ val plan = createScriptTransformationExec(
+ script = "cat",
+ output = Seq(AttributeReference("id", StringType)()),
+ child = spark.range(0, 1000000, 1, 1).queryExecution.sparkPlan,
+ ioschema = defaultIOSchema)
+ val logAppender = new LogAppender("the writer thread of a destroyed
script")
+ logAppender.setThreshold(Level.ERROR)
+ withLogAppender(logAppender) {
+ assert(plan.execute().mapPartitions(rows =>
Iterator(rows.take(1).size)).collect() ===
+ Array(1))
+ eventually(timeout(60.seconds)) {
+ assert((writerThreads() -- before).isEmpty)
+ }
+ }
+ // The interrupt of the writer thread does not escape it, and its failure
to write to the
+ // destroyed script is not logged as an error. The writer threads of
earlier tests, which have
+ // the same name, may still log, so only those of this test are checked.
+ assert(uncaughtExceptionHandler.exception.isEmpty)
+ val earlierThreads = before.map(_.threadId())
+ val errors = logAppender.loggingEvents.filter { event =>
+ event.getThreadName.endsWith("WriterThread-Feed") &&
+ !earlierThreads.contains(event.getThreadId)
+ }
+ assert(errors.isEmpty,
errors.map(_.getMessage.getFormattedMessage).mkString("\n"))
+ }
+
def testBasicInputDataTypesWith(serde: ScriptTransformationIOSchema,
testName: String): Unit = {
test(s"SPARK-32400: TRANSFORM should support basic data types as input
($testName)") {
assume(TestUtils.testCommandAvailable("python3"))
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeColumnVectorSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeColumnVectorSuite.scala
new file mode 100644
index 000000000000..951341a6474c
--- /dev/null
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeColumnVectorSuite.scala
@@ -0,0 +1,420 @@
+/*
+ * 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.ffi
+
+import java.math.{BigDecimal => JavaBigDecimal}
+import java.nio.charset.StandardCharsets
+
+import scala.util.{Failure, Success, Try, Using}
+
+import org.apache.arrow.memory.{BufferAllocator, RootAllocator}
+import org.apache.arrow.vector._
+import org.apache.arrow.vector.complex.StructVector
+import org.apache.arrow.vector.types.pojo.{ArrowType, FieldType}
+
+import org.apache.spark.SparkFunSuite
+import org.apache.spark.sql.catalyst.expressions.UnsafeRow
+import org.apache.spark.sql.catalyst.expressions.codegen.UnsafeRowWriter
+import org.apache.spark.sql.execution.vectorized.{OnHeapColumnVector,
ReusedArrowColumnVector}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{Decimal, DecimalType}
+import org.apache.spark.sql.vectorized.ArrowColumnVector
+
+/**
+ * Checks that a [[NativeColumnVector]] reads the nulls and values that an
[[ArrowColumnVector]]
+ * of the same Arrow vector reads.
+ */
+class NativeColumnVectorSuite extends SparkFunSuite {
+
+ // The rows of the batches, more than 8 so that the validity bitmaps have
several bytes, and the
+ // rows that are null.
+ private val rows = 0 until 20
+ private val nulls = Set(1, 8, 9, 15)
+
+ private def withAllocator(f: BufferAllocator => Unit): Unit = {
+ Using.resource(new RootAllocator())(f)
+ }
+
+ /** The column vector of `vector`, refreshed as the reader refreshes it
after an import. */
+ private def native(vector: ValueVector, nullable: Boolean = true):
NativeColumnVector = {
+ val column = NativeColumnVector.create(vector, nullable, null)
+ column.refresh(-1)
+ column
+ }
+
+ /** Checks that `column` reads the nulls and the values of `vector` as
ArrowColumnVector does. */
+ private def checkSame(vector: ValueVector, column: ArrowColumnVector)(
+ value: (ArrowColumnVector, Int) => Any): Unit = {
+ val expected = new ArrowColumnVector(vector)
+ (0 until vector.getValueCount).foreach { row =>
+ assert(column.isNullAt(row) === expected.isNullAt(row), s"row $row")
+ if (!expected.isNullAt(row)) {
+ assert(value(column, row) === value(expected, row), s"row $row")
+ }
+ }
+ }
+
+ /** Sets the rows of a vector: nulls, and `set` for the other rows. */
+ private def fill[V <: BaseFixedWidthVector](vector: V)(set: (V, Int) =>
Unit): V = {
+ vector.allocateNew(rows.size)
+ rows.foreach { row => if (nulls(row)) vector.setNull(row) else set(vector,
row) }
+ vector.setValueCount(rows.size)
+ vector
+ }
+
+ /** Checks a vector whose values the column vector reads at the addresses of
its buffers. */
+ private def checkDirect(vector: ValueVector)(value: (ArrowColumnVector, Int)
=> Any): Unit = {
+ Using.resource(vector) { vector =>
+ val column = native(vector)
+ assert(column.getClass !== classOf[NativeColumnVector],
vector.getClass.getName)
+ checkSame(vector, column)(value)
+ }
+ }
+
+ test("booleans, integers, floats, dates and timestamps") {
+ withAllocator { allocator =>
+ val bytes = Seq(Byte.MinValue, -1: Byte, 0: Byte, 1: Byte, Byte.MaxValue)
+ val shorts = Seq(Short.MinValue, -1: Short, 0: Short, 1: Short,
Short.MaxValue)
+ val ints = Seq(Int.MinValue, -1, 0, 1, Int.MaxValue)
+ val longs = Seq(Long.MinValue, -1L, 0L, 1L, Long.MaxValue)
+ val floats = Seq(0.0f, -0.0f, Float.NaN, Float.NegativeInfinity,
Float.MinValue, 1.5f)
+ val doubles = Seq(0.0, -0.0, Double.NaN, Double.PositiveInfinity,
Double.MaxValue, -2.5)
+
+ checkDirect(fill(new BitVector("b", allocator))((v, row) => v.set(row,
row % 3 % 2))) {
+ _.getBoolean(_)
+ }
+ checkDirect(fill(new TinyIntVector("i8", allocator)) { (v, row) =>
+ v.set(row, bytes(row % bytes.size))
+ })(_.getByte(_))
+ checkDirect(fill(new SmallIntVector("i16", allocator)) { (v, row) =>
+ v.set(row, shorts(row % shorts.size))
+ })(_.getShort(_))
+ checkDirect(fill(new IntVector("i32", allocator))((v, row) => v.set(row,
ints(row % 5)))) {
+ _.getInt(_)
+ }
+ checkDirect(fill(new DateDayVector("day", allocator))((v, row) =>
v.set(row, row - 9))) {
+ _.getInt(_)
+ }
+ checkDirect(fill(new BigIntVector("i64", allocator)) { (v, row) =>
+ v.set(row, longs(row % longs.size))
+ })(_.getLong(_))
+ checkDirect(fill(new TimeStampMicroTZVector("ts", allocator, "UTC")) {
(v, row) =>
+ v.set(row, longs(row % longs.size))
+ })(_.getLong(_))
+ checkDirect(fill(new TimeStampMicroVector("ntz", allocator)) { (v, row)
=>
+ v.set(row, longs(row % longs.size))
+ })(_.getLong(_))
+ // The bits, so that NaN equals NaN.
+ checkDirect(fill(new Float4Vector("f32", allocator)) { (v, row) =>
+ v.set(row, floats(row % floats.size))
+ })((column, row) =>
java.lang.Float.floatToRawIntBits(column.getFloat(row)))
+ checkDirect(fill(new Float8Vector("f64", allocator)) { (v, row) =>
+ v.set(row, doubles(row % doubles.size))
+ })((column, row) =>
java.lang.Double.doubleToRawLongBits(column.getDouble(row)))
+ }
+ }
+
+ test("strings and string views, in several batches") {
+ // Values that a view holds, of up to 12 bytes, and longer ones that a
data buffer holds, with
+ // characters of 2 bytes in UTF-8.
+ val (acute, grave) = (0xe9.toChar.toString, 0xe8.toChar.toString)
+ val short = Seq(Some(""), Some("a"), None, Some("twelve bytes"),
Some(acute + grave), None)
+ val long = Seq(Some("thirteen byte"), None, Some(acute * 40), Some("a long
value " * 20))
+ // Values that do not fit in one data buffer of a view vector, which holds
them in several.
+ val spread = Seq(Some("a" * 100000), None, Some(acute * 50000), Some("c" *
100000))
+ withAllocator { allocator =>
+ def check(vector: FieldVector)(set: (Int, Array[Byte]) => Unit, setNull:
Int => Unit)
+ : Unit = {
+ Using.resource(vector) { vector =>
+ val column = NativeColumnVector.create(vector, true, null)
+ assert(column.getClass !== classOf[NativeColumnVector],
vector.getClass.getName)
+ // Batches without and with data buffers, with values of both kinds,
and with values in
+ // several data buffers.
+ Seq(short, long, short ++ long, spread).foreach { values =>
+ vector.clear()
+ vector.allocateNew()
+ values.zipWithIndex.foreach {
+ case (Some(value), row) => set(row,
value.getBytes(StandardCharsets.UTF_8))
+ case (None, row) => setNull(row)
+ }
+ vector.setValueCount(values.size)
+ vector match {
+ case views: ViewVarCharVector if values eq spread =>
+ assert(views.getDataBuffers.size > 1)
+ case _ =>
+ }
+ column.refresh(-1)
+ checkSame(vector, column)(_.getUTF8String(_))
+ assert(column.getUTF8String(values.indexOf(None)) === null)
+ }
+ }
+ }
+ val strings = new VarCharVector("s", allocator)
+ check(strings)(strings.setSafe(_, _), strings.setNull)
+ val views = new ViewVarCharVector("v", allocator)
+ check(views)(views.setSafe(_, _), views.setNull)
+ }
+ }
+
+ private def withDecimalVector(precision: Int, scale: Int)(f: DecimalVector
=> Unit): Unit = {
+ withAllocator { allocator =>
+ Using.resource(new DecimalVector("decimal", allocator, precision,
scale))(f)
+ }
+ }
+
+ /**
+ * Checks that `column` returns the decimal of a row that `expected`, an
[[ArrowColumnVector]] of
+ * the same vector, returns, as Spark uses it, or fails as it does. Its
integral conversions are
+ * those of the decimal of Spark's own column vectors, which hold the
decimals that a long holds,
+ * of a scale from 0 to their precision, as longs, while ArrowColumnVector
holds BigDecimals,
+ * which Decimal rounds to bytes, shorts and ints through doubles.
+ */
+ private def checkDecimal(
+ expected: ArrowColumnVector,
+ column: ArrowColumnVector,
+ row: Int,
+ precision: Int,
+ scale: Int): Unit = {
+ def result(decimal: Decimal): (JavaBigDecimal, Int, Int, Long, UnsafeRow)
= {
+ val writer = new UnsafeRowWriter(1)
+ writer.write(0, decimal, precision, scale)
+ (decimal.toJavaBigDecimal, decimal.precision, decimal.scale,
decimal.toLong, writer.getRow)
+ }
+ def rounded(decimal: Decimal): Seq[Either[String, Long]] = {
+ Seq[Decimal => Long](_.roundToByte(), _.roundToShort(), _.roundToInt(),
_.roundToLong())
+ .map(round => Try(round(decimal)).toEither.left.map(e =>
s"${e.getClass}: ${e.getMessage}"))
+ }
+ def own(decimal: Decimal): Decimal = {
+ if (0 <= scale && scale <= precision && precision <=
Decimal.MAX_LONG_DIGITS) {
+ Decimal.createUnsafe(decimal.toUnscaledLong, precision, scale)
+ } else {
+ decimal
+ }
+ }
+ Try(result(expected.getDecimal(row, precision, scale))) match {
+ case Success(value) =>
+ val decimal = column.getDecimal(row, precision, scale)
+ assert(result(decimal) === value)
+ assert(rounded(decimal) === rounded(own(expected.getDecimal(row,
precision, scale))))
+ case Failure(error) =>
+ val actual = intercept[Exception](result(column.getDecimal(row,
precision, scale)))
+ assert(actual.getClass === error.getClass)
+ assert(actual.getMessage === error.getMessage)
+ }
+ }
+
+ test("decimals in and out of their precision, at other precisions and
scales") {
+ for (precision <- 1 to Decimal.MAX_LONG_DIGITS; scale <- Set(0, precision
/ 2, precision)) {
+ withDecimalVector(precision, scale) { vector =>
+ val limit = BigInt(10).pow(precision)
+ // The bounds of the precision, values out of it, which the byte
setter permits, and
+ // values that a long does not hold.
+ val values = Seq(BigInt(0), BigInt(1), BigInt(-1), limit - 1, -(limit
- 1), limit, -limit,
+ BigInt(Long.MaxValue), BigInt(Long.MinValue), (BigInt(1) << 64) + 7)
+ vector.allocateNew(values.size + 1)
+ values.zipWithIndex.foreach { case (value, row) =>
+ vector.setBigEndian(row, value.toByteArray)
+ }
+ vector.setNull(values.size)
+ vector.setValueCount(values.size + 1)
+ val expected = new ArrowColumnVector(vector)
+ val column = native(vector)
+ assert(column.getClass !== classOf[NativeColumnVector])
+ val requested = Seq((precision, scale), (Decimal.MAX_LONG_DIGITS,
scale), (38, scale),
+ (precision + 1, scale), (precision, scale + 1))
+ for (row <- values.indices; (p, s) <- requested) {
+ checkDecimal(expected, column, row, p, s)
+ }
+ assert(column.getDecimal(values.size, precision, scale) === null)
+ }
+ }
+ }
+
+ test("decimals of a negative scale") {
+ val conf = new SQLConf
+ val key = SQLConf.LEGACY_ALLOW_NEGATIVE_SCALE_OF_DECIMAL_ENABLED.key
+ SQLConf.withExistingConf(conf) {
+ conf.setConfString(key, "true")
+ withDecimalVector(5, -2) { vector =>
+ vector.allocateNew(1)
+ vector.set(0, new JavaBigDecimal("1.23E+4"))
+ vector.setValueCount(1)
+ val expected = new ArrowColumnVector(vector)
+ val column = native(vector)
+ Seq((5, -2), (8, 0), (5, -3)).foreach { case (precision, scale) =>
+ checkDecimal(expected, column, 0, precision, scale)
+ }
+ assert(column.getDecimal(0, 5, -2).toLong === 12300L)
+ conf.setConfString(key, "false")
+ checkDecimal(expected, column, 0, 5, -2)
+ }
+ }
+ }
+
+ test("decimals that a long holds round to integers as those of Spark's own
column vectors") {
+ // The decimals of Spark's own column vectors and of the native one, of
OnHeapColumnVector and
+ // NativeColumnVector, hold longs, which Decimal rounds exactly.
+ def decimals(value: String, scale: Int)(f: (Decimal, Decimal) => Unit):
Unit = {
+ val precision = Decimal.MAX_LONG_DIGITS
+ withDecimalVector(precision, scale) { vector =>
+ vector.allocateNew(1)
+ vector.set(0, new JavaBigDecimal(value))
+ vector.setValueCount(1)
+ Using.resource(new OnHeapColumnVector(1, DecimalType(precision,
scale))) { own =>
+ own.putDecimal(0, Decimal(value), precision)
+ f(own.getDecimal(0, precision, scale), native(vector).getDecimal(0,
precision, scale))
+ }
+ }
+ }
+ decimals("123456789.999999999", 9) { (own, column) =>
+ assert(column.roundToInt() === own.roundToInt())
+ }
+ decimals("127.999999999999999", 15) { (own, column) =>
+ assert(column.roundToByte() === own.roundToByte())
+ }
+ }
+
+ test("the decimals of the fields of a struct still hold BigDecimals") {
+ // ArrowColumnVector reads the fields of a struct, so that their decimals,
unlike those of a
+ // top-level column, hold BigDecimals. Decimal rounds those to integers
through doubles until
+ // SPARK-60843, so that the nested decimal then rounds to 123456790, a
known inconsistency,
+ // which this test does not pin.
+ withAllocator { allocator =>
+ Using.resource(StructVector.empty("struct", allocator)) { struct =>
+ val field = FieldType.nullable(new ArrowType.Decimal(18, 9, 128))
+ val child = struct.addOrGet("d", field, classOf[DecimalVector])
+ struct.allocateNew()
+ child.setSafe(0, new JavaBigDecimal("123456789.999999999"))
+ struct.setIndexDefined(0)
+ child.setValueCount(1)
+ struct.setValueCount(1)
+ val top = native(child).getDecimal(0, 18, 9)
+ val nested = native(struct).getChild(0).getDecimal(0, 18, 9)
+ assert(top.toDebugString === "Decimal(compact, 123456789999999999, 18,
9)")
+ assert(top.roundToInt() === 123456789)
+ assert(nested.toDebugString === "Decimal(expanded,
123456789.999999999, 18, 9)")
+ }
+ }
+ }
+
+ test("reads the buffers of the batch that the reader imported last") {
+ withAllocator { allocator =>
+ Using.resource(new BigIntVector("id", allocator)) { vector =>
+ val column = NativeColumnVector.create(vector, true, null)
+ // Each batch has other buffers: with nulls, without nulls, empty, and
larger.
+ val batches = Seq(
+ Seq(Some(1L), None, Some(3L)),
+ Seq(Some(4L), Some(5L)),
+ Seq.empty[Option[Long]],
+ (0L until 1000L).map(id => Option.when(id % 7 != 0)(id)))
+ batches.foreach { values =>
+ vector.clear()
+ vector.allocateNew(values.size)
+ values.zipWithIndex.foreach {
+ case (Some(value), row) => vector.set(row, value)
+ case (None, row) => vector.setNull(row)
+ }
+ vector.setValueCount(values.size)
+ column.refresh(-1)
+ checkSame(vector, column)(_.getLong(_))
+ }
+ }
+ }
+ }
+
+ test("take the null count that the library exported, and count the nulls
without one") {
+ withAllocator { allocator =>
+ Using.resource(new IntVector("i", allocator)) { vector =>
+ vector.allocateNew(2)
+ vector.set(0, 1)
+ vector.setNull(1)
+ vector.setValueCount(2)
+ val column = NativeColumnVector.create(vector, true, null)
+ column.refresh(1)
+ assert(column.isNullAt(1))
+ // The C data interface requires a null_count of 0 to be exact, so the
column vector does
+ // not read the validity bitmap then.
+ column.refresh(0)
+ assert(!column.isNullAt(1))
+ column.refresh(-1)
+ assert(column.isNullAt(1))
+ }
+ }
+ }
+
+ test("a column that the schema declares not nullable") {
+ withAllocator { allocator =>
+ Using.resource(new IntVector("k", allocator)) { vector =>
+ vector.allocateNew(rows.size)
+ rows.foreach(row => vector.set(row, row))
+ vector.setValueCount(rows.size)
+ val column = native(vector, nullable = false)
+ assert(column.getClass !== classOf[NativeColumnVector])
+ checkSame(vector, column)(_.getInt(_))
+ // The column vector does not count the nulls of such a column when
the reader refreshes
+ // it: the reader then checks that the batch has no null, and the
batch has no rows until
+ // that check passes.
+ vector.setNull(1)
+ column.refresh(-1)
+ assert(!column.isNullAt(1))
+ }
+ }
+ }
+
+ test("other types, through ArrowColumnVector") {
+ withAllocator { allocator =>
+ Using.resource(new VarBinaryVector("bytes", allocator)) { vector =>
+ vector.allocateNew()
+ vector.setSafe(0, Array[Byte](1, 2))
+ vector.setNull(1)
+ vector.setValueCount(2)
+ val column = native(vector)
+ assert(column.getClass === classOf[NativeColumnVector])
+ checkSame(vector, column)(_.getBinary(_).toSeq)
+ }
+ Using.resource(StructVector.empty("struct", allocator)) { struct =>
+ val field = FieldType.nullable(new ArrowType.Int(64, true))
+ val child = struct.addOrGet("a", field, classOf[BigIntVector])
+ struct.allocateNew()
+ child.setSafe(0, 7L)
+ struct.setIndexDefined(0)
+ struct.setNull(1)
+ child.setValueCount(2)
+ struct.setValueCount(2)
+ val column = native(struct)
+ assert(column.getClass === classOf[NativeColumnVector])
+ assert(!column.isNullAt(0) && column.isNullAt(1))
+ assert(column.getChild(0).getLong(0) === 7L)
+ }
+ }
+ }
+
+ test("is reused by the reader, so that Spark does not close it") {
+ withAllocator { allocator =>
+ Using.resource(fill(new IntVector("k", allocator))((v, row) =>
v.set(row, row))) { vector =>
+ val column = native(vector)
+ assert(column.isInstanceOf[ReusedArrowColumnVector])
+ column.closeIfFreeable()
+ assert(column.getInt(2) === 2)
+ // Nor does a consumer that closes it free the buffers that it reads:
the reader does.
+ column.close()
+ assert(column.getInt(2) === 2)
+ }
+ }
+ }
+}
diff --git
a/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala
b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala
index af01c4980abc..95ae4208fb49 100644
---
a/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala
+++
b/sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/v2/ffi/NativeDataSourceSuite.scala
@@ -46,7 +46,7 @@ import org.apache.spark.sql.classic.{DataFrame, SparkSession}
import org.apache.spark.sql.connector.catalog.SupportsRead
import org.apache.spark.sql.connector.expressions.{Expression => V2Expression,
FieldReference, LiteralValue}
import org.apache.spark.sql.connector.expressions.filter.Predicate
-import org.apache.spark.sql.connector.read.{InputPartition,
SupportsArrowStreamRead, SupportsPushDownRequiredColumns}
+import org.apache.spark.sql.connector.read.{InputPartition, PartitionReader,
SupportsArrowStreamRead, SupportsPushDownRequiredColumns}
import org.apache.spark.sql.connector.read.streaming.{MicroBatchStream,
Offset, ReadLimit, SupportsAdmissionControl}
import org.apache.spark.sql.connector.write.PhysicalWriteInfoImpl
import org.apache.spark.sql.execution.WholeStageCodegenExec
@@ -54,6 +54,7 @@ import org.apache.spark.sql.execution.datasources.DataSource
import org.apache.spark.sql.execution.datasources.v2.{BatchScanExec,
DataSourceV2ScanRelation, MicroBatchScanExec, V2TableWriteExec}
import
org.apache.spark.sql.execution.datasources.v2.columnar.{ColumnarBatchScan,
ColumnarBatchWrite, ColumnarMicroBatchStream, ColumnarScan,
ColumnarScanBuilder, ColumnarStreamingWrite, ColumnarStreamOffset}
import
org.apache.spark.sql.execution.datasources.v2.python.{PythonDataSourceV2,
UserDefinedPythonDataSource}
+import org.apache.spark.sql.execution.python.ArrowEvalPythonExec
import org.apache.spark.sql.execution.streaming.runtime.StreamingQueryWrapper
import org.apache.spark.sql.execution.vectorized.ReusedArrowColumnVector
import org.apache.spark.sql.functions.lit
@@ -124,9 +125,47 @@ class NativeDataSourceSuite extends QueryTest with
SharedSparkSession {
// The test libraries record the calls that the order of the calls of the
header rules out,
// which fail the test that made them.
+ // Each test also checks that the buffers of its readers are freed, see
checkReadersFreed, also
+ // when it fails, and only those of its own readers: a reader that a failing
test leaves behind
+ // is reported with the failure of that test, and does not fail the next one.
private def nativeTest(name: String)(f: => Unit): Unit = test(name) {
assume(toolchain.isDefined, "A C++ compiler and Java 22 or later are
required.")
- try checkingOrderOfCalls(f) finally SparkSession.setActiveSession(spark)
+ val earlierReaders = readerAllocators()
+ try {
+ try {
+ checkingOrderOfCalls(f)
+ } catch {
+ case e: Throwable =>
+ try {
+ checkReadersFreed(earlierReaders)
+ } catch {
+ case leak: Throwable => e.addSuppressed(leak)
+ }
+ throw e
+ }
+ checkReadersFreed(earlierReaders)
+ } finally {
+ SparkSession.setActiveSession(spark)
+ }
+ }
+
+ /**
+ * Checks that the buffers of the readers of native data sources are freed.
A reader closed while
+ * the batch that it returned may still be read, as when a query stops
before the end of a
+ * partition, frees the buffers of the batch once it is unreachable. Each
test checks that they
+ * are freed after it, so that a test that leaks a reader fails, and the
readers of a test are
+ * freed before the next test, see readerAndAllocator, and before the suites
that run next in
+ * this JVM, which may count the memory of Arrow. `earlierReaders` are those
that were not freed
+ * before the test, which a failed test may have left behind, and which it
does not check.
+ */
+ private def checkReadersFreed(earlierReaders: Set[BufferAllocator]): Unit = {
+ if ((readerAllocators() -- earlierReaders).nonEmpty) {
+ eventually(timeout(1.minute), interval(100.milliseconds)) {
+ System.gc()
+ val readers = readerAllocators() -- earlierReaders
+ assert(readers.isEmpty, readers.map(a => s"${a.getName}:
${a.getAllocatedMemory} bytes"))
+ }
+ }
}
// Checks the answer without converting the DataFrame to an RDD: a job
outside of a SQL
@@ -146,6 +185,31 @@ class NativeDataSourceSuite extends QueryTest with
SharedSparkSession {
}.get
}
+ /** The allocators of the readers of native data sources that are not freed
yet. */
+ private def readerAllocators(): Set[BufferAllocator] = {
+ ArrowUtils.rootAllocator.getChildAllocators.asScala
+ .filter(_.getName.startsWith("native data source ")).toSet
+ }
+
+ /**
+ * Creates the reader of a partition of the batch scan of `df`, and returns
it with the allocator
+ * of its buffers, which the reader closes once it frees them.
+ */
+ private def readerAndAllocator(
+ df: DataFrame,
+ partition: Int = 0): (PartitionReader[ColumnarBatch], BufferAllocator) =
{
+ val batch = scan(df).toBatch
+ val (factory, partitions) = (batch.createReaderFactory(),
batch.planInputPartitions())
+ val before = readerAllocators()
+ val reader = factory.createColumnarReader(partitions(partition))
+ val created = readerAllocators() -- before
+ if (created.size != 1) {
+ reader.close()
+ fail(s"The reader has ${created.size} allocators.")
+ }
+ (reader, created.head)
+ }
+
private def expectedRow(id: Long): Row = Row(
id,
(id % 3).toInt,
@@ -155,6 +219,19 @@ class NativeDataSourceSuite extends QueryTest with
SharedSparkSession {
Date.valueOf(LocalDate.ofEpochDay(id)),
Timestamp.from(Instant.ofEpochSecond(id)))
+ /** Checks the failure of a next called once the reader of native_range was
closed. */
+ private def checkClosed(e: Throwable): Unit = e match {
+ case e: SparkRuntimeException =>
+ checkError(
+ exception = e,
+ condition = "NATIVE_DATA_SOURCE_ERROR",
+ parameters = Map(
+ "action" -> "read",
+ "name" -> "native_range",
+ "msg" -> "The partition reader is closed."))
+ case _ => fail(s"Unexpected failure: $e", e)
+ }
+
/** Finds the error with the given condition among the causes of a failure.
*/
private def findError(e: Throwable, condition: String): SparkThrowable = {
Iterator.iterate(e)(_.getCause).takeWhile(_ != null)
@@ -629,20 +706,66 @@ class NativeDataSourceSuite extends QueryTest with
SharedSparkSession {
assert(scan(nested).readSchema() == StructType.fromDDL("st STRUCT<a:
BIGINT, b: STRING>"))
}
+ nativeTest("read the columns at the addresses of their buffers, and decimals
as longs") {
+ val df = range(newSession(defaultPackage), "end" -> "10", "partitions" ->
"1",
+ "extra" -> "decimal")
+ assert(df.schema("d").dataType == DecimalType(10, 2))
+ checkRows(df, (0L until 10L).map { id =>
+ Row.fromSeq(expectedRow(id).toSeq :+ java.math.BigDecimal.valueOf(id *
100, 2))
+ })
+ val batch = scan(df).toBatch
+ val reader =
batch.createReaderFactory().createColumnarReader(batch.planInputPartitions().head)
+ try {
+ assert(reader.next())
+ val columns = (0 until reader.get().numCols()).map(reader.get().column)
+ // The columns of all these types read their buffers through a subclass
of
+ // NativeColumnVector.
+ columns.foreach { column =>
+ assert(column.isInstanceOf[NativeColumnVector] &&
+ column.getClass != classOf[NativeColumnVector],
column.getClass.getName)
+ }
+ // The decimals hold their unscaled longs, as those of Spark's own
column vectors do.
+ (0 until reader.get().numRows()).foreach { row =>
+ assert(columns.last.getDecimal(row, 10, 2).toDebugString ===
+ s"Decimal(compact, ${row * 100}, 10, 2)")
+ }
+ } finally {
+ reader.close()
+ }
+ }
+
nativeTest("reject the data that has nulls where the schema to read has
none") {
// The column name is null for the ids that are multiples of 5.
val session = newSession(defaultPackage)
- val e = intercept[Exception] {
- session.read.schema("id BIGINT, name STRING NOT
NULL").format("native_range")
- .option("end", "4").load().collect()
- }
- checkError(
+ def checkNullError(e: Throwable): Unit = checkError(
exception = findError(e, "NATIVE_DATA_SOURCE_ERROR"),
condition = "NATIVE_DATA_SOURCE_ERROR",
parameters = Map(
"action" -> "read",
"name" -> "native_range",
"msg" -> "The column name has a null, but the schema to read declares
it not nullable."))
+ checkNullError(intercept[Exception] {
+ session.read.schema("id BIGINT, name STRING NOT
NULL").format("native_range")
+ .option("end", "4").load().collect()
+ })
+ // A batch that is rejected after others were read: the second partition
reads the ids 6-7,
+ // 8-9 and 10-11, and the name of id 10 is null.
+ val df = session.read.schema("id BIGINT, name STRING NOT
NULL").format("native_range")
+ .options(Map("end" -> "12", "partitions" -> "2", "batch_size" ->
"2")).load()
+ val batch = scan(df).toBatch
+ val reader =
batch.createReaderFactory().createColumnarReader(batch.planInputPartitions()(1))
+ try {
+ assert(reader.next() && reader.next())
+ assert(reader.get().numRows() == 2)
+ assert(reader.get().column(1).getUTF8String(1).toString == "n9")
+ checkNullError(intercept[Exception](reader.next()))
+ // The batch has no rows, and its column vectors read the buffers of the
rejected batch,
+ // since the import released those of the previous one.
+ assert(reader.get().numRows() == 0)
+ assert(reader.get().column(1).getUTF8String(1).toString == "n11")
+ } finally {
+ reader.close()
+ }
// The fields that are not nullable have no nulls.
checkRows(
session.read.schema("id BIGINT NOT NULL, st STRUCT<a: BIGINT NOT NULL,
b: STRING NOT NULL>")
@@ -689,16 +812,26 @@ class NativeDataSourceSuite extends QueryTest with
SharedSparkSession {
name = "native_str", returnType = Some(StringType))
IntegratedUDFTestUtils.registerTestUDF(udf, session)
// One batch, two, and many. The test UDF casts its input to string: on
the string column
- // name, the cast is removed, so the batches go to Python as they are.
- Seq(100, 200, 200000).foreach { end =>
- val rows = range(session, "end" -> end.toString, "partitions" -> "1",
"batch_size" -> "100")
- .selectExpr("id", "name", "native_str(name) AS udf_name").collect()
- assert(rows.map(_.getLong(0)).toSeq == (0L until end))
- rows.foreach { row =>
- val id = row.getLong(0)
- val name = if (id % 5 == 0) null else s"n$id"
- assert(row.getString(1) == name, s"name mismatch for id $id")
- assert(row.getString(2) == name, s"UDF mismatch for id $id")
+ // name, the cast is removed, so the batches go to Python as they are.
With columnar input,
+ // the UDF reads the batches of the reader, whose column vectors are
ReusedArrowColumnVectors,
+ // so it copies their pass-through columns rather than keep them past the
next batch.
+ Seq(false, true).foreach { columnarInput =>
+ session.conf.set(
+ SQLConf.ARROW_PYSPARK_UDF_COLUMNAR_INPUT_ENABLED.key,
columnarInput.toString)
+ Seq(100, 200, 200000).foreach { end =>
+ val df = range(session, "end" -> end.toString, "partitions" -> "1",
"batch_size" -> "100")
+ .selectExpr("id", "name", "native_str(name) AS udf_name")
+ val plan = df.queryExecution.executedPlan
+ assert(plan.collectFirst { case e: ArrowEvalPythonExec =>
e.supportsColumnar }
+ .contains(columnarInput), plan)
+ val rows = df.collect()
+ assert(rows.map(_.getLong(0)).toSeq == (0L until end))
+ rows.foreach { row =>
+ val id = row.getLong(0)
+ val name = if (id % 5 == 0) null else s"n$id"
+ assert(row.getString(1) == name, s"name mismatch for id $id")
+ assert(row.getString(2) == name, s"UDF mismatch for id $id")
+ }
}
}
}
@@ -2571,7 +2704,9 @@ class NativeDataSourceSuite extends QueryTest with
SharedSparkSession {
val session = newSession(defaultPackage)
val pool = ThreadUtils.newDaemonSingleThreadExecutor("native-reader")
// Closes a reader while another thread is in get_next. The reader
releases the stream once
- // get_next returns, also when it fails, and then next returns false or
throws.
+ // get_next returns, also when it fails, and then next throws: the error
of its read, or the
+ // failure of a next once the reader is closed, so that the thread does
not take the close for
+ // the end of the data.
def closeWhileReading(failing: Boolean): Either[Throwable, Boolean] = {
val marker = new File(Utils.createTempDir(), "released")
val options = Seq("end" -> "10", "partitions" -> "1", "slow_read" ->
marker.getPath) ++
@@ -2597,7 +2732,7 @@ class NativeDataSourceSuite extends QueryTest with
SharedSparkSession {
// it freed is interrupted, and a read outside of a task never is.
assert(Files.readString(new File(marker.getPath +
".interrupted").toPath) == "false")
// A reader that was closed reads nothing more, and closing it again
does not fail.
- assert(!reader.next())
+ checkClosed(intercept[SparkRuntimeException](reader.next()))
reader.close()
result
} finally {
@@ -2607,7 +2742,7 @@ class NativeDataSourceSuite extends QueryTest with
SharedSparkSession {
}
}
try {
- assert(closeWhileReading(failing = false) == Right(false))
+ checkClosed(closeWhileReading(failing = false).swap.getOrElse(fail("next
did not fail")))
val error = closeWhileReading(failing = true).swap.getOrElse(fail("next
did not fail"))
assert(error.getMessage.contains("injected failure after a slow
get_next"))
} finally {
@@ -2615,6 +2750,134 @@ class NativeDataSourceSuite extends QueryTest with
SharedSparkSession {
}
}
+ nativeTest("close a reader while another thread reads the batch that it
returned") {
+ val session = newSession(defaultPackage)
+ val pool = ThreadUtils.newDaemonSingleThreadExecutor("native-reader")
+ def onPool[T](f: => T): T = pool.submit(new Callable[T] {
+ override def call(): T = f
+ }).get(1, TimeUnit.MINUTES)
+ // The contexts of the tasks of earlier tests are closed first, so that
the counts below are
+ // exactly those of this test.
+ eventually(timeout(1.minute))(assert(NativeLibrary.openTaskContexts() ==
0))
+ // Closes a reader on this thread once the other thread read a batch. With
`nextAgain`, the
+ // other thread then calls next, which tells that it no longer reads the
batch. Otherwise
+ // nativeTest checks that a Cleaner frees the buffers once the reader is
unreachable.
+ def closeWhileRead(nextAgain: Boolean): Unit = {
+ val marker = new File(Utils.createTempDir(), "released")
+ // get_next does not wait: the file .continue exists.
+ new File(marker.getPath + ".continue").createNewFile()
+ val (reader, allocator) = readerAndAllocator(
+ range(session, "end" -> "10", "partitions" -> "1", "slow_read" ->
marker.getPath)
+ .select("id"))
+ try {
+ assert(onPool(reader.next()))
+ assert(NativeLibrary.openTaskContexts() == 1)
+ reader.close()
+ // The stream and the task are released at once, but not the buffers
of the batch, which
+ // the other thread may still read.
+ assert(Files.readString(marker.toPath) == "after get_next")
+ assert(NativeLibrary.openTaskContexts() == 0)
+ assert(readerAllocators().contains(allocator) &&
allocator.getAllocatedMemory > 0)
+ val rows = onPool((0 until
reader.get().numRows()).map(reader.get().column(0).getLong))
+ assert(rows === (0L until 10L))
+ // Closing the reader again does nothing.
+ reader.close()
+ assert(readerAllocators().contains(allocator))
+ if (nextAgain) {
+ // A next then fails, and frees the buffers of the batch and the
allocator at once: the
+ // test still references the reader, which a Cleaner would wait for.
+
checkClosed(intercept[ExecutionException](onPool(reader.next())).getCause)
+ assert(!readerAllocators().contains(allocator))
+ // The batch then has no rows, so that it is not read at the freed
addresses.
+ assert(reader.get().numRows() == 0)
+ // So does a next on any thread after that.
+ checkClosed(intercept[SparkRuntimeException](reader.next()))
+ }
+ } finally {
+ reader.close()
+ }
+ }
+ try {
+ closeWhileRead(nextAgain = false)
+ closeWhileRead(nextAgain = true)
+ } finally {
+ pool.shutdown()
+ }
+ }
+
+ nativeTest("keep the buffers of a closed reader while its batch is held
without the reader") {
+ val session = newSession(defaultPackage)
+ // Closes a reader once it returned a batch, and returns the batch and the
allocator of the
+ // reader, but not the reader, as `DataSourceRDD` drops it once it closes
it.
+ def closedBatch(): (ColumnarBatch, BufferAllocator) = {
+ val (reader, allocator) = readerAndAllocator(
+ range(session, "end" -> "10", "partitions" -> "1").select("id"))
+ try {
+ assert(reader.next())
+ } finally {
+ reader.close()
+ }
+ (reader.get(), allocator)
+ }
+ // Reads the batch after garbage collections.
+ def readAfterGC(): Unit = {
+ val (batch, allocator) = closedBatch()
+ // An object that a Cleaner action marks once a garbage collection found
it unreachable,
+ // after which the reader would be freed too if only the reader referred
to it.
+ val collected = new CountDownLatch(1)
+ NativeHandle.cleaner.register(new Object, () => collected.countDown())
+ eventually(timeout(1.minute), interval(100.milliseconds)) {
+ System.gc()
+ assert(collected.getCount == 0)
+ }
+ // The column vectors of the batch keep the reader reachable, so that
the Cleaner does not
+ // free the buffers that a consumer still reads.
+ assert(readerAllocators().contains(allocator) &&
allocator.getAllocatedMemory > 0)
+ assert((0 until batch.numRows()).map(batch.column(0).getLong) === (0L
until 10L))
+ }
+ // nativeTest checks that the Cleaner frees them once the batch is dropped
too.
+ readAfterGC()
+ }
+
+ nativeTest("free the buffers of a reader closed at the end of its stream
without a GC") {
+ val session = newSession(defaultPackage)
+ // The ids 0-3, 4-7 and 8-9.
+ val (reader, allocator) = readerAndAllocator(
+ range(session, "end" -> "10", "partitions" -> "1", "batch_size" ->
"4").select("id"))
+ try {
+ val ids = ArrayBuffer.empty[Long]
+ while (reader.next()) {
+ ids ++= (0 until
reader.get().numRows()).map(reader.get().column(0).getLong)
+ }
+ assert(ids.toSeq === (0L until 10L))
+ // The buffers of the last batch stay allocated until the reader is
closed.
+ assert(allocator.getAllocatedMemory > 0)
+ reader.close()
+ // Consumers no longer read a batch once next was called again, here at
the end of the
+ // stream, so the close frees its buffers and the allocator at once: the
test still
+ // references the reader, which a Cleaner would wait for.
+ assert(!readerAllocators().contains(allocator))
+ // The batch then has no rows, so that it is not read at the freed
addresses.
+ assert(reader.get().numRows() == 0)
+ } finally {
+ reader.close()
+ }
+ // So does the close of a reader whose next failed, also after an import:
the name of id 10, in
+ // the third batch of the second partition, is null.
+ val (failed, failedAllocator) = readerAndAllocator(
+ session.read.schema("id BIGINT, name STRING NOT
NULL").format("native_range")
+ .options(Map("end" -> "12", "partitions" -> "2", "batch_size" ->
"2")).load(),
+ partition = 1)
+ try {
+ assert(failed.next() && failed.next())
+ findError(intercept[Exception](failed.next()),
"NATIVE_DATA_SOURCE_ERROR")
+ failed.close()
+ assert(!readerAllocators().contains(failedAllocator))
+ } finally {
+ failed.close()
+ }
+ }
+
nativeTest("load libraries that export the same functions side by side") {
val session = newSession(
defaultPackage, createPackage(negatingLibrary, dataSources("b_")))
diff --git
a/sql/hive/src/main/scala/org/apache/spark/sql/hive/execution/HiveScriptTransformationExec.scala
b/sql/hive/src/main/scala/org/apache/spark/sql/hive/execution/HiveScriptTransformationExec.scala
index de2d15415837..d1755eedc5e8 100644
---
a/sql/hive/src/main/scala/org/apache/spark/sql/hive/execution/HiveScriptTransformationExec.scala
+++
b/sql/hive/src/main/scala/org/apache/spark/sql/hive/execution/HiveScriptTransformationExec.scala
@@ -64,7 +64,6 @@ private[hive] case class HiveScriptTransformationExec(
outputSoi: StructObjectInspector,
hadoopConf: Configuration): Iterator[InternalRow] = {
new Iterator[InternalRow] with HiveInspectors {
- private var completed = false
val scriptOutputStream = new DataInputStream(inputStream)
val scriptOutputReader =
@@ -78,7 +77,7 @@ private[hive] case class HiveScriptTransformationExec(
lazy val unwrappers =
outputSoi.getAllStructFieldRefs.asScala.map(unwrapperFor)
override def hasNext: Boolean = {
- if (completed) {
+ if (writerThread.outputReadToEnd) {
return false
}
try {
@@ -88,7 +87,7 @@ private[hive] case class HiveScriptTransformationExec(
if (scriptOutputReader != null) {
if (scriptOutputReader.next(scriptOutputWritable) <= 0) {
checkFailureAndPropagate(writerThread, null, proc,
stderrBuffer)
- completed = true
+ writerThread.outputReadToEnd = true
return false
}
} else {
@@ -101,7 +100,7 @@ private[hive] case class HiveScriptTransformationExec(
// there can be a lag between EOF being written out and the
process
// being terminated. So explicitly waiting for the process
to be done.
checkFailureAndPropagate(writerThread, null, proc,
stderrBuffer)
- completed = true
+ writerThread.outputReadToEnd = true
return false
}
}
@@ -134,6 +133,10 @@ private[hive] case class HiveScriptTransformationExec(
}
i += 1
}
+ // Read ahead, as the iterator without serde does: the task may not
call `hasNext` again,
+ // as under a LIMIT, so the end of the output must also be recorded
here. The unwrappers
+ // copy the values, so reading the next row into the reused writable
keeps `mutableRow`.
+ hasNext
mutableRow
}
}
@@ -183,7 +186,7 @@ private[hive] case class HiveScriptTransformationExec(
writerThread, inputStream, proc, stderrBuffer, outputSerde, outputSoi,
hadoopConf)
}
- writerThread.start()
+ startWriterThread(writerThread)
outputIterator
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]