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


##########
examples/src/main/rust/native-data-sink/src/lib.rs:
##########
@@ -0,0 +1,1036 @@
+// 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.
+        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()) {
+                fs::remove_file(entry.path())?;
+            }
+        }
+
+        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;
+            return Err(error.into());
+        }
+        self.committed = true;
+        self.lock.take();
+        Ok(())
+    }
+
+    /// Publishes nothing, for an epoch whose output is already published: 
removes what this
+    /// write staged, and releases the lock.
+    fn skip(&mut self) -> Result<()> {
+        let result = self.cleanup();
+        // Nothing is left for Drop to clean.
+        self.committed = true;
+        self.lock.take();
+        result
+    }
+
+    fn cleanup(&self) -> Result<()> {
+        // Do not rely on commit messages: failed tasks and losing attempts may
+        // have staged files without returning a message to the driver. A 
killed
+        // attempt that is still running may also create a file while its 
directory
+        // is removed, which then fails this cleanup or leaves the directory 
behind.
+        let mut first_error = None;
+        for result in [
+            fs::remove_dir_all(&self.staging),
+            if self.sealed {
+                fs::remove_dir_all(&self.objects)
+            } else {
+                Ok(())
+            },
+            fs::remove_file(&self.temporary_manifest),
+        ] {
+            if let Err(error) = result {
+                if error.kind() != ErrorKind::NotFound && 
first_error.is_none() {
+                    first_error = Some(error);
+                }
+            }
+        }
+        match first_error {
+            Some(error) => Err(error.into()),
+            None => Ok(()),
+        }
+    }
+}
+
+// Spark calls each method at most once, and never aborts a successful commit, 
so this
+// coordinator does not track its own phase.
+impl BatchWrite for JsonWrite {
+    type Factory = JsonWriterFactory;
+    type Message = CommitMessage;
+
+    // The sink also supports overwrites.
+    const SUPPORTS_TRUNCATE: bool = true;
+
+    fn new_writer_factory(&self) -> Result<JsonWriterFactory> {
+        Ok(JsonWriterFactory {
+            staging: self.staging.clone(),
+            operation: self.operation.clone(),
+        })
+    }
+
+    fn commit(&mut self, info: CommitInfo<CommitMessage>) -> Result<()> {
+        self.publish(info.messages, None)
+    }
+
+    fn abort(&mut self, _info: AbortInfo<CommitMessage>) -> Result<()> {
+        let result = self.cleanup();
+        self.lock.take();
+        result
+    }
+}
+
+/// The write of a micro-batch, exactly once: the manifest records the last 
epoch that each
+/// streaming query committed, so an epoch that Spark commits again after a 
restart adds
+/// nothing.
+pub struct JsonStreamingWrite {
+    write: JsonWrite,
+    query_id: String,
+}
+
+impl StreamingWrite for JsonStreamingWrite {
+    type Factory = JsonWriterFactory;
+    type Message = CommitMessage;
+
+    // The output mode complete replaces the output of the previous 
micro-batches.
+    const SUPPORTS_TRUNCATE: bool = true;
+
+    fn new_writer_factory(&self) -> Result<JsonWriterFactory> {
+        self.write.new_writer_factory()
+    }
+
+    fn commit(&mut self, info: StreamingCommitInfo<CommitMessage>) -> 
Result<()> {
+        // The write holds the lock, so the manifest that it read is still the 
latest one.
+        let committed = self.write.previous.epochs.get(&self.query_id);
+        if committed.is_some_and(|last| *last >= info.epoch_id) {
+            return self.write.skip();
+        }
+        self.write
+            .publish(info.messages, Some((self.query_id.clone(), 
info.epoch_id)))
+    }
+
+    fn abort(&mut self, info: StreamingAbortInfo<CommitMessage>) -> Result<()> 
{
+        self.write.abort(AbortInfo::new(info.messages))
+    }
+}
+
+// A write can be dropped without abort, for example when creating or 
serializing its
+// factory fails, so an unfinished write also cleans up here.
+impl Drop for JsonWrite {
+    fn drop(&mut self) {
+        if !self.committed {
+            let _ = self.cleanup();
+        }
+    }
+}
+
+/// Serializable values only: the driver lock and open files stay on their 
hosts.
+#[derive(Deserialize, Serialize)]
+pub struct JsonWriterFactory {
+    staging: PathBuf,
+    operation: String,
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct CommitMessage {
+    operation: String,
+    filename: String,
+    partition: i32,
+    rows: u64,
+}
+
+impl DataWriterFactory for JsonWriterFactory {
+    type Message = CommitMessage;
+
+    fn open<'task>(
+        &self,
+        context: WriterContext<'task>,
+    ) -> Result<PartitionWriter<'task, Self::Message>> {
+        // Each batch has this schema, so the writer checks it once.
+        validate_schema(&context.schema)?;
+        let task = context.task;
+        if task.is_interrupted() {
+            return Err("Task cancelled before opening the sink".into());
+        }
+        // Do not recreate staging: its absence means the driver sealed or
+        // aborted this operation. create_new also separates speculative tasks.
+        for _ in 0..16 {
+            let filename = format!(
+                "part-{}-attempt-{}-{}.jsonl",
+                task.partition_id(),
+                task.task_attempt_id(),
+                unique_id()?
+            );
+            let path = self.staging.join(&filename);
+            match OpenOptions::new().write(true).create_new(true).open(&path) {
+                Ok(file) => {
+                    return Ok(Box::new(JsonTaskWriter {
+                        task,
+                        path,
+                        message: CommitMessage {
+                            operation: self.operation.clone(),
+                            filename,
+                            partition: task.partition_id(),
+                            rows: 0,
+                        },
+                        writer: Some(BufWriter::new(file)),
+                        committed: false,
+                    }));
+                }
+                Err(error) if error.kind() == ErrorKind::AlreadyExists => 
continue,
+                Err(error) => return Err(error.into()),
+            }
+        }
+        Err("Could not create a unique task attempt file".into())
+    }
+}
+
+#[derive(Serialize)]
+struct Row<'a> {
+    id: Option<i64>,
+    label: Option<&'a str>,
+}
+
+struct JsonTaskWriter<'task> {
+    task: TaskContext<'task>,
+    path: PathBuf,
+    message: CommitMessage,
+    writer: Option<BufWriter<File>>,
+    committed: bool,
+}
+
+impl JsonTaskWriter<'_> {
+    fn discard_buffer(&mut self) {
+        if let Some(writer) = self.writer.take() {
+            // BufWriter normally flushes on drop; abort discards buffered 
rows.
+            let (file, _) = writer.into_parts();
+            drop(file);
+        }
+    }
+}
+
+// Spark never writes after a failure, a commit, or an abort, and commits at 
most once, so this
+// writer does not track its phase. Abort may follow a commit whose message 
the SDK could not
+// serialize, so it removes the file in every case.
+impl DataWriter for JsonTaskWriter<'_> {
+    type Message = CommitMessage;
+
+    fn write(&mut self, batch: RecordBatch) -> Result<()> {
+        let writer = self.writer.as_mut().ok_or("The task writer is closed")?;
+        let ids = batch
+            .column(0)
+            .as_any()
+            .downcast_ref::<Int64Array>()
+            .ok_or("The id column must be an Arrow int64 array")?;
+        let labels = batch
+            .column(1)
+            .as_any()
+            .downcast_ref::<StringArray>()
+            .ok_or("The label column must be an Arrow utf8 array")?;
+        for index in 0..batch.num_rows() {
+            if index % 1024 == 0 && self.task.is_interrupted() {
+                return Err("Task cancelled while writing the sink".into());
+            }
+            let row = Row {
+                id: (!ids.is_null(index)).then(|| ids.value(index)),
+                label: (!labels.is_null(index)).then(|| labels.value(index)),
+            };
+            serde_json::to_writer(&mut *writer, &row)?;
+            writer.write_all(b"\n")?;
+        }
+        self.message.rows = self
+            .message
+            .rows
+            .checked_add(batch.num_rows() as u64)
+            .ok_or("Task row count overflow")?;
+        Ok(())
+    }
+
+    fn commit(&mut self) -> Result<Self::Message> {
+        if self.task.is_interrupted() {
+            return Err("Task cancelled before committing the sink".into());
+        }
+        let mut writer = self.writer.take().ok_or("The task writer is 
closed")?;
+        writer.flush()?;
+        writer.get_ref().sync_all()?;
+        drop(writer);
+        self.committed = true;
+        Ok(self.message.clone())
+    }
+
+    fn abort(&mut self) -> Result<()> {
+        self.discard_buffer();
+        match fs::remove_file(&self.path) {
+            Ok(()) => Ok(()),
+            Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
+            Err(error) => Err(error.into()),
+        }
+    }
+}
+
+impl Drop for JsonTaskWriter<'_> {
+    fn drop(&mut self) {
+        if !self.committed {
+            self.discard_buffer();
+            let _ = fs::remove_file(&self.path);
+        }
+    }
+}
+
+fn is_filename(name: &str) -> bool {
+    let mut components = Path::new(name).components();
+    matches!(components.next(), Some(Component::Normal(_))) && 
components.next().is_none()
+}
+
+fn unique_id() -> Result<String> {
+    Ok(format!(
+        "{}-{}-{}",
+        std::process::id(),
+        SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos(),
+        NEXT_ID.fetch_add(1, Ordering::Relaxed)
+    ))
+}
+
+fn unique_directory(parent: &Path) -> Result<PathBuf> {
+    for _ in 0..16 {
+        let path = parent.join(unique_id()?);
+        match fs::create_dir(&path) {
+            Ok(()) => return Ok(path),
+            Err(error) if error.kind() == ErrorKind::AlreadyExists => continue,
+            Err(error) => return Err(error.into()),
+        }
+    }
+    Err("Could not create a unique write operation directory".into())
+}
+
+#[cfg(test)]
+mod tests {
+    use std::sync::atomic::AtomicBool;
+
+    use super::*;
+
+    struct TempDirectory(PathBuf);
+
+    impl TempDirectory {
+        fn new() -> Self {
+            Self(unique_directory(&std::env::temp_dir()).unwrap())
+        }
+
+        fn source(&self) -> JsonSink {
+            JsonSink::new(info(&[("path", self.0.to_str().unwrap())])).unwrap()
+        }
+    }
+
+    impl Drop for TempDirectory {
+        fn drop(&mut self) {
+            let _ = fs::remove_dir_all(&self.0);
+        }
+    }
+
+    fn info(options: &[(&str, &str)]) -> CreateInfo {
+        let options = options
+            .iter()
+            .map(|(key, value)| (key.to_string(), value.to_string()))
+            .collect();
+        CreateInfo::new("rust_sdk_sink", options)
+    }
+
+    fn new_write(source: &JsonSink, mode: WriteMode) -> Result<(JsonWrite, 
JsonWriterFactory)> {
+        let write = source.new_write(WriteInfo::new(sink_schema(), mode))?;
+        let factory = write.new_writer_factory()?;
+        Ok((write, factory))
+    }
+
+    fn open(
+        factory: &JsonWriterFactory,
+        partition: i32,
+    ) -> PartitionWriter<'static, CommitMessage> {
+        let task = TaskContext::for_testing().with_partition_id(partition);
+        factory
+            .open(WriterContext::new(sink_schema(), task))
+            .unwrap()
+    }
+
+    fn batch(ids: Vec<Option<i64>>) -> RecordBatch {
+        let labels = ids
+            .iter()
+            .map(|id| id.map(|id| format!("row-{id}")))
+            .collect::<Vec<_>>();
+        RecordBatch::try_new(
+            sink_schema(),
+            vec![
+                Arc::new(Int64Array::from(ids)),
+                Arc::new(StringArray::from(labels)),
+            ],
+        )
+        .unwrap()
+    }
+
+    fn stage(factory: &JsonWriterFactory, partition: i32, ids: 
Vec<Option<i64>>) -> CommitMessage {
+        // Executors reconstruct the factory without the source or driver 
write.
+        let factory: JsonWriterFactory =
+            
serde_json::from_slice(&serde_json::to_vec(factory).unwrap()).unwrap();
+        let mut writer = open(&factory, partition);
+        writer.write(batch(ids)).unwrap();
+        let message = writer.commit().unwrap();
+        serde_json::from_slice(&serde_json::to_vec(&message).unwrap()).unwrap()
+    }
+
+    fn committed_rows(path: &Path) -> Vec<serde_json::Value> {
+        read_manifest(path)
+            .unwrap()
+            .files
+            .iter()
+            .flat_map(|file| {
+                let text = fs::read_to_string(path.join(&file.path)).unwrap();
+                let rows = text
+                    .lines()
+                    .map(|line| serde_json::from_str(line).unwrap())
+                    .collect::<Vec<_>>();
+                assert_eq!(rows.len() as u64, file.rows);
+                rows
+            })
+            .collect()
+    }
+
+    fn new_streaming_write(
+        source: &JsonSink,
+        query_id: &str,
+        mode: WriteMode,
+    ) -> Result<(JsonStreamingWrite, JsonWriterFactory)> {
+        let info = StreamingWriteInfo::new(sink_schema(), mode, query_id);
+        let write = source.new_streaming_write(info)?;
+        let factory = write.new_writer_factory()?;
+        Ok((write, factory))
+    }
+
+    fn commit_epoch(
+        source: &JsonSink,
+        query_id: &str,
+        mode: WriteMode,
+        epoch_id: i64,
+        ids: Vec<Option<i64>>,
+    ) {
+        let (mut write, factory) = new_streaming_write(source, query_id, 
mode).unwrap();
+        let message = stage(&factory, 0, ids);
+        write
+            .commit(StreamingCommitInfo::new(epoch_id, vec![message]))
+            .unwrap();
+    }
+
+    fn commit_ids(source: &JsonSink, mode: WriteMode, ids: Vec<Option<i64>>) {
+        let (mut write, factory) = new_write(source, mode).unwrap();
+        let message = stage(&factory, 0, ids);
+        write.commit(CommitInfo::new(vec![message])).unwrap();
+    }
+
+    #[test]
+    fn append_publishes_all_committed_rows_and_preserves_nulls() {
+        let directory = TempDirectory::new();
+        let source = directory.source();
+        commit_ids(&source, WriteMode::Append, vec![Some(1), None]);
+        commit_ids(&source, WriteMode::Append, vec![Some(2)]);
+        assert_eq!(
+            committed_rows(&directory.0),
+            vec![
+                serde_json::json!({"id": 1, "label": "row-1"}),
+                serde_json::json!({"id": null, "label": null}),
+                serde_json::json!({"id": 2, "label": "row-2"}),
+            ]
+        );
+        assert_eq!(read_manifest(&directory.0).unwrap().files.len(), 2);
+        assert!(!directory.0.join(".write-lock").exists());
+    }
+
+    #[test]
+    fn truncate_replaces_manifest_but_retains_previously_published_files() {
+        let directory = TempDirectory::new();
+        let source = directory.source();
+        commit_ids(&source, WriteMode::Append, vec![Some(1)]);
+        let previous = read_manifest(&directory.0).unwrap();
+        commit_ids(&source, WriteMode::Truncate, vec![Some(2)]);
+        assert_eq!(
+            committed_rows(&directory.0),
+            vec![serde_json::json!({"id": 2, "label": "row-2"})]
+        );
+        assert!(directory.0.join(&previous.files[0].path).is_file());
+        commit_ids(&source, WriteMode::Truncate, Vec::new());
+        assert!(committed_rows(&directory.0).is_empty());
+    }
+
+    #[test]
+    fn driver_publishes_only_winning_attempts_and_removes_unreported_files() {
+        let directory = TempDirectory::new();
+        let (mut write, factory) = new_write(&directory.source(), 
WriteMode::Append).unwrap();
+        let winning = stage(&factory, 0, vec![Some(1)]);
+        let _losing = stage(&factory, 0, vec![Some(2)]);
+        let _missing_message = stage(&factory, 1, vec![Some(3)]);
+        assert_eq!(fs::read_dir(&write.staging).unwrap().count(), 3);
+        write.commit(CommitInfo::new(vec![winning])).unwrap();
+        assert!(!write.staging.exists());
+        assert_eq!(fs::read_dir(&write.objects).unwrap().count(), 1);
+        assert_eq!(
+            committed_rows(&directory.0),
+            vec![serde_json::json!({"id": 1, "label": "row-1"})]
+        );
+        let task = TaskContext::for_testing();
+        assert!(factory
+            .open(WriterContext::new(sink_schema(), task))
+            .is_err());
+    }
+
+    #[test]
+    fn commit_rejects_a_message_at_the_position_of_another_partition() {
+        let directory = TempDirectory::new();
+        let (mut write, factory) = new_write(&directory.source(), 
WriteMode::Append).unwrap();
+        let message = stage(&factory, 1, vec![Some(1)]);
+        assert!(write.commit(CommitInfo::new(vec![message])).is_err());
+        assert!(!directory.0.join("manifest.json").exists());
+    }
+
+    #[test]
+    fn commit_rejects_invalid_messages_and_leaves_the_manifest_unchanged() {
+        let directory = TempDirectory::new();
+        let source = directory.source();
+        commit_ids(&source, WriteMode::Append, vec![Some(1)]);
+        let before = fs::read(directory.0.join("manifest.json")).unwrap();
+        let cases: [(fn(&JsonWrite, &mut [CommitMessage]), &str); 4] = [

Review Comment:
   Done in 79b167dd2a7: applied the suggestion. With Rust 1.85, the job's 
commands all pass locally on 75db9edae95: `cargo build`, `cargo test` (82 
tests), `cargo clippy` with `-D warnings`, `cargo fmt --check`, and `cargo doc` 
with `-D warnings`.
   



##########
sql/native/rust/src/abi.rs:
##########
@@ -0,0 +1,887 @@
+// 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.
+
+//! Bindings and adapters for version 1 of `spark_datasource.h`.
+
+use std::cell::RefCell;
+use std::ffi::{c_char, c_int, c_void, CStr, CString};
+use std::mem::{offset_of, size_of};
+use std::sync::Arc;
+
+pub use arrow_array::ffi::FFI_ArrowArray as ArrowArray;
+pub use arrow_array::ffi_stream::FFI_ArrowArrayStream as ArrowArrayStream;
+pub use arrow_schema::ffi::FFI_ArrowSchema as ArrowSchema;
+use arrow_schema::{Schema, SchemaRef};
+
+use crate::bridge::{c_message, provider_call};
+use crate::host::{self, LogEnabledFunction, LogFunction};
+use crate::{CreateInfo, HostInfo, LatestOffsetInfo, Options, ReadLimit, 
Result, WriteMode};
+
+pub const ABI_VERSION: i32 = 1;
+pub const BATCH_READ: u64 = 1;
+pub const MICRO_BATCH_READ: u64 = 2;
+pub const BATCH_WRITE: u64 = 4;
+pub const STREAMING_WRITE: u64 = 8;
+pub const BATCH_TRUNCATE: u64 = 16;
+pub const STREAMING_TRUNCATE: u64 = 32;
+pub const ADMISSION_CONTROL: u64 = 64;
+pub const READ_BATCH: i32 = 0;
+pub const READ_MICRO_BATCH: i32 = 1;
+pub const READ_ALL_AVAILABLE: i32 = 0;
+pub const READ_MAX_ROWS: i32 = 1;
+pub const WRITE_APPEND: i32 = 0;
+pub const WRITE_TRUNCATE: i32 = 1;
+pub const LOG_ERROR: i32 = 1;
+
+pub type SparkDsSink = Option<unsafe extern "C" fn(*mut c_void, *const u8, 
i64)>;
+pub type Interrupted = unsafe extern "C" fn(*const SparkDsTaskContext) -> bool;
+
+// What Spark passes to the library.
+
+#[repr(C)]
+pub struct SparkDsHost {
+    pub size: i64,
+    pub abi_version: i32,
+    pub spark_version: *const c_char,
+    pub log: Option<LogFunction>,
+    pub is_log_enabled: Option<LogEnabledFunction>,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsCreateInfo {
+    pub size: i64,
+    pub name: *const c_char,
+    pub option_keys: *const *const c_char,
+    pub option_values: *const *const c_char,
+    pub num_options: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsReaderInfo {
+    pub size: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsPartitionsInfo {
+    pub size: i64,
+}
+
+/// The domain of a column, which `push_domains` gets. The SDK binds it, so 
that the function
+/// table has the size of the header, but does not expose it yet (SPARK-61306).
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsDomain {
+    pub size: i64,
+    pub path: *const i32,
+    pub path_length: i64,
+    pub null_allowed: bool,
+    pub nan_allowed: bool,
+    pub ranges: *mut ArrowArray,
+    pub ranges_schema: *mut ArrowSchema,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsStreamReaderInfo {
+    pub size: i64,
+    pub checkpoint_location: *const c_char,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsInitialOffsetInfo {
+    pub size: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsReadLimit {
+    pub size: i64,
+    pub kind: i32,
+    pub max_rows: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsLatestOffsetInfo {
+    pub size: i64,
+    pub start: *const c_char,
+    pub limit: *const SparkDsReadLimit,
+    pub run_end: *const c_char,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsStreamPartitionsInfo {
+    pub size: i64,
+    pub start: *const c_char,
+    pub end: *const c_char,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsCommitOffsetInfo {
+    pub size: i64,
+    pub end: *const c_char,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsTaskContext {
+    pub size: i64,
+    pub stage_id: i32,
+    pub stage_attempt_number: i32,
+    pub partition_id: i32,
+    pub attempt_number: i32,
+    pub task_attempt_id: i64,
+    pub is_interrupted: Option<Interrupted>,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsReadInfo {
+    pub size: i64,
+    pub kind: i32,
+    pub schema: *mut ArrowSchema,
+    pub reader_state: *const u8,
+    pub reader_state_length: i64,
+    pub partition: *const u8,
+    pub partition_length: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsWriteInfo {
+    pub size: i64,
+    pub mode: i32,
+    pub query_id: *const c_char,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsDataWriterInfo {
+    pub size: i64,
+    pub schema: *mut ArrowSchema,
+    pub writer_state: *const u8,
+    pub writer_state_length: i64,
+    pub epoch_id: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsFinishWriteInfo {
+    pub size: i64,
+    pub epoch_id: i64,
+    pub messages: *const *const u8,
+    pub message_lengths: *const i64,
+    pub num_messages: i64,
+    pub rejected: i64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy)]
+pub struct SparkDsFinishDataWriterInfo {
+    pub size: i64,
+}
+
+// What the library returns to Spark.
+
+/// The complete version 1 table. Unsupported operations have null function 
slots.
+#[repr(C)]
+pub struct SparkDsLibrary {
+    pub size: i64,
+    pub abi_version: i32,
+    pub last_error: Option<unsafe extern "C" fn() -> *const c_char>,
+    pub create:
+        Option<unsafe extern "C" fn(*const SparkDsCreateInfo, *mut u64, *mut 
*mut c_void) -> c_int>,
+    pub schema: Option<unsafe extern "C" fn(*mut c_void, *mut ArrowSchema) -> 
c_int>,
+    pub create_reader: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *mut ArrowSchema,
+            *const SparkDsReaderInfo,
+            *mut *mut c_void,
+        ) -> c_int,
+    >,
+    pub create_stream_reader: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *mut ArrowSchema,
+            *const SparkDsStreamReaderInfo,
+            *mut *mut c_void,
+        ) -> c_int,
+    >,
+    pub create_writer: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *mut ArrowSchema,
+            *const SparkDsWriteInfo,
+            SparkDsSink,
+            *mut c_void,
+            *mut *mut c_void,
+        ) -> c_int,
+    >,
+    pub close: Option<unsafe extern "C" fn(*mut c_void)>,
+    pub push_limit: Option<unsafe extern "C" fn(*mut c_void, i32, *mut bool) 
-> c_int>,
+    pub prune_columns:
+        Option<unsafe extern "C" fn(*mut c_void, *const *const c_char, i64) -> 
c_int>,
+    pub partitions: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *const SparkDsPartitionsInfo,
+            SparkDsSink,
+            SparkDsSink,
+            *mut c_void,
+        ) -> c_int,
+    >,
+    pub close_reader: Option<unsafe extern "C" fn(*mut c_void)>,
+    pub initial_offset: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *const SparkDsInitialOffsetInfo,
+            SparkDsSink,
+            *mut c_void,
+        ) -> c_int,
+    >,
+    pub latest_offset: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *const SparkDsLatestOffsetInfo,
+            SparkDsSink,
+            *mut c_void,
+        ) -> c_int,
+    >,
+    pub stream_partitions: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *const SparkDsStreamPartitionsInfo,
+            SparkDsSink,
+            SparkDsSink,
+            *mut c_void,
+        ) -> c_int,
+    >,
+    pub commit_offset:
+        Option<unsafe extern "C" fn(*mut c_void, *const 
SparkDsCommitOffsetInfo) -> c_int>,
+    pub close_stream_reader: Option<unsafe extern "C" fn(*mut c_void)>,
+    pub read: Option<
+        unsafe extern "C" fn(
+            *const SparkDsTaskContext,
+            *const SparkDsReadInfo,
+            *mut ArrowArrayStream,
+        ) -> c_int,
+    >,
+    pub commit: Option<unsafe extern "C" fn(*mut c_void, *const 
SparkDsFinishWriteInfo) -> c_int>,
+    pub abort: Option<unsafe extern "C" fn(*mut c_void, *const 
SparkDsFinishWriteInfo) -> c_int>,
+    pub close_writer: Option<unsafe extern "C" fn(*mut c_void)>,
+    pub create_data_writer: Option<
+        unsafe extern "C" fn(
+            *const SparkDsTaskContext,
+            *const SparkDsDataWriterInfo,
+            *mut *mut c_void,
+        ) -> c_int,
+    >,
+    pub write: Option<unsafe extern "C" fn(*mut c_void, *mut ArrowArray) -> 
c_int>,
+    pub commit_data_writer: Option<
+        unsafe extern "C" fn(
+            *mut c_void,
+            *const SparkDsFinishDataWriterInfo,
+            SparkDsSink,
+            *mut c_void,
+        ) -> c_int,
+    >,
+    pub abort_data_writer:
+        Option<unsafe extern "C" fn(*mut c_void, *const 
SparkDsFinishDataWriterInfo) -> c_int>,
+    pub close_data_writer: Option<unsafe extern "C" fn(*mut c_void)>,
+    pub default_read_limit:
+        Option<unsafe extern "C" fn(*mut c_void, *mut SparkDsReadLimit) -> 
c_int>,
+    // Added to version 1 by SPARK-61200, after the other functions.
+    pub push_domains: Option<
+        unsafe extern "C" fn(*mut c_void, *const *const SparkDsDomain, i64, 
*mut bool) -> c_int,
+    >,
+}
+
+// The known sizes and field offsets on 64-bit targets, checked wherever the 
SDK builds.
+// Tests also compare the actual Rust layouts with the current C header, using 
this field list.
+macro_rules! layout {
+    ($($name:ident: $size:literal { $($field:ident: $offset:literal),* $(,)? 
})*) => {
+        #[cfg(target_pointer_width = "64")]
+        const _: () = {
+            $(
+                assert!(size_of::<$name>() == $size);
+                $(assert!(offset_of!($name, $field) == $offset);)*
+            )*
+        };
+
+        #[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
+        fn c_layout_assertions() -> String {
+            use std::fmt::Write;
+
+            let mut source =
+                String::from("#include <stddef.h>\n#include 
\"spark_datasource.h\"\n");
+            $(
+                writeln!(
+                    source,
+                    "_Static_assert(sizeof({0}) == {1}, \"{0}: size\");",
+                    stringify!($name),
+                    size_of::<$name>(),
+                ).unwrap();
+                writeln!(
+                    source,
+                    "_Static_assert(_Alignof({0}) == {1}, \"{0}: 
alignment\");",
+                    stringify!($name),
+                    std::mem::align_of::<$name>(),
+                ).unwrap();
+                $(
+                    writeln!(
+                        source,
+                        "_Static_assert(offsetof({0}, {1}) == {2}, \"{0}.{1}: 
offset\");",
+                        stringify!($name),
+                        stringify!($field),
+                        offset_of!($name, $field),
+                    ).unwrap();
+                )*
+            )*
+            source
+        }
+    };
+}
+
+layout! {
+    SparkDsHost: 40 { size: 0, abi_version: 8, spark_version: 16, log: 24, 
is_log_enabled: 32 }
+    SparkDsCreateInfo: 40 {
+        size: 0, name: 8, option_keys: 16, option_values: 24, num_options: 32,
+    }
+    SparkDsReaderInfo: 8 { size: 0 }
+    SparkDsPartitionsInfo: 8 { size: 0 }
+    SparkDsDomain: 48 {
+        size: 0, path: 8, path_length: 16, null_allowed: 24, nan_allowed: 25, 
ranges: 32,
+        ranges_schema: 40,
+    }
+    SparkDsStreamReaderInfo: 16 { size: 0, checkpoint_location: 8 }
+    SparkDsInitialOffsetInfo: 8 { size: 0 }
+    SparkDsReadLimit: 24 { size: 0, kind: 8, max_rows: 16 }
+    SparkDsLatestOffsetInfo: 32 { size: 0, start: 8, limit: 16, run_end: 24 }
+    SparkDsStreamPartitionsInfo: 24 { size: 0, start: 8, end: 16 }
+    SparkDsCommitOffsetInfo: 16 { size: 0, end: 8 }
+    SparkDsTaskContext: 40 {
+        size: 0, stage_id: 8, stage_attempt_number: 12, partition_id: 16, 
attempt_number: 20,
+        task_attempt_id: 24, is_interrupted: 32,
+    }
+    SparkDsReadInfo: 56 {
+        size: 0, kind: 8, schema: 16, reader_state: 24, reader_state_length: 
32, partition: 40,
+        partition_length: 48,
+    }
+    SparkDsWriteInfo: 24 { size: 0, mode: 8, query_id: 16 }
+    SparkDsDataWriterInfo: 40 {
+        size: 0, schema: 8, writer_state: 16, writer_state_length: 24, 
epoch_id: 32,
+    }
+    SparkDsFinishWriteInfo: 48 {
+        size: 0, epoch_id: 8, messages: 16, message_lengths: 24, num_messages: 
32, rejected: 40,
+    }
+    SparkDsFinishDataWriterInfo: 8 { size: 0 }
+    SparkDsLibrary: 232 {
+        size: 0, abi_version: 8, last_error: 16, create: 24, schema: 32, 
create_reader: 40,
+        create_stream_reader: 48, create_writer: 56, close: 64, push_limit: 72,
+        prune_columns: 80, partitions: 88, close_reader: 96, initial_offset: 
104,
+        latest_offset: 112, stream_partitions: 120, commit_offset: 128,
+        close_stream_reader: 136, read: 144, commit: 152, abort: 160, 
close_writer: 168,
+        create_data_writer: 176, write: 184, commit_data_writer: 192, 
abort_data_writer: 200,
+        close_data_writer: 208, default_read_limit: 216, push_domains: 224,
+    }
+}
+
+thread_local! {
+    static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
+}
+
+/// Converts provider failures and unwinding panics into the C error 
convention.
+pub fn call(action: impl FnOnce() -> Result<()>) -> c_int {
+    LAST_ERROR.with(|error| *error.borrow_mut() = None);
+    let Err(message) = provider_call(action) else {
+        return 0;
+    };
+    LAST_ERROR.with(|error| *error.borrow_mut() = Some(c_message(message)));
+    1
+}
+
+/// Returns the calling thread's error until its next adapter call.
+///
+/// # Safety
+/// The returned pointer must not be freed or used after another adapter call 
on this thread.
+pub unsafe extern "C" fn last_error() -> *const c_char {
+    LAST_ERROR.with(|error| {
+        error
+            .borrow()
+            .as_ref()
+            .map_or(std::ptr::null(), |message| message.as_ptr())
+    })
+}
+
+/// Reads only a field that fits in a sized C structure.
+///
+/// # Safety
+/// `pointer` must address `size` readable bytes, and `offset` must identify a 
field of type `T`.
+pub unsafe fn field<T: Copy>(pointer: *const u8, size: i64, offset: usize) -> 
Option<T> {
+    let end = offset.checked_add(size_of::<T>())?;
+    if usize::try_from(size).ok()? < end {
+        return None;
+    }
+    Some(unsafe { pointer.add(offset).cast::<T>().read_unaligned() })
+}
+
+/// # Safety
+/// A non-null pointer must address the size prefix of a live C structure.
+pub unsafe fn struct_size<T>(pointer: *const T) -> Result<i64> {
+    if pointer.is_null() {
+        return Err("null sized structure".into());
+    }
+    let size = unsafe { pointer.cast::<i64>().read_unaligned() };
+    if size < size_of::<i64>() as i64 {
+        return Err("structure is smaller than its size field".into());
+    }
+    Ok(size)
+}
+
+/// Copies a structure that Spark passes, which has every field of version 1 
of the ABI: fields
+/// are only appended to the structures, so a shorter one is an error, not 
partly read.
+///
+/// # Safety
+/// A non-null pointer must address a live structure whose first field is its 
size.
+pub unsafe fn input<T: Copy>(pointer: *const T) -> Result<T> {
+    let size = unsafe { struct_size(pointer)? };
+    if size < size_of::<T>() as i64 {

Review Comment:
   Done in 75db9edae95. Each of the 16 structures that Spark passes now has its 
size in 4.4.0 as its minimum, `Input::MIN_SIZE`. `input` copies only the bytes 
that Spark passes into a zeroed binding, so on an earlier 4.4.x a field 
appended later reads as zero (a null pointer, `None`, or 0), and `fill`, which 
`set_read_limit` now uses, sets only the bytes that fit. Every binding still 
has the fields of 4.4.0, so nothing changes today. On 64-bit targets a 
compile-time assertion pins the 4.4.0 sizes, so a binding that gains a field 
fails to build until its minimum is the offset of that field. A unit test reads 
and fills a structure that grew after 4.4.0 at the 4.4.0 size, at its own size 
and at a later one, and checks that a shorter one is rejected. The README now 
says that the SDK rejects structures shorter than in 4.4.0 and reads appended 
fields only when Spark passes them.
   



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