gengliangwang commented on code in PR #59520: URL: https://github.com/apache/spark/pull/59520#discussion_r4589195454
########## examples/src/main/rust/native-data-sink/src/lib.rs: ########## @@ -0,0 +1,1047 @@ +// 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. + +//! A write-only JSONL sink demonstrating task staging, atomic manifest commits, and +//! exactly-once streaming writes. +//! +//! This example requires one local or shared POSIX filesystem. It is not an +//! object-store connector, a concurrent writer protocol, or a durable table format. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::{self, File, OpenOptions}; +use std::io::{BufWriter, ErrorKind, Write}; +use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use serde::{Deserialize, Serialize}; +use spark_datasource::{ + AbortInfo, BatchWrite, Capabilities, CommitInfo, CreateInfo, DataSource, DataWriter, + DataWriterFactory, PartitionWriter, Result, StreamingAbortInfo, StreamingCommitInfo, + StreamingWrite, StreamingWriteInfo, TaskContext, Unsupported, WriteInfo, WriteMode, + WriterContext, +}; + +spark_datasource::export_data_source!(JsonSink); + +static NEXT_ID: AtomicU64 = AtomicU64::new(0); + +/// Construction and capability discovery do not access the filesystem. +pub struct JsonSink { + path: PathBuf, + readonly: bool, +} + +impl DataSource for JsonSink { + // A write-only sink. + type ScanBuilder = Unsupported; + type MicroBatchStream = Unsupported; + type BatchWrite = JsonWrite; + type StreamingWrite = JsonStreamingWrite; + + fn new(info: CreateInfo) -> Result<Self> { + let mut options = info.options; + let path = PathBuf::from( + options + .remove("path") + .ok_or("The path option is required")?, + ); + if !path.is_absolute() { + return Err("The path must be absolute and shared by the driver and executors".into()); + } + let readonly = match options.remove("readonly").as_deref() { + None | Some("false") => false, + Some("true") => true, + _ => return Err("The readonly option must be true or false".into()), + }; + // Spark passes the checkpoint and the name of a streaming query among the options of + // its sink. + options.remove("checkpointlocation"); + options.remove("queryname"); + if !options.is_empty() { + return Err( + format!("Unknown options: {:?}", options.keys().collect::<Vec<_>>()).into(), + ); + } + Ok(Self { path, readonly }) + } + + fn infer_schema(&self) -> Result<SchemaRef> { + Ok(sink_schema()) + } + + fn capabilities(&self) -> Capabilities { + if self.readonly { + // A write-only sink without its writes. + Capabilities::empty() + } else { + Capabilities::all() + } + } + + fn new_write(&self, info: WriteInfo) -> Result<JsonWrite> { + if self.readonly { + return Err("This sink is readonly".into()); + } + validate_schema(&info.schema)?; + JsonWrite::new(self.path.clone(), info.mode) + } + + fn new_streaming_write(&self, info: StreamingWriteInfo) -> Result<JsonStreamingWrite> { + Ok(JsonStreamingWrite { + write: self.new_write(WriteInfo::new(info.schema, info.mode))?, + query_id: info.query_id, + }) + } +} + +fn sink_schema() -> SchemaRef { + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, true), + Field::new("label", DataType::Utf8, true), + ])) +} + +fn validate_schema(schema: &Schema) -> Result<()> { + let fields = schema.fields(); + if fields.len() != 2 + || fields[0].name() != "id" + || fields[0].data_type() != &DataType::Int64 + || fields[1].name() != "label" + || fields[1].data_type() != &DataType::Utf8 + { + return Err("Expected columns id BIGINT, label STRING, in that order".into()); + } + Ok(()) +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +struct DataFile { + path: String, + rows: u64, +} + +#[derive(Debug, Deserialize, Serialize)] +struct Manifest { + version: u32, + files: Vec<DataFile>, + /// The last epoch that each streaming query committed, by the ID of the query. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + epochs: BTreeMap<String, i64>, +} + +impl Default for Manifest { + fn default() -> Self { + Self { + version: 1, + files: Vec::new(), + epochs: BTreeMap::new(), + } + } +} + +fn read_manifest(root: &Path) -> Result<Manifest> { + let file = match File::open(root.join("manifest.json")) { + Ok(file) => file, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Manifest::default()), + Err(error) => return Err(error.into()), + }; + let manifest: Manifest = serde_json::from_reader(file)?; + if manifest.version != 1 { + return Err("Unsupported sink manifest version".into()); + } + for file in &manifest.files { + let components = Path::new(&file.path).components().collect::<Vec<_>>(); + if components.len() != 3 + || components[0] != Component::Normal("objects".as_ref()) + || !components.iter().all(|c| matches!(c, Component::Normal(_))) + { + return Err("Invalid sink manifest data path".into()); + } + } + Ok(manifest) +} + +/// This lock is held for the whole write operation, including all task attempts. +struct WriteLock(PathBuf); + +impl WriteLock { + fn acquire(root: &Path) -> Result<Self> { + let path = root.join(".write-lock"); + match fs::create_dir(&path) { + Ok(()) => Ok(Self(path)), + Err(error) if error.kind() == ErrorKind::AlreadyExists => { + Err("Another write owns .write-lock; concurrent writes are unsupported".into()) + } + Err(error) => Err(error.into()), + } + } +} + +impl Drop for WriteLock { + fn drop(&mut self) { + let _ = fs::remove_dir(&self.0); + } +} + +pub struct JsonWrite { + root: PathBuf, + operation: String, + staging: PathBuf, + objects: PathBuf, + temporary_manifest: PathBuf, + previous: Manifest, + truncate: bool, + committed: bool, + sealed: bool, + lock: Option<WriteLock>, +} + +impl JsonWrite { + fn new(root: PathBuf, mode: WriteMode) -> Result<Self> { + if !cfg!(unix) { + return Err("This demo requires a POSIX filesystem".into()); + } + let truncate = match mode { + WriteMode::Append => false, + WriteMode::Truncate => true, + _ => return Err("Unsupported write mode".into()), + }; + fs::create_dir_all(&root)?; + let lock = WriteLock::acquire(&root)?; + let previous = read_manifest(&root)?; + fs::create_dir_all(root.join(".staging"))?; + fs::create_dir_all(root.join("objects"))?; + let staging = unique_directory(&root.join(".staging"))?; + let operation = staging.file_name().unwrap().to_str().unwrap().to_owned(); + Ok(Self { + objects: root.join("objects").join(&operation), + temporary_manifest: root.join(format!(".manifest-{operation}.json")), + root, + operation, + staging, + previous, + truncate, + committed: false, + sealed: false, + lock: Some(lock), + }) + } + + /// Publishes the winning attempts, and records the epoch of a streaming query. + fn publish( + &mut self, + messages: Vec<CommitMessage>, + epoch: Option<(String, i64)>, + ) -> Result<()> { + let mut filenames = BTreeSet::new(); + for (index, message) in messages.iter().enumerate() { + if message.operation != self.operation + || !is_filename(&message.filename) + || !filenames.insert(message.filename.clone()) + { + return Err("Invalid or duplicate task commit message".into()); + } + // Spark passes the message of partition i at position i. + if usize::try_from(message.partition).ok() != Some(index) { + return Err("A commit message does not match its partition".into()); + } + if !self.staging.join(&message.filename).is_file() { + return Err("A winning task's staged file is missing".into()); + } + } + + // Seal the entire operation directory. New attempts can no longer open + // a staged file, and existing losing files remain invisible to readers. + // A killed attempt that is still running, such as a losing speculative one, + // may have resolved the staging directory just before this rename and create + // its file after the sweep below. That file stays in the sealed directory, + // unlisted, so readers never see it. Such an attempt may also be aborting, and + // its unlink can remove a losing file after the listing below returns it. + fs::rename(&self.staging, &self.objects)?; + self.sealed = true; + for entry in fs::read_dir(&self.objects)? { + let entry = entry?; + if !filenames.contains(&entry.file_name().to_string_lossy().into_owned()) { + match fs::remove_file(entry.path()) { + Ok(()) => {} + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(error.into()), + } + } + } + + let mut files = if self.truncate { + Vec::new() + } else { + self.previous.files.clone() + }; + files.extend(messages.into_iter().map(|message| DataFile { + path: format!("objects/{}/{}", self.operation, message.filename), + rows: message.rows, + })); + let mut epochs = self.previous.epochs.clone(); + if let Some((query_id, epoch_id)) = epoch { + epochs.insert(query_id, epoch_id); + } + let manifest = Manifest { + version: 1, + files, + epochs, + }; + let file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&self.temporary_manifest)?; + let mut writer = BufWriter::new(file); + serde_json::to_writer(&mut writer, &manifest)?; + writer.write_all(b"\n")?; + writer.flush()?; + writer.get_ref().sync_all()?; + drop(writer); + + // This single rename is the commit point. No existing data is deleted, + // including during truncate. No fallible work follows publication. + if let Err(error) = fs::rename(&self.temporary_manifest, self.root.join("manifest.json")) { + // A rename that reports an error, for example on a network filesystem that loses + // the reply, may still have taken effect, and then the new manifest lists the + // objects. Abort and Drop keep them: unlisted objects are invisible to readers. + self.sealed = false; Review Comment: Done in 40fbaf065d48: Added `a_failed_manifest_rename_keeps_the_sealed_files_that_it_may_have_published`. A directory at `manifest.json` makes the final rename fail after the seal, and the test checks that `objects/<operation>` survives the failed commit, the abort and Drop. ########## sql/native/rust/tests/streaming.rs: ########## @@ -0,0 +1,888 @@ +// 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. + +use std::ffi::{c_char, c_int, c_void, CStr, CString}; +use std::mem::size_of; +use std::ptr; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; + +use arrow_array::ffi::FFI_ArrowArray; +use arrow_array::ffi_stream::{ArrowArrayStreamReader, FFI_ArrowArrayStream}; +use arrow_array::{Array, Int64Array, RecordBatch, StructArray}; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use serde::{Deserialize, Serialize}; +use spark_datasource::__private::abi::{ + self, ArrowSchema, SparkDsCommitOffsetInfo, SparkDsCreateInfo, SparkDsDataWriterInfo, + SparkDsFinishDataWriterInfo, SparkDsFinishWriteInfo, SparkDsHost, SparkDsInitialOffsetInfo, + SparkDsLatestOffsetInfo, SparkDsLibrary, SparkDsPartitionsInfo, SparkDsReadInfo, + SparkDsReadLimit, SparkDsReaderInfo, SparkDsStreamPartitionsInfo, SparkDsStreamReaderInfo, + SparkDsTaskContext, SparkDsWriteInfo, ABI_VERSION, +}; +use spark_datasource::{ + Capabilities, CommitOffsetInfo, CreateInfo, DataSource, DataWriter, DataWriterFactory, + LatestOffsetInfo, MicroBatchInfo, MicroBatchStream, MicroBatchStreamInfo, PartitionReader, + PartitionReaderFactory, PartitionWriter, ReadLimit, ReaderContext, Result, ScanBuilder, + ScanInfo, ScanPlan, StreamingAbortInfo, StreamingCommitInfo, StreamingWrite, + StreamingWriteInfo, Unsupported, WriterContext, +}; + +// Each test exercises the actual exported table; this lock isolates fixture observations. +static TEST_LOCK: Mutex<()> = Mutex::new(()); +static EVENTS: Mutex<Vec<Event>> = Mutex::new(Vec::new()); +// The position of the latest data of the streams. +static LATEST: AtomicU64 = AtomicU64::new(0); + +#[derive(Clone, Debug, PartialEq)] +enum Event { + StreamCreated(String), + LatestOffset(u64, ReadLimit, Option<u64>), + OffsetCommitted(u64), + WriteCreated { query_id: String, truncate: bool }, + EpochCommitted(i64, Vec<Message>), + EpochAborted(i64, Vec<Option<Message>>), + WriteDropped, +} + +fn record(event: Event) { + EVENTS.lock().unwrap().push(event); +} + +fn events() -> Vec<Event> { + EVENTS.lock().unwrap().clone() +} + +fn schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Int64, + false, + )])) +} + +fn batch(values: Vec<i64>) -> RecordBatch { + RecordBatch::try_new(schema(), vec![Arc::new(Int64Array::from(values))]).unwrap() +} + +/// Batch and micro-batch reads, whose reader factories have different types, and streaming +/// writes without batch writes. +struct Source { + failure: String, + capabilities: String, + max_rows: Option<u64>, +} + +impl DataSource for Source { + type ScanBuilder = Scan; + type MicroBatchStream = Stream; + type BatchWrite = Unsupported; + type StreamingWrite = Write; + + fn new(info: CreateInfo) -> Result<Self> { + let option = |name: &str| info.options.get(name).cloned().unwrap_or_default(); + Ok(Self { + failure: option("failure"), + capabilities: option("capabilities"), + max_rows: info + .options + .get("maxrows") + .map(|rows| rows.parse()) + .transpose()?, + }) + } + + fn infer_schema(&self) -> Result<SchemaRef> { + Ok(schema()) + } + + fn capabilities(&self) -> Capabilities { + match self.capabilities.as_str() { + "no_streaming_write" => Capabilities::all().without(Capabilities::STREAMING_WRITE), + "append_only" => Capabilities::all().without(Capabilities::STREAMING_TRUNCATE), + _ => Capabilities::all(), + } + } + + fn new_scan(&self, _: ScanInfo) -> Result<Scan> { + Ok(Scan) + } + + fn new_micro_batch_stream(&self, info: MicroBatchStreamInfo) -> Result<Stream> { + if info.schema != schema() { + return Err("unsupported stream schema".into()); + } + record(Event::StreamCreated(info.checkpoint_location)); + Ok(Stream { + failure: self.failure.clone(), + max_rows: self.max_rows, + }) + } + + fn new_streaming_write(&self, info: StreamingWriteInfo) -> Result<Write> { + record(Event::WriteCreated { + query_id: info.query_id, + truncate: info.mode == spark_datasource::WriteMode::Truncate, + }); + Ok(Write) + } +} + +struct Scan; + +impl ScanBuilder for Scan { + type Factory = BatchFactory; + + fn plan(self) -> Result<ScanPlan<BatchFactory>> { + Ok(ScanPlan::new(BatchFactory(100), vec![5])) + } +} + +/// Reads `factory + partition` from each partition of a batch scan. +#[derive(Serialize, Deserialize)] +struct BatchFactory(i64); + +impl PartitionReaderFactory for BatchFactory { + type Partition = i64; + + fn open<'task>( + &self, + partition: i64, + _: ReaderContext<'task>, + ) -> Result<PartitionReader<'task>> { + Ok(Box::new(std::iter::once(Ok(batch(vec![ + self.0 + partition, + ]))))) + } +} + +struct Stream { + failure: String, + max_rows: Option<u64>, +} + +/// The note checks that offsets stay on one line, as Spark requires. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +struct Offset { + position: u64, + note: String, +} + +impl Offset { + fn at(position: u64) -> Self { + Self { + position, + note: "two\nlines".into(), + } + } +} + +impl MicroBatchStream for Stream { + type Offset = Offset; + type Factory = StreamFactory; + + fn initial_offset(&mut self) -> Result<Offset> { + Ok(Offset::at(0)) + } + + fn default_read_limit(&self) -> Result<ReadLimit> { + Ok(self + .max_rows + .map_or(ReadLimit::AllAvailable, ReadLimit::MaxRows)) + } + + fn latest_offset(&mut self, info: LatestOffsetInfo<Offset>) -> Result<Offset> { + if self.failure == "latest_panic" { + panic!("finding the latest offset panicked"); + } + let start = info.start.position; + let run_end = info.run_end.map(|end| end.position); + record(Event::LatestOffset(start, info.limit, run_end)); + let mut end = LATEST.load(Ordering::SeqCst); + if let ReadLimit::MaxRows(rows) = info.limit { + end = end.min(start + rows); + } + Ok(Offset::at(run_end.map_or(end, |run_end| end.min(run_end)))) + } + + fn plan(&mut self, info: MicroBatchInfo<Offset>) -> Result<ScanPlan<StreamFactory>> { + let positions = (info.start.position..info.end.position).collect(); + Ok(ScanPlan::new(StreamFactory { scale: 10 }, positions)) + } + + fn commit(&mut self, info: CommitOffsetInfo<Offset>) -> Result<()> { + record(Event::OffsetCommitted(info.end.position)); + Ok(()) + } +} + +/// Reads `scale * position` from the partition of each position of a micro-batch. +#[derive(Serialize, Deserialize)] +struct StreamFactory { + scale: i64, +} + +impl PartitionReaderFactory for StreamFactory { + type Partition = u64; + + fn open<'task>( + &self, + position: u64, + _: ReaderContext<'task>, + ) -> Result<PartitionReader<'task>> { + let value = self.scale * position as i64; + Ok(Box::new(std::iter::once(Ok(batch(vec![value]))))) + } +} + +struct Write; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct Message { + epoch_id: Option<i64>, + values: Vec<i64>, +} + +impl StreamingWrite for Write { + type Factory = WriteFactory; + type Message = Message; + + const SUPPORTS_TRUNCATE: bool = true; + + fn new_writer_factory(&self) -> Result<WriteFactory> { + Ok(WriteFactory) + } + + fn commit(&mut self, info: StreamingCommitInfo<Message>) -> Result<()> { + record(Event::EpochCommitted(info.epoch_id, info.messages)); + Ok(()) + } + + fn abort(&mut self, info: StreamingAbortInfo<Message>) -> Result<()> { + record(Event::EpochAborted(info.epoch_id, info.messages)); + Ok(()) + } +} + +impl Drop for Write { + fn drop(&mut self) { + record(Event::WriteDropped); + } +} + +#[derive(Serialize, Deserialize)] +struct WriteFactory; + +impl DataWriterFactory for WriteFactory { + type Message = Message; + + fn open<'task>( + &self, + context: WriterContext<'task>, + ) -> Result<PartitionWriter<'task, Message>> { + Ok(Box::new(Writer { + message: Message { + epoch_id: context.epoch_id, + values: vec![], + }, + })) + } +} + +struct Writer { + message: Message, +} + +impl DataWriter for Writer { + type Message = Message; + + fn write(&mut self, batch: RecordBatch) -> Result<()> { + let values = batch + .column(0) + .as_any() + .downcast_ref::<Int64Array>() + .unwrap(); + self.message.values.extend(values.values()); + Ok(()) + } + + fn commit(&mut self) -> Result<Message> { + Ok(self.message.clone()) + } + + fn abort(&mut self) -> Result<()> { + Ok(()) + } +} + +spark_datasource::export_data_source!(Source); + +extern "C" { + fn spark_ds_init(host: *const SparkDsHost, library: *mut *const SparkDsLibrary) -> c_int; +} + +fn library() -> &'static SparkDsLibrary { + // Spark's host structure stays valid until the JVM exits. + let host = Box::leak(Box::new(SparkDsHost { + size: size_of::<SparkDsHost>() as i64, + abi_version: ABI_VERSION, + spark_version: c"test".as_ptr(), + log: None, + is_log_enabled: None, + })); + let mut table = ptr::null(); + assert_eq!(unsafe { spark_ds_init(host, &mut table) }, 0); + unsafe { &*table } +} + +fn error(library: &SparkDsLibrary) -> String { + let message = unsafe { library.last_error.unwrap()() }; + assert!(!message.is_null()); + unsafe { CStr::from_ptr(message) }.to_str().unwrap().into() +} + +fn success(library: &SparkDsLibrary, status: c_int) { + assert_eq!(status, 0, "{}", error(library)); +} + +/// The values that a call passes to its sinks: each sink gets a list of its own. +#[derive(Default)] +struct Sinks { + values: Vec<Vec<u8>>, + states: Vec<Vec<u8>>, +} + +unsafe extern "C" fn add_value(sink: *mut c_void, bytes: *const u8, length: i64) { + let sinks = unsafe { &mut *sink.cast::<Sinks>() }; + sinks + .values + .push(unsafe { std::slice::from_raw_parts(bytes, length as usize) }.to_vec()); +} + +unsafe extern "C" fn set_state(sink: *mut c_void, bytes: *const u8, length: i64) { + let sinks = unsafe { &mut *sink.cast::<Sinks>() }; + sinks + .states + .push(unsafe { std::slice::from_raw_parts(bytes, length as usize) }.to_vec()); +} + +/// Calls a function of the table that passes its results to sinks. +fn emitted(library: &SparkDsLibrary, call: impl FnOnce(*mut c_void) -> c_int) -> (c_int, Sinks) { + let mut sinks = Sinks::default(); + let status = call((&mut sinks as *mut Sinks).cast()); + if status != 0 { + assert!(sinks.values.is_empty() && sinks.states.is_empty()); + let _ = error(library); + } + (status, sinks) +} + +/// The single value of a call, such as an offset. +fn single(library: &SparkDsLibrary, call: impl FnOnce(*mut c_void) -> c_int) -> Vec<u8> { + let (status, mut sinks) = emitted(library, call); + success(library, status); + assert_eq!(sinks.values.len(), 1); + assert!(sinks.states.is_empty()); + sinks.values.pop().unwrap() +} + +/// The partitions of a plan, and its state, which a planning call returns once. +fn planned(library: &SparkDsLibrary, call: impl FnOnce(*mut c_void) -> c_int) -> Sinks { + let (status, sinks) = emitted(library, call); + success(library, status); + assert_eq!(sinks.states.len(), 1, "a plan has a single state"); + sinks +} + +fn source(library: &SparkDsLibrary, options: &[(&str, &str)]) -> (*mut c_void, u64) { + let options: Vec<(CString, CString)> = options + .iter() + .map(|(key, value)| (CString::new(*key).unwrap(), CString::new(*value).unwrap())) + .collect(); + let keys: Vec<*const c_char> = options.iter().map(|(key, _)| key.as_ptr()).collect(); + let values: Vec<*const c_char> = options.iter().map(|(_, value)| value.as_ptr()).collect(); + let info = SparkDsCreateInfo { + size: size_of::<SparkDsCreateInfo>() as i64, + name: c"streaming_test".as_ptr(), + option_keys: keys.as_ptr(), + option_values: values.as_ptr(), + num_options: keys.len() as i64, + }; + let mut mask = 0; + let mut pointer = ptr::null_mut(); + success(library, unsafe { + library.create.unwrap()(&info, &mut mask, &mut pointer) + }); + (pointer, mask) +} + +fn stream_reader(library: &SparkDsLibrary, options: &[(&str, &str)]) -> *mut c_void { + let (source, _) = source(library, options); + let mut schema = ArrowSchema::try_from(schema().as_ref()).unwrap(); + let info = SparkDsStreamReaderInfo { + size: size_of::<SparkDsStreamReaderInfo>() as i64, + checkpoint_location: c"file:/tmp/checkpoint/sources/0".as_ptr(), + }; + let mut reader = ptr::null_mut(); + let status = + unsafe { library.create_stream_reader.unwrap()(source, &mut schema, &info, &mut reader) }; + // Before close, which clears the error of the thread. + success(library, status); + // A stream reader outlives its source, which Spark closes right after creating it. + unsafe { library.close.unwrap()(source) }; + reader +} + +fn read_limit(kind: i32, max_rows: i64) -> SparkDsReadLimit { + SparkDsReadLimit { + size: size_of::<SparkDsReadLimit>() as i64, + kind, + max_rows, + } +} + +fn latest( + library: &SparkDsLibrary, + reader: *mut c_void, + start: &CStr, + limit: &SparkDsReadLimit, + run_end: Option<&CStr>, +) -> (c_int, Sinks) { + let info = SparkDsLatestOffsetInfo { + size: size_of::<SparkDsLatestOffsetInfo>() as i64, + start: start.as_ptr(), + limit, + run_end: run_end.map_or(ptr::null(), CStr::as_ptr), + }; + emitted(library, |sink| unsafe { + library.latest_offset.unwrap()(reader, &info, Some(add_value), sink) + }) +} + +fn stream_partitions( + library: &SparkDsLibrary, + reader: *mut c_void, + start: &CStr, + end: &CStr, +) -> (c_int, Sinks) { + let info = SparkDsStreamPartitionsInfo { + size: size_of::<SparkDsStreamPartitionsInfo>() as i64, + start: start.as_ptr(), + end: end.as_ptr(), + }; + emitted(library, |sink| unsafe { + library.stream_partitions.unwrap()(reader, &info, Some(add_value), Some(set_state), sink) + }) +} + +fn task(partition: i32) -> SparkDsTaskContext { + SparkDsTaskContext { + size: size_of::<SparkDsTaskContext>() as i64, + stage_id: 1, + stage_attempt_number: 0, + partition_id: partition, + attempt_number: 0, + task_attempt_id: 10 + i64::from(partition), + is_interrupted: None, + } +} + +/// Reads a partition with the read function that batch scans and micro-batches share. +fn read(library: &SparkDsLibrary, kind: i32, state: &[u8], partition: &[u8]) -> Vec<i64> { + let task = task(0); + let mut read_schema = ArrowSchema::try_from(schema().as_ref()).unwrap(); + let info = SparkDsReadInfo { + size: size_of::<SparkDsReadInfo>() as i64, + kind, + schema: &mut read_schema, + reader_state: state.as_ptr(), + reader_state_length: state.len() as i64, + partition: partition.as_ptr(), + partition_length: partition.len() as i64, + }; + let mut stream = FFI_ArrowArrayStream::empty(); + success(library, unsafe { + library.read.unwrap()(&task, &info, &mut stream) + }); + ArrowArrayStreamReader::try_new(stream) + .unwrap() + .flat_map(|batch| { + let batch = batch.unwrap(); + let values = batch + .column(0) + .as_any() + .downcast_ref::<Int64Array>() + .unwrap(); + values.values().to_vec() + }) + .collect() +} + +#[test] +fn streaming_operations_declare_their_capabilities_and_callbacks() { + let _guard = TEST_LOCK.lock().unwrap_or_else(PoisonError::into_inner); + let library = library(); + assert!(library.create_reader.is_some() && library.create_stream_reader.is_some()); + assert!(library.initial_offset.is_some() && library.latest_offset.is_some()); + assert!(library.stream_partitions.is_some() && library.default_read_limit.is_some()); + assert!(library.commit_offset.is_some() && library.close_stream_reader.is_some()); + assert!(library.read.is_some() && library.create_writer.is_some()); + assert!(library.create_data_writer.is_some() && library.close_data_writer.is_some()); + + // Every stream supports admission control, and only streaming writes truncate. + let streaming_truncate = abi::STREAMING_WRITE | abi::STREAMING_TRUNCATE; Review Comment: Done in 40fbaf065d48: `c_header_matches_rust_layout` now also compiles a `_Static_assert` for every constant of the bindings, including `STREAMING_WRITE` and `STREAMING_TRUNCATE`, against its `SPARK_DS_*` macro in the header. ########## sql/native/rust/src/write.rs: ########## @@ -0,0 +1,499 @@ +// 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. + +//! Driver write coordination and task-local writers restored from serialized state, for batch +//! writes and for the writes of micro-batches. + +use std::ffi::c_void; + +use arrow_array::{ffi, Array, RecordBatch, StructArray}; +use arrow_data::ArrayData; +use arrow_schema::{ArrowError, DataType, SchemaRef}; +use serde::Serialize; + +use crate::abi::{self, ArrowArray, SparkDsTaskContext}; +use crate::bridge::stream::validate_schema; +use crate::bridge::{decode, describe, drop_provider, encode, provider_call}; +use crate::{ + AbortInfo, BatchWrite, CommitInfo, DataWriter, DataWriterFactory, PartitionWriter, Result, + StreamingAbortInfo, StreamingCommitInfo, StreamingWrite, TaskContext, WriterContext, +}; + +/// A batch write, which a driver writer drives as a streaming write whose epoch ID is always +/// -1 and is ignored. +pub struct Batch<W>(pub W); + +impl<W: BatchWrite> StreamingWrite for Batch<W> { + type Factory = W::Factory; + type Message = W::Message; + + fn new_writer_factory(&self) -> Result<W::Factory> { + self.0.new_writer_factory() + } + + fn commit(&mut self, info: StreamingCommitInfo<W::Message>) -> Result<()> { + self.0.commit(CommitInfo::new(info.messages)) + } + + fn abort(&mut self, info: StreamingAbortInfo<W::Message>) -> Result<()> { + self.0.abort(AbortInfo::new(info.messages)) + } +} + +/// A driver writer that decodes its own commit messages, so that one handle type holds the +/// driver writers of batch writes and of the writes of micro-batches, which share the writer +/// handles of the ABI. +pub trait DriverWrite: Send { + fn commit(&mut self, epoch_id: i64, messages: &[Option<&[u8]>]) -> Result<()>; + + fn abort(&mut self, epoch_id: i64, messages: &[Option<&[u8]>]) -> Result<()>; +} + +/// The driver keeps this coordinator until close, including after a failed commit, which +/// Spark aborts next. Spark closes the writer right after it commits or aborts the write. +pub struct DriverWriter<C: StreamingWrite> { + coordinator: Option<C>, +} + +impl<C: StreamingWrite> DriverWriter<C> { + /// Wraps a coordinator, with the state that its task writers need: its serialized + /// writer factory. On failure, the coordinator is dropped. + pub fn create(coordinator: C) -> Result<(Box<dyn DriverWrite>, Vec<u8>)> { + let writer = Self { + coordinator: Some(coordinator), + }; + // The factory's destructor is connector code too, so it runs in provider_call. + let state = provider_call(|| encode(&writer.coordinator().new_writer_factory()?))?; + Ok((Box::new(writer), state)) + } + + fn coordinator(&self) -> &C { + self.coordinator.as_ref().expect("coordinator is present") + } + + fn coordinator_mut(&mut self) -> &mut C { + self.coordinator.as_mut().expect("coordinator is present") + } +} + +impl<C: StreamingWrite> DriverWrite for DriverWriter<C> { + fn commit(&mut self, epoch_id: i64, messages: &[Option<&[u8]>]) -> Result<()> { + let messages = messages + .iter() + .map(|message| decode(message.ok_or("missing committed task message")?)) + .collect::<Result<Vec<_>>>()?; + self.coordinator_mut() + .commit(StreamingCommitInfo::new(epoch_id, messages)) + } + + fn abort(&mut self, epoch_id: i64, messages: &[Option<&[u8]>]) -> Result<()> { + // Abort is the cleanup path: a message that cannot be decoded is passed as None + // instead of preventing the coordinator from cleaning up. + let messages = messages + .iter() + .enumerate() + .map(|(partition, message)| match decode((*message)?) { + Ok(message) => Some(message), + Err(error) => { + log::warn!( + "Aborting a write without the commit message of partition \ + {partition}, which cannot be decoded: {}", + describe(&*error) + ); + None + } + }) + .collect(); + self.coordinator_mut() + .abort(StreamingAbortInfo::new(epoch_id, messages)) + } +} + +impl<C: StreamingWrite> Drop for DriverWriter<C> { + fn drop(&mut self) { + // A panic of the coordinator's Drop is logged instead of unwinding into close. + if let Some(coordinator) = self.coordinator.take() { + drop_provider(coordinator); + } + } +} + +/// A task writer that encodes its own commit message, so that one handle type holds the +/// writers of batch and streaming writes, whatever their messages. +trait TaskWriter: Send { + fn write(&mut self, batch: RecordBatch) -> Result<()>; + + fn commit(&mut self) -> Result<Vec<u8>>; + + fn abort(&mut self) -> Result<()>; +} + +impl<M: Serialize> TaskWriter for PartitionWriter<'_, M> { + fn write(&mut self, batch: RecordBatch) -> Result<()> { + DataWriter::write(&mut **self, batch) + } + + fn commit(&mut self) -> Result<Vec<u8>> { + encode(&DataWriter::commit(&mut **self)?) + } + + fn abort(&mut self) -> Result<()> { + DataWriter::abort(&mut **self) + } +} + +struct TaskState<'task> { + writer: Option<Box<dyn TaskWriter + 'task>>, + // The struct type of the arrays that write gets: the schema that create_data_writer got. + data_type: DataType, +} + +impl TaskState<'_> { + fn writer(&mut self) -> &mut (dyn TaskWriter + '_) { + self.writer.as_deref_mut().expect("writer is present") + } +} + +impl Drop for TaskState<'_> { + fn drop(&mut self) { + if let Some(writer) = self.writer.take() { + drop_provider(writer); + } + } +} + +/// Restores the task writer of a batch write, with factory `B`, or of a micro-batch, with +/// factory `S`, without creating or consulting any driver registry. The epoch ID tells them +/// apart: it is -1 for a batch write. +/// +/// # Safety +/// `task` must satisfy TaskContext::from_raw and remain valid until close_task. +/// The returned handle must never be used concurrently, and must be closed exactly +/// once while the plugin stays loaded. +pub unsafe fn open<B: DataWriterFactory, S: DataWriterFactory>( + task: *const SparkDsTaskContext, + schema: SchemaRef, + state: &[u8], + epoch_id: i64, +) -> Result<*mut c_void> { + match epoch_id { + -1 => unsafe { open_writer::<B>(task, schema, state, None) }, + epoch_id if epoch_id >= 0 => unsafe { + open_writer::<S>(task, schema, state, Some(epoch_id)) + }, + _ => Err(format!("invalid epoch ID {epoch_id}").into()), + } +} + +/// # Safety +/// As for open. +unsafe fn open_writer<F: DataWriterFactory>( + task: *const SparkDsTaskContext, + schema: SchemaRef, + state: &[u8], + epoch_id: Option<i64>, +) -> Result<*mut c_void> { + validate_schema(&schema)?; + let factory: F = decode(state)?; + let (task, partition_id) = unsafe { TaskContext::from_raw(task)? }; + let data_type = DataType::Struct(schema.fields().clone()); + let mut context = WriterContext::new(schema, partition_id, task); + context.epoch_id = epoch_id; + let opened = provider_call(|| factory.open(context)); + // Keep guarded writer destruction in place before dropping the temporary + // factory, whose destructor is connector code too. + let state = opened.map(|writer| { + Box::new(TaskState { + writer: Some(Box::new(writer)), + data_type, + }) + }); + let factory_drop = provider_call(|| { + drop(factory); + Ok(()) + }); + let state = state?; + factory_drop?; + Ok(Box::into_raw(state).cast()) +} + +/// # Safety +/// `handle` must be a live handle from open, accessed without concurrency. +unsafe fn task_state<'a>(handle: *mut c_void) -> Result<&'a mut TaskState<'a>> { + abi::require_output(handle)?; + Ok(unsafe { &mut *handle.cast::<TaskState<'a>>() }) +} + +/// Imports owned Arrow data, with the schema of the writer, and passes it to the task writer. +/// +/// # Safety +/// `handle` must follow open's contract. The array must be valid Arrow C data of the schema +/// of the writer, which this call may move. +pub unsafe fn write_batch(handle: *mut c_void, array: *mut ArrowArray) -> Result<()> { + let state = unsafe { task_state(handle)? }; + abi::require_output(array)?; + let array = unsafe { import(ArrowArray::from_raw(array), &state.data_type)? }; + if array.null_count() != 0 { + return Err("write input cannot contain null rows".into()); + } + state.writer().write(RecordBatch::from(array)) +} + +/// Imports a batch to write. Arrow does not validate the C data that it imports, which the safe +/// accessors of the connector rely on, so this validates its layout and values, but not its +/// nullability: a Spark string may hold bytes that are not UTF-8, such as those of a cast from +/// binary, which a Rust `&str` must not. Review Comment: Done in 40fbaf065d48: Applied the suggestion: the UTF-8 reason now explains why values are validated, and the comment says nullability is left to Spark for the reason that `validate` gives. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
