tdcmeehan commented on code in PR #59520:
URL: https://github.com/apache/spark/pull/59520#discussion_r4544484043


##########
sql/native/rust/src/write.rs:
##########
@@ -0,0 +1,279 @@
+// 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_schema::{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")?))

Review Comment:
   No test reaches this check: every driver commit in tests/batch_write.rs and 
tests/streaming.rs passes `Some` messages, and `None` appears only in aborts. 
Two other guards are untested too: `write_batch` rejecting top-level null rows 
(L249-L251), and `check_values` treating map keys as non-null whatever the 
schema to read says (stream.rs L350-L351). So skipping a missing message here, 
dropping the `null_count` check, or dropping `.with_nullable(false)` on the key 
would each still pass `cargo test`. Could tests/batch_write.rs commit with 
`&[None]` and write a struct array with a null row, and stream.rs read a map 
with a null key? `MapBuilder` rejects null keys, but `StructArray::try_new` 
with a nullable key field, followed by `MapArray::try_new`, builds one.



##########
sql/native/rust/src/stream.rs:
##########
@@ -0,0 +1,963 @@
+// 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)?));
+        }
+        match &self.projection {
+            Some((_, Some(indices))) => Ok(batch.project(indices)?),
+            _ => Ok(batch),
+        }
+    }
+}
+
+/// Describes how the schema of a batch differs from that of the stream. Both 
have the
+/// columns of the schema to read, so either a column or the metadata of the 
schema differs.
+fn schema_change(stream: &Schema, batch: &Schema) -> String {
+    let mut fields = stream.fields().iter().zip(batch.fields());
+    match fields.find(|(first, field)| first != field) {
+        Some((first, field)) => format!(
+            "reader returned a batch with a different schema: the column {} is 
{first:?} in \
+             the first batch and {field:?} in this one",
+            first.name()
+        ),
+        None => "reader returned a batch with a different schema: its metadata 
differs".to_owned(),
+    }
+}
+
+/// The indices of the columns of the schema to read, in its order, in the 
schema of a batch
+/// that may have more, or None when the batch has exactly those columns.
+fn projection(schema: &Schema, expected: &Schema) -> 
Result<Option<Vec<usize>>> {
+    let names = |fields: &Fields| fields.iter().map(|field| 
field.name().clone()).collect();
+    let actual: Vec<String> = names(schema.fields());
+    let wanted: Vec<String> = names(expected.fields());
+    if actual == wanted {
+        return Ok(None);
+    }
+    let indices =
+        wanted
+            .iter()
+            .map(|name| {
+                actual.iter().position(|actual| actual == name).ok_or_else(|| {
+                format!("reader returned a batch without the column {name} of 
the schema to read")
+            })
+            })
+            .collect::<std::result::Result<Vec<_>, _>>()?;
+    Ok(Some(indices))
+}
+
+impl Drop for StreamState<'_> {
+    fn drop(&mut self) {
+        // release has no error return channel, but it must never unwind into 
C.
+        if let Some(reader) = self.reader.take() {
+            drop_provider(reader);
+        }
+    }
+}
+
+/// The reader may borrow the host task context until the consumer releases
+/// this stream. Erasure into C private_data is confined to this boundary.
+///
+/// # Safety
+/// The caller must keep everything borrowed by the reader alive until release,
+/// and the consumer must obey the Arrow C Stream ownership protocol.
+pub(super) unsafe fn export(
+    reader: PartitionReader<'_>,
+    expected_schema: &SchemaRef,
+) -> FFI_ArrowArrayStream {
+    let state = Box::new(StreamState {
+        reader: Some(reader),
+        expected: expected_schema.clone(),
+        schema: None,
+        projection: None,
+        pending: None,
+        last_error: None,
+        finished: false,
+    });
+    FFI_ArrowArrayStream {
+        get_schema: Some(get_schema),
+        get_next: Some(get_next),
+        get_last_error: Some(get_last_error),
+        release: Some(release),
+        private_data: Box::into_raw(state).cast::<c_void>(),
+    }
+}
+
+fn callback(
+    state: &mut StreamState<'_>,
+    action: impl FnOnce(&mut StreamState<'_>) -> Result<()>,
+) -> c_int {
+    // A failed stream stays failed, with its error: an engine that calls it 
again must not
+    // read a failed partition as complete.
+    if state.last_error.is_some() {
+        return 5;
+    }
+    let Err(message) = provider_call(|| action(state)) else {
+        return 0;
+    };
+    state.last_error = Some(c_message(message));
+    5 // EIO; get_last_error supplies the provider's actual error message.
+}
+
+unsafe extern "C" fn get_schema(
+    stream: *mut FFI_ArrowArrayStream,
+    output: *mut FFI_ArrowSchema,
+) -> c_int {
+    let state = unsafe { &mut 
*(*stream).private_data.cast::<StreamState<'_>>() };
+    callback(state, |state| {
+        // The reader does not declare a schema: read the first batch, which 
has it.
+        if state.schema.is_none() && !state.finished {
+            state.pending = state.read_next()?;
+        }
+        let schema = state.schema.as_ref().unwrap_or(&state.expected);
+        let schema = FFI_ArrowSchema::try_from(schema.as_ref())?;
+        unsafe { output.write(schema) };
+        Ok(())
+    })
+}
+
+unsafe extern "C" fn get_next(
+    stream: *mut FFI_ArrowArrayStream,
+    output: *mut FFI_ArrowArray,
+) -> c_int {
+    let state = unsafe { &mut 
*(*stream).private_data.cast::<StreamState<'_>>() };
+    callback(state, |state| {
+        let data = match state.pending.take() {
+            Some(data) => Some(data),
+            None if state.finished => None,
+            None => state.read_next()?,
+        };
+        match data {
+            Some(data) => unsafe { output.write(FFI_ArrowArray::new(&data)) },
+            // A null release callback denotes EOF, including for zero-column 
data.
+            None => unsafe { output.write(FFI_ArrowArray::empty()) },
+        }
+        Ok(())
+    })
+}
+
+unsafe extern "C" fn get_last_error(stream: *mut FFI_ArrowArrayStream) -> 
*const c_char {
+    let state = unsafe { &*(*stream).private_data.cast::<StreamState<'_>>() };
+    state
+        .last_error
+        .as_ref()
+        .map_or(std::ptr::null(), |error| error.as_ptr())
+}
+
+unsafe extern "C" fn release(stream: *mut FFI_ArrowArrayStream) {
+    let state = unsafe { (*stream).private_data.cast::<StreamState<'_>>() };
+    // Mark released before destruction. The consumer owns the stream 
structure.
+    unsafe { stream.write(FFI_ArrowArrayStream::empty()) };
+    drop_provider(unsafe { Box::from_raw(state) });
+}
+
+// Compare the Spark logical types of version 1 of the ABI, ignoring Arrow
+// nullability/metadata and the interchangeable physical encodings of strings 
and
+// binary data. Spark also distinguishes only the presence of a time zone, not 
its
+// spelling. Nullability is checked against the data instead, in check_nulls.

Review Comment:
   `check_nulls` no longer exists: nullability and decimal precision are 
checked in `check_values` (L293).
   
   ```suggestion
   // spelling. Nullability is checked against the data instead, in 
check_values.
   ```



##########
examples/src/main/rust/native-data-sink/src/lib.rs:
##########
@@ -0,0 +1,928 @@
+// 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());
+            }

Review Comment:
   Of the checks here, the tests reach only the partition position (L784). 
Nothing commits a duplicate filename, a message of another operation, a name 
that isn't a plain filename, or a message whose staged file is missing. Nothing 
reads a manifest with an unsupported version or an invalid data path 
(`read_manifest`, L164-L177), and nothing interrupts a task before open, while 
writing or before commit (L455, L534, L553), although 
`TaskContext::for_testing().interrupted_by` makes that easy. Removing any of 
these checks keeps the sink's tests green, in an example meant to be copied. 
Could the tests cover them? For the commit cases, the published manifest should 
stay unchanged.



##########
examples/src/main/rust/native-data-sink/src/lib.rs:
##########
@@ -0,0 +1,928 @@
+// 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.
+        fs::rename(&self.staging, &self.objects)?;
+        self.sealed = true;
+        for entry in fs::read_dir(&self.objects)? {

Review Comment:
   The SDK says the writer of a killed attempt, such as a losing speculative 
one, "may still write, abort, and drop after the driver committed or aborted 
the write" (sql/native/rust/src/lib.rs L763-L764). If its `create_new` in 
`open` (L468) resolves `.staging/<op>` just before this rename and creates the 
file after the sweep below, the file stays in `objects/<op>` unlisted: its 
abort and Drop remove the old `.staging` path (L564-L578), which no longer 
exists. On abort, a create racing `remove_dir_all(&self.staging)` in `cleanup` 
(L338) can likewise fail the abort or leave the directory behind. Readers are 
unaffected, since they read only the files in the manifest. But the README says 
that abort removes the entire operation (L70), and names only process or 
machine failure as leaving staged files or unreferenced objects (L161-L162). 
Since connectors will copy this example, could the README name straggling 
attempts too, with a short comment here and at `cleanup`?



-- 
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]

Reply via email to