gengliangwang commented on code in PR #59520: URL: https://github.com/apache/spark/pull/59520#discussion_r4559680744
########## examples/src/main/rust/native-data-sink/src/lib.rs: ########## @@ -0,0 +1,1042 @@ +// 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); + } Review Comment: Done in f29353269658: The test now checks the whole epochs map after the Truncate epoch, then runs a batch append and checks that the rows are [6, 7] and the map is unchanged. ########## sql/native/rust/src/stream.rs: ########## @@ -0,0 +1,987 @@ +// 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, CString}; +use std::sync::Arc; + +use arrow_array::ffi::FFI_ArrowArray; +use arrow_array::ffi_stream::FFI_ArrowArrayStream; +use arrow_array::types::{Decimal128Type, DecimalType}; +use arrow_array::{Array, RecordBatch, StructArray}; +use arrow_data::ArrayData; +use arrow_schema::{ffi::FFI_ArrowSchema, DataType, Field, Fields, Schema, SchemaRef, TimeUnit}; + +use super::{c_message, drop_provider, provider_call}; +use crate::{PartitionReader, Result}; + +struct StreamState<'task> { + reader: Option<PartitionReader<'task>>, + // The schema to read, whose columns, Spark types, and nullability each batch must have. + expected: SchemaRef, + // The schema of the stream: that of the first batch, which every batch must have, or + // the schema to read of a reader without batches. Unknown until either is read. + schema: Option<SchemaRef>, + // The schema of the last batch that the reader returned, with the indices of the columns + // to read in it, or None when it has exactly those columns. + projection: Option<(SchemaRef, Option<Vec<usize>>)>, + // The first batch, when get_schema read it to learn the schema. + pending: Option<ArrayData>, + last_error: Option<CString>, + finished: bool, +} + +impl StreamState<'_> { + /// Reads and checks the next batch. The first batch, or the end of the reader, + /// determines the schema of the stream. + fn read_next(&mut self) -> Result<Option<ArrayData>> { + let Some(batch) = self.reader.as_mut().expect("reader is present").next() else { + self.finished = true; + self.schema.get_or_insert_with(|| self.expected.clone()); + return Ok(None); + }; + let batch = self.project(batch?)?; + match &self.schema { + Some(schema) if batch.schema() != *schema => { + return Err(schema_change(schema, &batch.schema()).into()); + } + Some(_) => {} + None => { + if canonical_fields(batch.schema().fields())? + != canonical_fields(self.expected.fields())? + { + return Err("executor reader schema does not match the schema to read".into()); + } + self.schema = Some(batch.schema()); + } + } + let data = StructArray::from(batch).to_data(); + validate_layout(&data)?; + for (column, field) in data.child_data().iter().zip(self.expected.fields()) { + check_values(column, field, field.name(), None)?; + } + Ok(Some(data)) + } + + /// Keeps the columns of the schema to read, in its order, from a batch that may have more, + /// such as all the columns of the source. Resolves the columns once for each schema. + fn project(&mut self, batch: RecordBatch) -> Result<RecordBatch> { + let schema = batch.schema(); + if !matches!(&self.projection, Some((last, _)) if *last == schema) { + self.projection = Some((schema.clone(), projection(&schema, &self.expected)?)); + } Review Comment: Done in f29353269658: Added `the_sdk_resolves_the_columns_again_when_a_batch_reorders_them`: the reader returns `[id, flag]` and then `[flag, id]` for the schema to read `[id]`, and both batches come back as `[id]` with their own values. -- 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]
