You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by gi...@apache.org on 2026/10/05 06:30:15 UTC
(datafusion-comet) branch gh-readonly-queue/main/pr-6534-35de0b9ec69ee4ae952af1f7250c8926ceffd7fd created (now a4e72fd9d4)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a change to branch gh-readonly-queue/main/pr-6534-35de0b9ec69ee4ae952af1f7250c8926ceffd7fd
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git
at a4e72fd9d4 refactor: move the remaining JNI-free entry point logic into core functions (#6534)
This branch includes the following new commits:
new a4e72fd9d4 refactor: move the remaining JNI-free entry point logic into core functions (#6534)
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org
(datafusion-comet) 01/01: refactor: move the remaining JNI-free entry point logic into core functions (#6534)
Posted by gi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-6534-35de0b9ec69ee4ae952af1f7250c8926ceffd7fd
in repository https://gitbox.apache.org/repos/asf/datafusion-comet.git
commit a4e72fd9d4e3bb8f459fc7950a98536724daf859
Author: Liang-Chi Hsieh <vi...@gmail.com>
AuthorDate: Mon Oct 5 06:05:20 2026 +0000
refactor: move the remaining JNI-free entry point logic into core functions (#6534)
* refactor: move the remaining JNI-free entry point logic into core functions
Continue separating the native logic of the JNI entry points that do not
call back into the JVM from their JNI argument handling, so it can be
unit-tested without a JVM:
- columnarToRowConvert: columnar_to_row_convert imports the Arrow C Data
columns and converts them; the export only pins the address arrays and
builds NativeColumnarToRowInfo.
- writeSortedFileNative: write_sorted_file takes the row addresses and
sizes as slices and handles the codec name and the i64::MIN checksum
convention.
- sortRowPartitionsNative: sort_row_partitions sorts a slice.
- getShufflePartitionOffsets: shuffle_partition_offsets takes the root
plan instead of the execution context.
- NativeBase.init: init_logging and logger_config set up logging; the
export keeps capturing the JavaVM.
- NativeBase.getTzdataVersion: tzdata_version.
Exception classes and messages are unchanged.
* Check slice lengths and extend tests for the moved entry point logic
write_sorted_file now returns an error when row_sizes is shorter than
row_addresses, and columnar_to_row_convert when the array and schema
address slices differ in length, instead of reading out of bounds or
panicking.
Test every codec name of write_sorted_file, including the lz4 fallback, by
decoding the written blocks; check its checksum against a CRC32 of the
written bytes, unseeded and continued from a previous file. Test the
undrained and drained shuffle writer in shuffle_partition_offsets, and a
string column in columnar_to_row_convert.
* Test the write_sorted_file checksum with Adler-32 as well as CRC32
With CRC32 a missing current checksum (i64::MIN) cannot be told apart from
a current checksum of 0, because a fresh CRC32 also starts at 0. Adler-32
starts at 1, and it is Spark's default, seeded with Long.MIN_VALUE for every
partition. Run the checksum test for both algorithms against an independent
Adler-32 reference, so it fails if i64::MIN were treated as a checksum of 0.
---
native/Cargo.lock | 1 +
native/core/Cargo.toml | 1 +
native/core/src/execution/jni_api.rs | 606 ++++++++++++++++++++++++++++-------
native/core/src/lib.rs | 66 +++-
4 files changed, 546 insertions(+), 128 deletions(-)
diff --git a/native/Cargo.lock b/native/Cargo.lock
index 07011be0d1..0e157bdda8 100644
--- a/native/Cargo.lock
+++ b/native/Cargo.lock
@@ -1979,6 +1979,7 @@ dependencies = [
"chrono-tz",
"comet-contrib-delta",
"comet-contrib-lance",
+ "crc32fast",
"criterion",
"datafusion",
"datafusion-comet-common",
diff --git a/native/core/Cargo.toml b/native/core/Cargo.toml
index ed5f73b13f..468ee4f45d 100644
--- a/native/core/Cargo.toml
+++ b/native/core/Cargo.toml
@@ -102,6 +102,7 @@ procfs = "0.18.0"
hdrs = { version = "0.3.2", features = ["vendored"] }
[dev-dependencies]
+crc32fast = "1.3.2"
pprof = { version = "0.15", features = ["flamegraph"] }
criterion = { version = "0.7", features = ["async", "async_tokio", "async_std"] }
jni = { version = "0.22.4", features = ["invocation"] }
diff --git a/native/core/src/execution/jni_api.rs b/native/core/src/execution/jni_api.rs
index 5b1bf96699..361d3847da 100644
--- a/native/core/src/execution/jni_api.rs
+++ b/native/core/src/execution/jni_api.rs
@@ -1537,46 +1537,55 @@ pub extern "system" fn Java_org_apache_comet_Native_getShufflePartitionOffsets(
) -> jlongArray {
try_unwrap_or_throw(&e, |env| {
let context = get_execution_context(exec_context);
+ let root_plan = context.root_op.as_ref().map(|op| op.native_plan.as_ref());
+ let offsets = shuffle_partition_offsets(root_plan)?;
- let root_op = context.root_op.as_ref().ok_or_else(|| {
+ let long_array = env.new_long_array(offsets.len())?;
+ long_array.set_region(env, 0, offsets)?;
+ Ok(long_array.into_raw())
+ })
+}
+
+/// The partition offsets published by `root_plan`, which must be a native shuffle write plan that
+/// has been drained to completion. `root_plan` is `None` before the plan has been executed. Core
+/// of `Native.getShufflePartitionOffsets`.
+fn shuffle_partition_offsets(
+ root_plan: Option<&dyn datafusion::physical_plan::ExecutionPlan>,
+) -> CometResult<&[i64]> {
+ let root_plan = root_plan.ok_or_else(|| {
+ CometError::Internal(
+ "Cannot read shuffle partition offsets before the plan has been executed".to_string(),
+ )
+ })?;
+
+ // `ExecutionPlan` has `Any` as a supertrait but no `as_any` method of its own, so upcast
+ // the trait object before downcasting to the writer.
+ let writer = (root_plan as &dyn std::any::Any)
+ .downcast_ref::<ShuffleWriterExec>()
+ .ok_or_else(|| {
CometError::Internal(
- "Cannot read shuffle partition offsets before the plan has been executed"
+ "Shuffle partition offsets are only available on a native shuffle write plan"
.to_string(),
)
})?;
- // `ExecutionPlan` has `Any` as a supertrait but no `as_any` method of its own, so upcast
- // the trait object before downcasting to the writer.
- let writer = (root_op.native_plan.as_ref() as &dyn std::any::Any)
- .downcast_ref::<ShuffleWriterExec>()
- .ok_or_else(|| {
- CometError::Internal(
- "Shuffle partition offsets are only available on a native shuffle write plan"
- .to_string(),
- )
- })?;
-
- let offsets = writer
- .partition_offsets()
- .ok_or_else(|| {
- CometError::Internal(
- "Shuffle partition offsets are not published by a remote shuffle destination"
- .to_string(),
- )
- })?
- .get()
- .ok_or_else(|| {
- CometError::Internal(
- "Shuffle writer has not published its partition offsets; the plan was not \
- drained to completion"
- .to_string(),
- )
- })?;
-
- let long_array = env.new_long_array(offsets.len())?;
- long_array.set_region(env, 0, offsets)?;
- Ok(long_array.into_raw())
- })
+ let offsets = writer
+ .partition_offsets()
+ .ok_or_else(|| {
+ CometError::Internal(
+ "Shuffle partition offsets are not published by a remote shuffle destination"
+ .to_string(),
+ )
+ })?
+ .get()
+ .ok_or_else(|| {
+ CometError::Internal(
+ "Shuffle writer has not published its partition offsets; the plan was not \
+ drained to completion"
+ .to_string(),
+ )
+ })?;
+ Ok(offsets)
}
/// Used by Comet shuffle external sorter to write sorted records to disk.
@@ -1605,58 +1614,27 @@ pub unsafe extern "system" fn Java_org_apache_comet_Native_writeSortedFileNative
tracing_enabled != JNI_FALSE,
|| {
let data_types = convert_datatype_arrays(env, serialized_datatypes)?;
-
- let row_num = row_addresses.len(env)?;
let row_addresses = row_addresses.get_elements(env, ReleaseMode::NoCopyBack)?;
-
let row_sizes = row_sizes.get_elements(env, ReleaseMode::NoCopyBack)?;
-
- let row_addresses_ptr = row_addresses.as_ptr();
- let row_sizes_ptr = row_sizes.as_ptr();
-
let output_path: String = file_path.try_to_string(env).unwrap();
-
- let current_checksum = if current_checksum == i64::MIN {
- // Initial checksum is not available.
- None
- } else {
- Some(current_checksum as u32)
- };
-
let compression_codec: String = compression_codec.try_to_string(env).unwrap();
- let compression_codec = match compression_codec.as_str() {
- "zstd" => CompressionCodec::Zstd(compression_level),
- "lz4" => CompressionCodec::Lz4Frame,
- "snappy" => CompressionCodec::Snappy,
- _ => CompressionCodec::Lz4Frame,
- };
-
- let (written_bytes, checksum, encode_nanos) = process_sorted_row_partition(
- row_num,
- batch_size as usize,
- row_addresses_ptr,
- row_sizes_ptr,
+ let results = write_sorted_file(
+ &row_addresses,
+ &row_sizes,
&data_types,
output_path,
prefer_dictionary_ratio,
+ batch_size as usize,
checksum_enabled,
checksum_algo,
current_checksum,
&compression_codec,
+ compression_level,
)?;
- let checksum = if let Some(checksum) = checksum {
- checksum as i64
- } else {
- // Spark checksums (CRC32 or Adler32) are both u32, so we use i64::MIN to indicate
- // checksum is not available.
- i64::MIN
- };
-
- // results[0] = bytes written, results[1] = checksum, results[2] = encode nanos
- let long_array = env.new_long_array(3)?;
- long_array.set_region(env, 0, &[written_bytes, checksum, encode_nanos])?;
+ let long_array = env.new_long_array(results.len())?;
+ long_array.set_region(env, 0, &results)?;
Ok(long_array.into_raw())
},
@@ -1664,6 +1642,68 @@ pub unsafe extern "system" fn Java_org_apache_comet_Native_writeSortedFileNative
})
}
+/// Converts the Spark `UnsafeRow`s at `row_addresses`, with the sizes in `row_sizes`, into Arrow
+/// batches of `data_types` and writes them to `output_path`. Returns `[bytes written, checksum,
+/// encode nanos]`. Checksums cross the boundary as `i64`, with `i64::MIN` meaning none: Spark's
+/// CRC32 and Adler32 checksums are both `u32`. Core of `Native.writeSortedFileNative`.
+///
+/// # Safety
+/// Each address must point to a readable row of the corresponding size.
+#[allow(clippy::too_many_arguments)]
+unsafe fn write_sorted_file(
+ row_addresses: &[i64],
+ row_sizes: &[i32],
+ data_types: &[ArrowDataType],
+ output_path: String,
+ prefer_dictionary_ratio: f64,
+ batch_size: usize,
+ checksum_enabled: bool,
+ checksum_algo: i32,
+ current_checksum: i64,
+ compression_codec: &str,
+ compression_level: i32,
+) -> CometResult<[i64; 3]> {
+ if row_sizes.len() < row_addresses.len() {
+ return Err(CometError::Internal(format!(
+ "{} row sizes for {} row addresses",
+ row_sizes.len(),
+ row_addresses.len()
+ )));
+ }
+
+ let current_checksum = if current_checksum == i64::MIN {
+ // Initial checksum is not available.
+ None
+ } else {
+ Some(current_checksum as u32)
+ };
+
+ let compression_codec = match compression_codec {
+ "zstd" => CompressionCodec::Zstd(compression_level),
+ "lz4" => CompressionCodec::Lz4Frame,
+ "snappy" => CompressionCodec::Snappy,
+ _ => CompressionCodec::Lz4Frame,
+ };
+
+ // `process_sorted_row_partition` only reads through the pointers.
+ let (written_bytes, checksum, encode_nanos) = process_sorted_row_partition(
+ row_addresses.len(),
+ batch_size,
+ row_addresses.as_ptr() as *mut i64,
+ row_sizes.as_ptr() as *mut i32,
+ data_types,
+ output_path,
+ prefer_dictionary_ratio,
+ checksum_enabled,
+ checksum_algo,
+ current_checksum,
+ &compression_codec,
+ )?;
+
+ let checksum = checksum.map_or(i64::MIN, |checksum| checksum as i64);
+ Ok([written_bytes, checksum, encode_nanos])
+}
+
#[no_mangle]
/// Used by Comet shuffle external sorter to sort in-memory row partition ids.
pub extern "system" fn Java_org_apache_comet_Native_sortRowPartitionsNative(
@@ -1688,13 +1728,19 @@ pub extern "system" fn Java_org_apache_comet_Native_sortRowPartitionsNative(
);
let array =
unsafe { std::slice::from_raw_parts_mut(address as *mut i64, size as usize) };
- array.rdxsort();
+ sort_row_partitions(array);
Ok(())
},
)
})
}
+/// Sorts packed shuffle record pointers in place by the partition id in their upper 24 bits,
+/// keeping the order of the pointers within a partition. Core of `Native.sortRowPartitionsNative`.
+fn sort_row_partitions(packed_pointers: &mut [i64]) {
+ packed_pointers.rdxsort();
+}
+
#[no_mangle]
/// Used by Comet native shuffle reader
/// # Safety
@@ -1971,50 +2017,12 @@ pub unsafe extern "system" fn Java_org_apache_comet_Native_columnarToRowConvert(
.as_mut()
.ok_or_else(|| CometError::Internal("Null columnar to row context".to_string()))?;
- let num_cols = array_addrs.len(env)?;
-
// Get array and schema addresses
- let array_addrs_elements =
- unsafe { array_addrs.get_elements(env, ReleaseMode::NoCopyBack)? };
- let schema_addrs_elements =
- unsafe { schema_addrs.get_elements(env, ReleaseMode::NoCopyBack)? };
-
- // Import Arrow arrays from FFI
- let mut arrays = Vec::with_capacity(num_cols);
- for i in 0..num_cols {
- let array_ptr = array_addrs_elements[i] as *mut FFI_ArrowArray;
- let schema_ptr = schema_addrs_elements[i] as *mut FFI_ArrowSchema;
-
- debug_assert!(
- !array_ptr.is_null(),
- "columnarToRowConvert: null array pointer at index {}",
- i
- );
- debug_assert!(
- !schema_ptr.is_null(),
- "columnarToRowConvert: null schema pointer at index {}",
- i
- );
+ let array_addrs = unsafe { array_addrs.get_elements(env, ReleaseMode::NoCopyBack)? };
+ let schema_addrs = unsafe { schema_addrs.get_elements(env, ReleaseMode::NoCopyBack)? };
- // Take ownership of the FFI structures
- let ffi_array = unsafe { std::ptr::read(array_ptr) };
- let ffi_schema = unsafe { std::ptr::read(schema_ptr) };
-
- // Convert to Arrow ArrayData
- let array_data = from_ffi(ffi_array, &ffi_schema)
- .map_err(|e| CometError::Internal(format!("Failed to import array: {}", e)))?;
-
- let imported = arrow::array::make_array(array_data);
- arrays.push(decode_string_arrays(&imported)?);
- }
-
- // Convert columnar to row
- debug_assert!(
- num_rows >= 0,
- "columnarToRowConvert: num_rows is negative: {}",
- num_rows
- );
- let (buffer_ptr, offsets, lengths) = ctx.convert(&arrays, num_rows as usize)?;
+ let (buffer_ptr, offsets, lengths) =
+ unsafe { columnar_to_row_convert(ctx, &array_addrs, &schema_addrs, num_rows)? };
// Create Java int arrays for offsets and lengths
let offsets_array = env.new_int_array(offsets.len())?;
@@ -2040,6 +2048,67 @@ pub unsafe extern "system" fn Java_org_apache_comet_Native_columnarToRowConvert(
})
}
+/// Imports the columns at `array_addrs` and `schema_addrs` and converts their first `num_rows`
+/// rows to Spark `UnsafeRow`s in `ctx`'s buffer. Returns the buffer address and the offset and
+/// length of each row in it, valid until the next conversion. Core of
+/// `Native.columnarToRowConvert`.
+///
+/// # Safety
+/// Each address must point to an exported `FFI_ArrowArray` / `FFI_ArrowSchema`, whose ownership
+/// moves to this call.
+unsafe fn columnar_to_row_convert<'a>(
+ ctx: &'a mut ColumnarToRowContext,
+ array_addrs: &[i64],
+ schema_addrs: &[i64],
+ num_rows: i32,
+) -> CometResult<(*const u8, &'a [i32], &'a [i32])> {
+ if schema_addrs.len() != array_addrs.len() {
+ return Err(CometError::Internal(format!(
+ "{} schema addresses for {} array addresses",
+ schema_addrs.len(),
+ array_addrs.len()
+ )));
+ }
+ let num_cols = array_addrs.len();
+
+ // Import Arrow arrays from FFI
+ let mut arrays = Vec::with_capacity(num_cols);
+ for i in 0..num_cols {
+ let array_ptr = array_addrs[i] as *mut FFI_ArrowArray;
+ let schema_ptr = schema_addrs[i] as *mut FFI_ArrowSchema;
+
+ debug_assert!(
+ !array_ptr.is_null(),
+ "columnarToRowConvert: null array pointer at index {}",
+ i
+ );
+ debug_assert!(
+ !schema_ptr.is_null(),
+ "columnarToRowConvert: null schema pointer at index {}",
+ i
+ );
+
+ // Take ownership of the FFI structures
+ let ffi_array = unsafe { std::ptr::read(array_ptr) };
+ let ffi_schema = unsafe { std::ptr::read(schema_ptr) };
+
+ // Convert to Arrow ArrayData
+ let array_data = from_ffi(ffi_array, &ffi_schema)
+ .map_err(|e| CometError::Internal(format!("Failed to import array: {}", e)))?;
+
+ let imported = arrow::array::make_array(array_data);
+ arrays.push(decode_string_arrays(&imported)?);
+ }
+
+ // Convert columnar to row
+ debug_assert!(
+ num_rows >= 0,
+ "columnarToRowConvert: num_rows is negative: {}",
+ num_rows
+ );
+ ctx.convert(&arrays, num_rows as usize)
+}
+
/// Close and release the native columnar to row converter.
///
/// # Safety
@@ -3005,4 +3074,311 @@ mod tests {
assert!(producer.next_batch().unwrap().is_none());
producer.stop().unwrap();
}
+
+ #[test]
+ fn sort_row_partitions_sorts_in_place() {
+ let mut pointers = vec![
+ 5_i64 << 40 | 3,
+ 1,
+ 2_i64 << 40,
+ 1_i64 << 40 | 7,
+ 0,
+ 5_i64 << 40,
+ ];
+ let mut expected = pointers.clone();
+ // Stable, so the lower 40 bits keep their input order within a partition.
+ expected.sort_by_key(|pointer| (*pointer as u64) >> 40);
+ sort_row_partitions(&mut pointers);
+ assert_eq!(pointers, expected);
+ assert_eq!(&pointers[..2], &[1, 0]);
+ }
+
+ #[test]
+ fn shuffle_partition_offsets_requires_an_executed_shuffle_write() {
+ let error = shuffle_partition_offsets(None).unwrap_err();
+ assert!(
+ error
+ .to_string()
+ .contains("before the plan has been executed"),
+ "{error}"
+ );
+
+ let plan = datafusion::physical_plan::empty::EmptyExec::new(Arc::new(Schema::empty()));
+ let error = shuffle_partition_offsets(Some(&plan)).unwrap_err();
+ assert!(
+ error
+ .to_string()
+ .contains("only available on a native shuffle write plan"),
+ "{error}"
+ );
+ }
+
+ #[test]
+ fn shuffle_partition_offsets_after_the_write_is_drained() {
+ use datafusion::datasource::memory::MemorySourceConfig;
+ use datafusion::datasource::source::DataSourceExec;
+ use datafusion_comet_shuffle::{CometPartitioning, RoundRobinStrategy};
+
+ let batch = int_batch();
+ let num_partitions = 3;
+ let dir = tempfile::tempdir().unwrap();
+ let data_file = dir.path().join("data.out");
+ let writer = ShuffleWriterExec::try_new(
+ Arc::new(DataSourceExec::new(Arc::new(
+ MemorySourceConfig::try_new(&[vec![batch.clone()]], batch.schema(), None).unwrap(),
+ ))),
+ CometPartitioning::RoundRobin(num_partitions, RoundRobinStrategy::default()),
+ CompressionCodec::Zstd(1),
+ data_file.to_str().unwrap().to_string(),
+ false,
+ 1024 * 1024,
+ None,
+ )
+ .unwrap();
+
+ let error = shuffle_partition_offsets(Some(&writer)).unwrap_err();
+ assert!(
+ error.to_string().contains("not drained to completion"),
+ "{error}"
+ );
+
+ let task_ctx = Arc::new(TaskContext::default());
+ let stream = writer.execute(0, task_ctx).unwrap();
+ Runtime::new()
+ .unwrap()
+ .block_on(datafusion::physical_plan::common::collect(stream))
+ .unwrap();
+
+ // One offset per partition plus the data file length.
+ let offsets = shuffle_partition_offsets(Some(&writer)).unwrap();
+ assert_eq!(offsets.len(), num_partitions + 1);
+ assert_eq!(offsets[0], 0);
+ assert!(offsets.windows(2).all(|pair| pair[0] <= pair[1]));
+ let file_len = std::fs::metadata(&data_file).unwrap().len() as i64;
+ assert_eq!(offsets[num_partitions], file_len);
+ }
+
+ /// Spark `UnsafeRow`s with one non-null `long` field each: an 8-byte null bitset, then the
+ /// value.
+ fn long_rows(values: &[i64]) -> Vec<[u8; 16]> {
+ values
+ .iter()
+ .map(|value| {
+ let mut row = [0_u8; 16];
+ row[8..].copy_from_slice(&value.to_le_bytes());
+ row
+ })
+ .collect()
+ }
+
+ /// Splits a shuffle data file into its blocks, each without the 8-byte length and the 8-byte
+ /// field count, so it starts at the codec tag as `read_ipc_compressed` expects.
+ fn shuffle_blocks(data: &[u8]) -> Vec<&[u8]> {
+ let mut blocks = Vec::new();
+ let mut pos = 0;
+ while pos < data.len() {
+ let length = u64::from_le_bytes(data[pos..pos + 8].try_into().unwrap()) as usize;
+ blocks.push(&data[pos + 16..pos + 8 + length]);
+ pos += 8 + length;
+ }
+ blocks
+ }
+
+ /// Writes `rows` (16-byte `long` rows) with `write_sorted_file` in batches of 2 rows,
+ /// checksummed with `checksum_algo` if set, and returns the results and the file contents.
+ fn write_long_rows(
+ rows: &[[u8; 16]],
+ sizes: &[i32],
+ path: &std::path::Path,
+ checksum_algo: Option<i32>,
+ current_checksum: i64,
+ codec: &str,
+ ) -> CometResult<([i64; 3], Vec<u8>)> {
+ let addresses: Vec<i64> = rows.iter().map(|row| row.as_ptr() as i64).collect();
+ let results = unsafe {
+ write_sorted_file(
+ &addresses,
+ sizes,
+ &[DataType::Int64],
+ path.to_str().unwrap().to_string(),
+ 1.0,
+ 2,
+ checksum_algo.is_some(),
+ checksum_algo.unwrap_or(0),
+ current_checksum,
+ codec,
+ 1,
+ )
+ }?;
+ Ok((results, std::fs::read(path).unwrap()))
+ }
+
+ #[test]
+ fn write_sorted_file_codecs() {
+ let values = [1_i64, 2, 3, 4, 5];
+ let rows = long_rows(&values);
+ let sizes = vec![16_i32; rows.len()];
+ let dir = tempfile::tempdir().unwrap();
+
+ // Unknown codec names fall back to lz4.
+ for (codec, tag) in [
+ ("lz4", b"LZ4_"),
+ ("zstd", b"ZSTD"),
+ ("snappy", b"SNAP"),
+ ("unknown", b"LZ4_"),
+ ] {
+ let path = dir.path().join(codec);
+ let ([written, checksum, _], data) =
+ write_long_rows(&rows, &sizes, &path, None, i64::MIN, codec).unwrap();
+ assert_eq!(written, data.len() as i64, "{codec}");
+ assert_eq!(checksum, i64::MIN, "no checksum without checksum_enabled");
+
+ let blocks = shuffle_blocks(&data);
+ assert_eq!(blocks.len(), 3, "{codec}: 5 rows in batches of 2");
+ let mut decoded = Vec::new();
+ for block in blocks {
+ assert_eq!(&block[..4], tag, "{codec}");
+ let batch = read_ipc_compressed(block).unwrap();
+ let column = arrow::array::AsArray::as_primitive::<arrow::datatypes::Int64Type>(
+ batch.column(0),
+ );
+ decoded.extend(column.values().iter().copied());
+ }
+ assert_eq!(decoded, values, "{codec}");
+ }
+ }
+
+ /// Adler-32 of `data`, computed independently of the implementation under test.
+ fn adler32(data: &[u8]) -> u32 {
+ let (mut a, mut b) = (1_u32, 0_u32);
+ for &byte in data {
+ a = (a + byte as u32) % 65521;
+ b = (b + a) % 65521;
+ }
+ b << 16 | a
+ }
+
+ #[test]
+ fn write_sorted_file_checksums_the_written_bytes() {
+ let rows = long_rows(&[1, 2, 3, 4, 5]);
+ let sizes = vec![16_i32; rows.len()];
+ let dir = tempfile::tempdir().unwrap();
+
+ // CRC32 (0) starts from 0 but Adler-32 (1) from 1, so a missing current checksum
+ // (`i64::MIN`) must start a fresh checksum rather than continue one from 0. Spark seeds
+ // every partition with `Long.MIN_VALUE` and defaults to Adler-32.
+ let algorithms = [(0, crc32fast::hash as fn(&[u8]) -> u32), (1, adler32)];
+ for (algo, checksum_of) in algorithms {
+ // Without a current checksum the checksum starts afresh and covers the file.
+ let first_path = dir.path().join(format!("{algo}-first"));
+ let ([_, first, _], first_data) =
+ write_long_rows(&rows, &sizes, &first_path, Some(algo), i64::MIN, "lz4").unwrap();
+ assert_eq!(first, checksum_of(&first_data) as i64, "algorithm {algo}");
+
+ // A current checksum continues it, as across the spill files of one partition.
+ let second_path = dir.path().join(format!("{algo}-second"));
+ let ([_, second, _], second_data) =
+ write_long_rows(&rows, &sizes, &second_path, Some(algo), first, "lz4").unwrap();
+ let both = [first_data, second_data].concat();
+ assert_eq!(second, checksum_of(&both) as i64, "algorithm {algo}");
+ }
+ }
+
+ #[test]
+ fn write_sorted_file_rejects_missing_row_sizes() {
+ let rows = long_rows(&[1, 2]);
+ let dir = tempfile::tempdir().unwrap();
+ let error = write_long_rows(&rows, &[16], &dir.path().join("a"), None, i64::MIN, "lz4")
+ .unwrap_err();
+ assert!(
+ error
+ .to_string()
+ .contains("1 row sizes for 2 row addresses"),
+ "{error}"
+ );
+ }
+
+ /// Exports `columns` as Arrow C Data structs and converts them with `columnar_to_row_convert`,
+ /// returning the offsets, the lengths, and the row bytes.
+ fn convert_exported(
+ columns: &[ArrayRef],
+ num_rows: i32,
+ ) -> CometResult<(Vec<i32>, Vec<i32>, Vec<u8>)> {
+ let mut ffi_arrays: Vec<Box<FFI_ArrowArray>> = columns
+ .iter()
+ .map(|column| Box::new(FFI_ArrowArray::new(&column.to_data())))
+ .collect();
+ let mut ffi_schemas: Vec<Box<FFI_ArrowSchema>> = columns
+ .iter()
+ .map(|column| Box::new(FFI_ArrowSchema::try_from(column.data_type()).unwrap()))
+ .collect();
+ let array_addrs: Vec<i64> = ffi_arrays
+ .iter_mut()
+ .map(|array| array.as_mut() as *mut FFI_ArrowArray as i64)
+ .collect();
+ let schema_addrs: Vec<i64> = ffi_schemas
+ .iter_mut()
+ .map(|schema| schema.as_mut() as *mut FFI_ArrowSchema as i64)
+ .collect();
+ let types = columns.iter().map(|c| c.data_type().clone()).collect();
+
+ let mut ctx = ColumnarToRowContext::new(types, 8);
+ let converted =
+ unsafe { columnar_to_row_convert(&mut ctx, &array_addrs, &schema_addrs, num_rows) };
+ // The call takes ownership of the exported structs, so they must not be released again.
+ ffi_arrays.into_iter().for_each(std::mem::forget);
+ ffi_schemas.into_iter().for_each(std::mem::forget);
+
+ let (buffer, offsets, lengths) = converted?;
+ let total = offsets
+ .iter()
+ .zip(lengths)
+ .map(|(offset, length)| (offset + length) as usize)
+ .max()
+ .unwrap_or(0);
+ let rows = unsafe { std::slice::from_raw_parts(buffer, total) }.to_vec();
+ Ok((offsets.to_vec(), lengths.to_vec(), rows))
+ }
+
+ #[test]
+ fn columnar_to_row_convert_imports_and_converts() {
+ let columns: Vec<ArrayRef> = vec![
+ Arc::new(Int32Array::from(vec![Some(1), None, Some(3)])),
+ Arc::new(arrow::array::StringArray::from(vec![
+ Some("a"),
+ Some("a longer string"),
+ None,
+ ])),
+ ];
+ let (offsets, lengths, rows) = convert_exported(&columns, 3).unwrap();
+
+ let types = columns.iter().map(|c| c.data_type().clone()).collect();
+ let mut expected_ctx = ColumnarToRowContext::new(types, 8);
+ let (expected_buffer, expected_offsets, expected_lengths) =
+ expected_ctx.convert(&columns, 3).unwrap();
+ assert_eq!(offsets, expected_offsets);
+ assert_eq!(lengths, expected_lengths);
+ assert_eq!(rows, unsafe {
+ std::slice::from_raw_parts(expected_buffer, rows.len())
+ });
+ // The string column makes the rows variable-length.
+ assert_ne!(lengths[0], lengths[1]);
+ }
+
+ #[test]
+ fn columnar_to_row_convert_rejects_mismatched_addresses() {
+ let column: ArrayRef = Arc::new(Int32Array::from(vec![1, 2]));
+ let mut ffi_array = Box::new(FFI_ArrowArray::new(&column.to_data()));
+ let array_addrs = [ffi_array.as_mut() as *mut FFI_ArrowArray as i64];
+ let mut ctx = ColumnarToRowContext::new(vec![DataType::Int32], 8);
+ // Rejected before any struct is imported, so the export is still released on drop.
+ let error = unsafe { columnar_to_row_convert(&mut ctx, &array_addrs, &[], 2) }
+ .expect_err("mismatched addresses are rejected");
+ assert!(
+ error
+ .to_string()
+ .contains("0 schema addresses for 1 array addresses"),
+ "{error}"
+ );
+ }
}
diff --git a/native/core/src/lib.rs b/native/core/src/lib.rs
index 63eefe3ad4..a05842cf03 100644
--- a/native/core/src/lib.rs
+++ b/native/core/src/lib.rs
@@ -134,20 +134,17 @@ pub extern "system" fn Java_org_apache_comet_NativeBase_init(
try_unwrap_or_throw(&e, |env| {
let path: String = log_conf_path.try_to_string(env)?;
- // empty path means there is no custom log4rs config file provided, so fallback to use
- // the default configuration
- let log_config = if path.is_empty() {
- let log_level: String = match log_level.try_to_string(env) {
+ // The log level only applies without a custom log4rs config file.
+ let log_level: String = if path.is_empty() {
+ match log_level.try_to_string(env) {
Ok(level) => level,
- Err(_) => "info".parse().unwrap(),
- };
- default_logger_config(&log_level)
+ Err(_) => "info".to_string(),
+ }
} else {
- load_config_file(path, Deserializers::default())
- .map_err(|err| CometError::Config(err.to_string()))
+ String::new()
};
- let _ = log4rs::init_config(log_config?).map_err(|err| CometError::Config(err.to_string()));
+ init_logging(&path, &log_level)?;
// Initialize the global Java VM
let java_vm = env.get_java_vm()?;
@@ -159,6 +156,27 @@ pub extern "system" fn Java_org_apache_comet_NativeBase_init(
})
}
+/// Initializes logging from the log4rs config file at `log_conf_path`, or, when it is empty, to the
+/// console at `log_level`. Logging can only be initialized once per process; later calls keep the
+/// first configuration. Core of `NativeBase.init`, except for capturing the `JavaVM`.
+pub fn init_logging(log_conf_path: &str, log_level: &str) -> CometResult<()> {
+ let _ = log4rs::init_config(logger_config(log_conf_path, log_level)?)
+ .map_err(|err| CometError::Config(err.to_string()));
+ Ok(())
+}
+
+/// The log4rs config [`init_logging`] installs.
+fn logger_config(log_conf_path: &str, log_level: &str) -> CometResult<Config> {
+ // empty path means there is no custom log4rs config file provided, so fallback to use
+ // the default configuration
+ if log_conf_path.is_empty() {
+ default_logger_config(log_level)
+ } else {
+ load_config_file(log_conf_path, Deserializers::default())
+ .map_err(|err| CometError::Config(err.to_string()))
+ }
+}
+
#[no_mangle]
/// Releases the global Tokio runtime used by Comet native execution.
pub extern "system" fn Java_org_apache_comet_NativeBase_release(_e: EnvUnowned, _class: JClass) {
@@ -242,9 +260,13 @@ pub extern "system" fn Java_org_apache_comet_NativeBase_getTzdataVersion(
env: EnvUnowned,
_: JClass,
) -> jni::sys::jstring {
- try_unwrap_or_throw(&env, |env| {
- Ok(env.new_string(chrono_tz::IANA_TZDB_VERSION)?.into_raw())
- })
+ try_unwrap_or_throw(&env, |env| Ok(env.new_string(tzdata_version())?.into_raw()))
+}
+
+/// The version of the IANA timezone database compiled into libcomet. Core of
+/// `NativeBase.getTzdataVersion`.
+pub fn tzdata_version() -> &'static str {
+ chrono_tz::IANA_TZDB_VERSION
}
// Creates a default log4rs config, which logs to console with log level.
@@ -279,6 +301,24 @@ mod tests {
assert!(!is_feature_enabled("no-such-feature"));
}
+ #[test]
+ fn logger_config_from_level_or_file() {
+ assert!(logger_config("", "debug").is_ok());
+ assert!(matches!(
+ logger_config("", "not-a-level"),
+ Err(CometError::Config(_))
+ ));
+ assert!(matches!(
+ logger_config("/no/such/log4rs.yaml", "info"),
+ Err(CometError::Config(_))
+ ));
+ }
+
+ #[test]
+ fn tzdata_version_is_set() {
+ assert!(!tzdata_version().is_empty());
+ }
+
#[test]
fn object_store_scheme_supported() {
assert!(is_object_store_scheme_supported("file:///tmp/data.parquet"));
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org