spark-test commented on code in PR #59520:
URL: https://github.com/apache/spark/pull/59520#discussion_r4506865937


##########
examples/src/main/rust/native-data-sink/src/lib.rs:
##########
@@ -0,0 +1,910 @@
+// 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_native_source::{
+    BatchWrite, Capabilities, CreateInfo, DataSource, DataWriter, 
DataWriterFactory,
+    PartitionWriter, Result, StreamingWrite, StreamingWriteInfo, TaskContext, 
Unsupported,
+    WriteInfo, WriteMode, WriterContext,
+};
+
+spark_native_source::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 of a streaming query among the options 
of its sink.
+        options.remove("checkpointlocation");

Review Comment:
   **Non-blocking (P2):** Only `checkpointlocation` is exempted here, but 
`DataStreamWriter.queryName(...)` also adds `queryName` to the options of the 
sink (DataStreamWriter.scala:81-82). `resolveSink` creates a native source with 
those options, keys lower-cased, when it checks 
`table.supports(STREAMING_WRITE)` during `start()` 
(DataStreamWriter.scala:293-312, ColumnarTable.scala:64-67). So 
`df.writeStream.format("rust_sdk_sink").queryName("events").option("checkpointLocation",
 c).start(path)` fails at start with `Unknown options: ["queryname"]`. On this 
path Spark adds no other key besides `path`, so exempting `queryname` here, and 
saying in the README that Spark passes both keys, covers it. Neither the sink's 
unit tests nor its smoke script name a query.
   
   **Verification:**
   - **Regression:** Creating the sink with the path, checkpointlocation and 
queryname options succeeds, while creating it with any other unknown option 
still fails.
   - **Inspection:** The sink's documentation of its options names both the 
query name and the checkpoint location as options that Spark adds for a 
streaming query.



##########
sql/native/rust/src/lib.rs:
##########
@@ -0,0 +1,772 @@
+// 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.
+
+//! Experimental SDK for native data sources in Rust, over version 1 of the C 
ABI of Spark,
+//! `spark_datasource.h`.
+//!
+//! Implement [`DataSource`], naming the types of the operations that it 
implements: a
+//! [`ScanBuilder`] for batch reads, a [`MicroBatchStream`] for micro-batch 
streaming reads, a
+//! [`BatchWrite`] for batch writes, and a [`StreamingWrite`] for streaming 
writes, or
+//! [`Unsupported`] for an operation that it does not implement. Then invoke
+//! [`export_data_source!`] once in a `cdylib` crate. The SDK
+//! owns handles, plan/message serialization, C ABI adaptation, and Arrow 
import/export.
+//! Rust traits stay inside the plugin; they are not an ABI between dynamic 
libraries.
+//!
+//! Methods receive their inputs in `#[non_exhaustive]` structs, so that new 
ABI fields
+//! can reach connectors without breaking them: `*Info` structs on the driver
+//! ([`CreateInfo`], [`ScanInfo`], [`MicroBatchStreamInfo`], 
[`LatestOffsetInfo`],
+//! [`WriteInfo`], [`StreamingWriteInfo`], and [`HostInfo`]), and `*Context` 
structs, which
+//! carry the live [`TaskContext`], on the executors ([`ReaderContext`] and 
[`WriterContext`]).
+
+use std::collections::BTreeMap;
+
+use arrow_array::RecordBatch;
+use arrow_schema::{ArrowError, SchemaRef};
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+
+mod abi;
+mod bridge;
+mod capabilities;
+mod export;
+mod host;
+mod task;
+mod unsupported;
+mod write;
+
+/// Implementation details of [`export_data_source!`] and of the SDK's own 
tests, not an API.
+#[doc(hidden)]
+pub mod __private {
+    pub use crate::bridge::Bridge;
+    pub use crate::export::{library, Exported};
+
+    pub mod abi {
+        pub use crate::abi::*;
+    }
+}
+
+/// The Arrow crate of [`RecordBatch`], which connectors can use to have the 
same version of
+/// Arrow as the SDK.
+pub use arrow_array;
+/// The Arrow crate of [`SchemaRef`] and [`ArrowError`], which connectors can 
use to have the
+/// same version of Arrow as the SDK.
+pub use arrow_schema;
+pub use capabilities::Capabilities;
+pub use host::HostInfo;
+/// The `log` crate, whose macros write to the log of the Spark driver or 
executor, with
+/// the path of the library, once Spark initializes the library.
+///
+/// Any thread can call them, including in the dependencies of the library. 
Outside
+/// Spark, for example in unit tests, their messages are dropped. The SDK sets 
the level of
+/// the `log` crate to that of the log of Spark, such as `Debug` when Spark 
logs debug
+/// messages, so the library does not set it.
+pub use log;
+pub use task::TaskContext;
+pub use unsupported::Unsupported;
+
+pub type Error = Box<dyn std::error::Error + Send + Sync>;
+pub type Result<T> = std::result::Result<T, Error>;
+pub type Options = BTreeMap<String, String>;
+
+// Data sources: Spark creates a DataSource for each operation, and its 
associated types
+// name the operations that the source implements.
+
+/// What Spark passes to create a data source.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct CreateInfo {
+    /// The name of the data source, as listed in the manifest of its package, 
or in
+    /// lower case for an installed library. A library that implements several 
data
+    /// sources, installed or listed under each of their names, can choose by 
this name.
+    pub name: String,
+    /// The options, with keys in lower case. A capability probe uses the 
options of the
+    /// table; an operation may override them with the options of its query.
+    pub options: Options,
+}
+
+impl CreateInfo {
+    /// The information of a source created outside Spark, for example in a 
test.
+    pub fn new(name: impl Into<String>, options: Options) -> Self {
+        Self {
+            name: name.into(),
+            options,
+        }
+    }
+}
+
+/// Driver-side source configuration, schema discovery, and the operations of 
a source.
+///
+/// The associated types name the operations that the source implements, and
+/// [`Unsupported`] stands for one that it does not implement:
+///
+/// ```rust,ignore
+/// impl DataSource for RangeSource {
+///     type ScanBuilder = RangeScan;
+///     type MicroBatchStream = RangeStream;
+///     type BatchWrite = Unsupported;
+///     type StreamingWrite = Unsupported;
+///     ...
+/// }
+/// ```
+///
+/// The SDK installs native callbacks and reports capabilities only for the 
implemented
+/// operations, and calls the `new_*` method of an operation only for them.
+///
+/// Spark creates a source for each schema inference, scan, stream, and write, 
including
+/// the write of each micro-batch, and may create one only to inspect its 
capabilities,
+/// then drop it. Keep construction lightweight. Scan builders, streams, and 
writes cannot
+/// borrow their source, which Spark drops first.
+pub trait DataSource: Send + Sized + 'static {
+    fn new(info: CreateInfo) -> Result<Self>;
+
+    /// Called once in each JVM when Spark loads the library, before it 
creates any
+    /// source. On failure, Spark does not use the library, and the error is 
logged.
+    fn init(_host: &HostInfo) -> Result<()> {
+        Ok(())
+    }
+
+    // Schema discovery.
+
+    /// Whether [`schema`](Self::schema) infers the schema of the data. When 
false, the
+    /// SDK leaves the native function unset: Spark then requires a 
user-specified
+    /// schema, reports its standard error without one, and never calls 
`schema`.
+    const INFERS_SCHEMA: bool = true;
+
+    /// Returns the schema of the data, when the user does not specify one.
+    fn schema(&self) -> Result<SchemaRef> {
+        Err(
+            "DataSource::schema is not implemented: implement it, or set \
+             DataSource::INFERS_SCHEMA to false to require a user-specified 
schema"
+                .into(),
+        )
+    }
+
+    // Batch reads.
+
+    /// The scan builder of batch reads, which [`new_scan`](Self::new_scan) 
creates, or
+    /// [`Unsupported`].
+    type ScanBuilder: ScanBuilder;
+
+    /// Creates an independent scan of [`ScanInfo::schema`], which the user 
may have
+    /// specified; reject unsupported schemas.
+    fn new_scan(&self, _info: ScanInfo) -> Result<Self::ScanBuilder> {
+        Err(
+            "DataSource::new_scan is not implemented: implement it, or set \
+             DataSource::ScanBuilder to Unsupported"
+                .into(),
+        )
+    }
+
+    // Micro-batch streaming reads.
+
+    /// The stream of micro-batch streaming reads, which
+    /// [`new_micro_batch_stream`](Self::new_micro_batch_stream) creates, or 
[`Unsupported`].
+    type MicroBatchStream: MicroBatchStream;
+
+    /// Creates the stream of a streaming query that reads the columns of
+    /// [`MicroBatchStreamInfo::schema`]; reject unsupported schemas.
+    fn new_micro_batch_stream(
+        &self,
+        _info: MicroBatchStreamInfo,
+    ) -> Result<Self::MicroBatchStream> {
+        Err(
+            "DataSource::new_micro_batch_stream is not implemented: implement 
it, or set \
+             DataSource::MicroBatchStream to Unsupported"
+                .into(),
+        )
+    }
+
+    // Batch writes.
+
+    /// The coordinator of batch writes, which [`new_write`](Self::new_write) 
creates, or
+    /// [`Unsupported`].
+    type BatchWrite: BatchWrite;
+
+    /// Validate the input schema and create an independent write. 
Construction may be
+    /// followed only by Drop, without commit or abort, so it must not make 
irreversible
+    /// changes. The SDK calls this only while the instance's capabilities 
include
+    /// `BATCH_WRITE`, and passes [`WriteMode::Truncate`] only when they 
include
+    /// `BATCH_TRUNCATE`, which the write declares with 
[`BatchWrite::SUPPORTS_TRUNCATE`].
+    fn new_write(&self, _info: WriteInfo) -> Result<Self::BatchWrite> {
+        Err(
+            "DataSource::new_write is not implemented: implement it, or set \
+             DataSource::BatchWrite to Unsupported"
+                .into(),
+        )
+    }
+
+    // Streaming writes.
+
+    /// The coordinator of the write of each micro-batch of a streaming query, 
which
+    /// [`new_streaming_write`](Self::new_streaming_write) creates, or 
[`Unsupported`].
+    type StreamingWrite: StreamingWrite;
+
+    /// Validate the input schema and create the write of a micro-batch. As 
with
+    /// [`new_write`](Self::new_write), construction may be followed only by 
Drop, so it must
+    /// not make irreversible changes. The SDK calls this only while the 
instance's
+    /// capabilities include `STREAMING_WRITE`, and passes 
[`WriteMode::Truncate`] only when
+    /// they include `STREAMING_TRUNCATE`, which the write declares with
+    /// [`StreamingWrite::SUPPORTS_TRUNCATE`].
+    fn new_streaming_write(&self, _info: StreamingWriteInfo) -> 
Result<Self::StreamingWrite> {
+        Err(
+            "DataSource::new_streaming_write is not implemented: implement it, 
or set \
+             DataSource::StreamingWrite to Unsupported"
+                .into(),
+        )
+    }
+
+    // Instance restrictions.
+
+    /// Returns the operations of this instance. The SDK keeps only those that 
the source
+    /// implements, so the default, [`Capabilities::all`], keeps them all. 
Override this to
+    /// restrict an instance, for example for a read-only destination. The SDK 
evaluates
+    /// it once when Spark creates the source. An instance without operations 
still
+    /// supports schema discovery.
+    fn capabilities(&self) -> Capabilities {
+        Capabilities::all()
+    }
+}
+
+// Batch reads: a ScanBuilder negotiates pushdown and plans the scan on the 
driver, and a
+// PartitionReaderFactory opens a reader of each partition on the executors.
+
+/// What Spark passes to create a scan.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct ScanInfo {
+    /// The schema to read: the schema of the source, or one that the user 
specified.
+    pub schema: SchemaRef,
+}
+
+impl ScanInfo {
+    /// The information of a scan created outside Spark, for example in a test.
+    pub fn new(schema: SchemaRef) -> Self {
+        Self { schema }
+    }
+}
+
+/// Negotiates pushdown on the driver, then plans the scan.
+///
+/// Spark calls [`push_limit`](Self::push_limit) and 
[`prune_columns`](Self::prune_columns),
+/// each at most once and in this order, then [`plan`](Self::plan), and drops 
the builder.
+/// After a call fails, it makes no other call. It drops a builder without 
planning it when it
+/// does not read the scan, for example to only explain a query. Only the 
serialized factory
+/// and partitions reach the executors.
+pub trait ScanBuilder: Send + Sized + 'static {
+    type Factory: PartitionReaderFactory;
+
+    /// False only for [`Unsupported`], from which the SDK derives the 
capabilities.
+    #[doc(hidden)]
+    const SUPPORTED: bool = true;
+
+    /// Count rows. Spark pushes a limit only when the query does not filter 
the rows, since
+    /// it filters them after reading.
+    fn push_limit(&mut self, _limit: usize) -> Result<LimitSupport> {
+        Ok(LimitSupport::Unsupported)
+    }
+
+    /// Tells the scan the top-level columns that the query needs, in order, 
so that it can
+    /// plan to read only them. There may be none, for example for `SELECT 
count(*)`: the
+    /// batches then only have a number of rows. Readers get these columns in
+    /// [`ReaderContext::schema`] whether or not the scan implements this 
method.
+    fn prune_columns(&mut self, _columns: &[String]) -> Result<()> {
+        Ok(())
+    }
+
+    fn plan(self) -> Result<ScanPlan<Self::Factory>>;
+}
+
+/// Whether a connector limits the rows produced by the whole scan.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum LimitSupport {
+    /// The scan may return more rows than the limit. A connector may still 
cap the
+    /// rows of each partition on its own: Spark applies its limit after 
reading.
+    Unsupported,
+    /// The whole scan returns at most the limit. Spark still applies its 
limit.
+    Global,
+}
+
+/// A driver-created plan containing only serializable values.
+///
+/// The SDK serializes the reader factory once and each partition 
independently.
+/// Include snapshot identifiers when needed for repeatable task attempts. Do 
not
+/// put pointers, open files, connections, or process-local resources here.
+#[non_exhaustive]
+pub struct ScanPlan<F: PartitionReaderFactory> {
+    pub factory: F,
+    pub partitions: Vec<F::Partition>,
+}
+
+impl<F: PartitionReaderFactory> ScanPlan<F> {
+    pub fn new(factory: F, partitions: Vec<F::Partition>) -> Self {
+        Self {
+            factory,
+            partitions,
+        }
+    }
+}
+
+/// Serializable configuration from which executors open partition readers.
+///
+/// The factory carries configuration or a snapshot descriptor; open 
connections and
+/// other live resources in [`open`](Self::open). Spark passes the schema to 
read with
+/// each partition, so the factory need not carry it.
+pub trait PartitionReaderFactory: Serialize + DeserializeOwned + Send + 
'static {
+    type Partition: Serialize + DeserializeOwned + Send + 'static;
+
+    /// Opens a lazy reader of the batches of `partition`, with the columns of
+    /// [`ReaderContext::schema`].
+    ///
+    /// - Return batches lazily, with bounded memory.
+    /// - The reader owns its resources and cannot borrow this short-lived 
factory. It
+    ///   may keep `context` until Spark releases the stream.
+    /// - Spark may call the reader on different threads, never concurrently, 
so it must
+    ///   be `Send` but not necessarily `Sync`.
+    /// - Check [`TaskContext::is_interrupted`] during long operations, and 
use timeouts
+    ///   for blocking I/O.
+    /// - Batches must own their buffers, because Spark may release the stream 
before
+    ///   its batches.
+    ///
+    /// The SDK checks Spark-compatible Arrow types, the schema to read and its
+    /// nullability, and zero array offsets recursively. It reports 
incompatible layouts
+    /// instead of copying buffers. A batch may have more columns than the 
schema to read,
+    /// such as all the columns of the source: the SDK keeps those of the 
schema, by name.
+    /// Batches may use any supported Arrow encoding of a Spark type, such as 
`LargeUtf8`
+    /// for a string, but the first batch determines the Arrow schema of the 
stream, which
+    /// every later batch must have.
+    fn open<'task>(
+        &self,
+        partition: Self::Partition,
+        context: ReaderContext<'task>,
+    ) -> Result<PartitionReader<'task>>;
+}
+
+/// What an executor reader receives with its partition.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct ReaderContext<'task> {
+    /// The schema to read: the columns that the scan reads, in order, which 
are those of
+    /// [`ScanBuilder::prune_columns`] for a batch scan, and of
+    /// [`MicroBatchStreamInfo::schema`] for a micro-batch.
+    pub schema: SchemaRef,
+    /// The task that reads the partition.
+    pub task: TaskContext<'task>,
+}
+
+impl<'task> ReaderContext<'task> {
+    /// The context of a reader opened outside Spark, for example in a test.
+    pub fn new(schema: SchemaRef, task: TaskContext<'task>) -> Self {
+        Self { schema, task }
+    }
+}
+
+/// The lazy batches of one partition, which [`PartitionReaderFactory::open`] 
returns.
+/// Any Arrow `RecordBatchReader`, such as a Parquet reader, is such an 
iterator.
+pub type PartitionReader<'task> =
+    Box<dyn Iterator<Item = std::result::Result<RecordBatch, ArrowError>> + 
Send + 'task>;
+
+// Micro-batch streaming reads: a MicroBatchStream finds new data and plans 
each micro-batch on
+// the driver, and the PartitionReaderFactory of each plan reads its 
partitions on the executors,
+// as in batch reads.
+
+/// What Spark passes to create the stream of a streaming query.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct MicroBatchStreamInfo {
+    /// The columns to read: those of the schema of the source, or of one that 
the user
+    /// specified, or only the top-level columns of it that the query needs. 
The readers of
+    /// the micro-batches get it in [`ReaderContext::schema`].
+    pub schema: SchemaRef,
+    /// A directory in the checkpoint of the query that is reserved for this 
source, such as
+    /// `file:/tmp/checkpoint/sources/0`, where the stream may keep what it 
needs to recover
+    /// from a failure. It stays the same when the query restarts. It is a 
fully qualified
+    /// Hadoop path, whose characters are not escaped as in a URI, on a file 
system that the
+    /// library may not be able to access, such as `s3a`. Spark keeps what it 
needs there under
+    /// the names that start with `_spark`, which the library must not use.
+    pub checkpoint_location: String,
+}
+
+impl MicroBatchStreamInfo {
+    /// The information of a stream created outside Spark, for example in a 
test.
+    pub fn new(schema: SchemaRef, checkpoint_location: impl Into<String>) -> 
Self {
+        Self {
+            schema,
+            checkpoint_location: checkpoint_location.into(),
+        }
+    }
+}
+
+/// Finds new data and plans the micro-batches of a streaming query, on the 
driver.
+///
+/// Spark creates a stream when a streaming query starts, or restarts from its 
checkpoint,
+/// and drops it when the query stops. For each micro-batch, it asks for the
+/// [`latest_offset`](Self::latest_offset), and when that differs from the end 
of the
+/// previous micro-batch, [`plan`](Self::plan)s the data in between. Only the 
serialized
+/// factory and partitions of each plan reach the executors, which read them 
as those of a
+/// batch scan.
+///
+/// # Offsets
+///
+/// Spark stores offsets in the checkpoint of the query, as the JSON of
+/// [`Offset`](Self::Offset), and compares them by that JSON, so serialize a 
position to the
+/// same JSON each time: for example, use structs and `BTreeMap` rather than 
`HashMap`. A
+/// restarted query passes the offsets of its checkpoint, which an earlier 
version of the
+/// library may have written, to `latest_offset`, `plan`, and `commit`. When 
that version had a
+/// different `Offset` type, the same position may encode to different JSON, 
so Spark runs one
+/// micro-batch without rows.
+///
+/// # Admission control
+///
+/// [`default_read_limit`](Self::default_read_limit) limits the data of each 
micro-batch,
+/// typically with an option of the source. Spark passes the limit to 
`latest_offset`, except
+/// when a micro-batch reads all the available data, as with `Trigger.Once`. 
With
+/// `Trigger.AvailableNow`, a run reads the data that was available when it 
started: with a
+/// limit, in several micro-batches, whose latest offsets must not go beyond
+/// [`LatestOffsetInfo::run_end`].
+///
+/// # Lifecycle
+///
+/// - Calls never run concurrently.
+/// - After a call fails, including with a panic, Spark makes no other call: 
it stops the
+///   query, and drops the stream.
+/// - After a restart, Spark may plan the last range of the query again, so 
`plan` must
+///   return partitions that read the same data for the same range.
+pub trait MicroBatchStream: Send + 'static {
+    /// A position in the data, such as the next record of each partition of a 
log.
+    type Offset: Serialize + DeserializeOwned;
+
+    /// The reader factory of the micro-batches, which can be that of batch 
scans.
+    type Factory: PartitionReaderFactory;
+
+    /// False only for [`Unsupported`], from which the SDK derives the 
capabilities.
+    #[doc(hidden)]
+    const SUPPORTED: bool = true;
+
+    /// Returns the offset to start from when the query has no checkpoint: the 
first
+    /// micro-batch reads the data after it. Spark keeps it in the checkpoint, 
and asks only
+    /// when the checkpoint does not have it yet, so a query that restarts 
before its first
+    /// micro-batch is committed starts from the same offset.
+    fn initial_offset(&mut self) -> Result<Self::Offset>;
+
+    /// Returns the limit on the data of each micro-batch. Spark asks once, 
when the query
+    /// starts. The default, [`ReadLimit::AllAvailable`], reads all the 
available data in
+    /// each micro-batch.
+    fn default_read_limit(&self) -> Result<ReadLimit> {
+        Ok(ReadLimit::AllAvailable)
+    }
+
+    /// Returns the end of the next micro-batch: the offset of the most recent 
data after
+    /// [`LatestOffsetInfo::start`], within its limit, and not beyond its end 
of the run.
+    /// Return `start` when there is no new data. When there is, return an 
offset after
+    /// `start`, even if the next unit of data, such as a file, is larger than 
the limit:
+    /// Spark sees no new data otherwise, and never reads further.
+    ///
+    /// With a limit, Spark also asks without a limit for some micro-batches, 
to report the
+    /// progress of the query, so do not count the calls as micro-batches, or 
reserve data in
+    /// them.
+    fn latest_offset(&mut self, info: LatestOffsetInfo<Self::Offset>) -> 
Result<Self::Offset>;
+
+    /// Plans the micro-batch that reads the data after `start`, up to and 
including `end`.
+    fn plan(&mut self, start: Self::Offset, end: Self::Offset) -> 
Result<ScanPlan<Self::Factory>>;
+
+    /// Tells the stream that Spark has processed the data up to and including 
`end` and
+    /// will not read it again, so that the stream can release it.
+    fn commit(&mut self, _end: Self::Offset) -> Result<()> {
+        Ok(())
+    }
+}
+
+/// A limit on the data of a micro-batch.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum ReadLimit {
+    /// All the available data.
+    AllAvailable,
+    /// At most this number of rows, at least 1.
+    MaxRows(u64),
+}
+
+/// What Spark passes to ask a stream for its latest offset.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct LatestOffsetInfo<O> {
+    /// The offset that the next micro-batch starts after: the end of the 
previous one, or
+    /// the initial offset.
+    pub start: O,
+    /// The limit on the data after `start`: that of
+    /// [`MicroBatchStream::default_read_limit`], or 
[`ReadLimit::AllAvailable`] when Spark
+    /// reads all the available data, such as for the progress of the query or 
with
+    /// `Trigger.Once`.
+    pub limit: ReadLimit,
+    /// With `Trigger.AvailableNow` and a limit, the end of the run: the 
latest offset must not
+    /// go beyond it, so that the run reads the data that was available when 
it started. It is
+    /// not the end of the next micro-batch. `None` otherwise.
+    pub run_end: Option<O>,
+}
+
+impl<O> LatestOffsetInfo<O> {
+    /// A request without a limit, made outside Spark, for example in a test. 
Set
+    /// [`limit`](Self::limit) and [`run_end`](Self::run_end) for other 
requests.
+    pub fn new(start: O) -> Self {
+        Self {
+            start,
+            limit: ReadLimit::AllAvailable,
+            run_end: None,
+        }
+    }
+}
+
+// Batch writes: a BatchWrite coordinates the write on the driver, and a 
DataWriterFactory
+// opens a DataWriter for each task attempt on the executors.
+
+/// What Spark passes to create a batch write.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct WriteInfo {
+    /// The schema of the data to write.
+    pub schema: SchemaRef,
+    /// How the write changes the destination.
+    pub mode: WriteMode,
+}
+
+impl WriteInfo {
+    /// The information of a write created outside Spark, for example in a 
test.
+    pub fn new(schema: SchemaRef, mode: WriteMode) -> Self {
+        Self { schema, mode }
+    }
+}
+
+/// How a batch write changes the destination.
+///
+/// New modes may be added. The SDK passes a mode only when the source instance
+/// has the matching capability, so a source never receives a mode it did not
+/// opt in to; a wildcard arm can return an error.
+#[derive(Debug, Clone, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum WriteMode {
+    Append,
+    /// Replace existing data at driver commit, never at writer creation.
+    Truncate,
+}
+
+/// A driver coordinator for one batch write, which also creates the 
serializable
+/// configuration of its task writers.
+///
+/// Keep irreversible publication, including removing overwritten data, in 
commit.
+/// Drop releases resources; it must not publish data or perform fallible 
flushing.
+///
+/// # Lifecycle
+///
+/// Spark calls the methods in this order, so implementations need not track 
their own
+/// phase or guard against repeated calls:
+///
+/// - `writer_factory` runs once, right after [`DataSource::new_write`], 
before any task
+///   opens a writer. When it fails, the SDK cannot serialize its factory, or 
Spark cannot
+///   copy the serialized factory, for example when it is too large, the write 
fails and
+///   the coordinator is dropped without `abort`, so Drop must also release 
what only this
+///   write staged.
+/// - `commit` runs at most once, when every task succeeded. The SDK fails the 
write
+///   without calling it when a task message cannot be decoded.
+/// - `abort` runs at most once, never after a successful `commit`. It follows 
a failed
+///   `commit`, or a failed task, also when computing the data to write failed.
+/// - Drop runs exactly once, possibly without `commit` or `abort`.
+/// - A panic in any method is reported as that method's failure.
+///
+/// Message `i` of `commit` and `abort` belongs to input partition `i`.
+pub trait BatchWrite: Send + 'static {
+    /// The configuration from which each task attempt opens its writer.
+    type Factory: DataWriterFactory<Message = Self::Message>;
+
+    /// The message with which a task attempt reports its staged output to the 
driver.
+    type Message: Serialize + DeserializeOwned + Send + 'static;
+
+    /// Whether the write supports [`WriteMode::Truncate`], for the save mode 
"overwrite",
+    /// which adds the `BATCH_TRUNCATE` capability.
+    const SUPPORTS_TRUNCATE: bool = false;
+
+    /// False only for [`Unsupported`], from which the SDK derives the 
capabilities.
+    #[doc(hidden)]
+    const SUPPORTED: bool = true;
+
+    /// Returns the configuration of the task writers, which the SDK 
serializes for them.
+    /// Include a unique operation ID when needed; Spark supplies no batch 
query ID.
+    fn writer_factory(&self) -> Result<Self::Factory>;
+
+    /// Publish only the winning attempt from each input partition. Task 
retries
+    /// and speculative attempts can stage other data that must not be 
published.
+    fn commit(&mut self, messages: Vec<Self::Message>) -> Result<()>;
+
+    /// Abort after input, task, or driver commit failure. None stands for a 
partition
+    /// whose commit message did not reach the driver, or cannot be decoded.
+    /// Executor loss can leave orphaned staged data; plan for its cleanup.
+    fn abort(&mut self, messages: Vec<Option<Self::Message>>) -> Result<()>;
+}
+
+/// Serializable configuration for independent task-attempt writers, which
+/// [`BatchWrite::writer_factory`] or [`StreamingWrite::writer_factory`] 
creates.
+///
+/// Open connections and files in open, not in the factory. A returned writer
+/// cannot borrow this temporary factory, but may retain the context until
+/// close. Callbacks can move between threads sequentially; writers must be 
Send.
+pub trait DataWriterFactory: Serialize + DeserializeOwned + Send + 'static {
+    type Message: Serialize + DeserializeOwned + Send + 'static;
+
+    fn open<'task>(
+        &self,
+        context: WriterContext<'task>,
+    ) -> Result<PartitionWriter<'task, Self::Message>>;
+}
+
+/// What a task writer receives when it opens.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct WriterContext<'task> {
+    /// The schema of the batches to write, as in [`WriteInfo::schema`].
+    pub schema: SchemaRef,
+    /// The task attempt that writes.
+    pub task: TaskContext<'task>,
+    /// The epoch of the micro-batch of a streaming write, or `None` for a 
batch write.
+    pub epoch_id: Option<i64>,
+}
+
+impl<'task> WriterContext<'task> {
+    /// The context of a batch writer opened outside Spark, for example in a 
test. Set
+    /// [`epoch_id`](Self::epoch_id) for a streaming writer.
+    pub fn new(schema: SchemaRef, task: TaskContext<'task>) -> Self {
+        Self {
+            schema,
+            task,
+            epoch_id: None,
+        }
+    }
+}
+
+/// One task attempt's writer. Spark drops it after commit or abort.
+///
+/// # Lifecycle
+///
+/// Spark calls the methods in this order, so implementations need not track 
their own
+/// phase or guard against repeated calls:
+///
+/// - `write` runs zero or more times, before `commit` or `abort`, and never 
after a
+///   call has failed.
+/// - `commit` runs at most once, never after a failed `write` or after 
`abort`.
+/// - `abort` runs at most once, never after a `commit` whose message reached 
Spark.
+///   It may follow a failed `write` or `commit`, including a `commit` that 
returned
+///   a message that the SDK could not serialize, so it must handle a task 
attempt
+///   that already finished its output.
+/// - Drop runs exactly once when Spark closes the writer, possibly without
+///   `commit` or `abort`.
+/// - The writer of a task attempt that Spark kills, such as a speculative 
one, may still
+///   write, abort, and drop after the driver committed or aborted the write.
+/// - A panic in any method is reported as that method's failure.
+pub trait DataWriter: Send {
+    type Message;
+
+    /// Takes ownership of an imported Arrow batch, which may be retained 
after this call,
+    /// but not after the writer is dropped: its buffers belong to the data 
writer of Spark,
+    /// and the ABI requires the library to release them before Spark closes 
the writer, so do
+    /// not pass the batch to a thread or a value that outlives the writer. 
Spark cannot free a
+    /// batch that is still retained when it closes the writer: it logs an 
error, and the memory
+    /// stays allocated until the batch is dropped. It has the schema of
+    /// [`WriterContext::schema`], and at most 
`spark.sql.execution.arrow.maxRecordsPerBatch`
+    /// rows. When Spark writes the batches of a native scan without 
converting them to rows,
+    /// it copies their values as the scan returned them, without the checks 
of a conversion,
+    /// such as the precision of a decimal. Process batches incrementally and 
check task
+    /// cancellation.
+    fn write(&mut self, batch: RecordBatch) -> Result<()>;
+
+    /// Finish staging and return a typed message for the driver. Do not make 
the
+    /// whole write visible here. On failure (including message serialization),
+    /// the SDK keeps this writer available for abort.
+    fn commit(&mut self) -> Result<Self::Message>;
+
+    fn abort(&mut self) -> Result<()>;
+}
+
+/// The writer of one task attempt, which [`DataWriterFactory::open`] returns.
+pub type PartitionWriter<'task, M> = Box<dyn DataWriter<Message = M> + 'task>;
+
+// Streaming writes: a StreamingWrite coordinates the write of one micro-batch 
on the driver,
+// and its DataWriterFactory opens a DataWriter for each task attempt on the 
executors, as in
+// batch writes.
+
+/// What Spark passes to create the write of a micro-batch.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct StreamingWriteInfo {
+    /// The schema of the data to write.
+    pub schema: SchemaRef,
+    /// How the micro-batch changes the destination: [`WriteMode::Truncate`] 
for the output
+    /// mode "complete", which replaces the output of the previous 
micro-batches.
+    pub mode: WriteMode,
+    /// The ID of the streaming query, which stays the same when the query 
restarts from
+    /// its checkpoint.
+    pub query_id: String,
+}
+
+impl StreamingWriteInfo {
+    /// The information of a write created outside Spark, for example in a 
test.
+    pub fn new(schema: SchemaRef, mode: WriteMode, query_id: impl 
Into<String>) -> Self {
+        Self {
+            schema,
+            mode,
+            query_id: query_id.into(),
+        }
+    }
+}
+
+/// A driver coordinator for the write of one micro-batch, or epoch, of a 
streaming query,
+/// which also creates the serializable configuration of its task writers.
+///
+/// Spark creates a write for each micro-batch, with the lifecycle of a 
[`BatchWrite`], and

Review Comment:
   **Non-blocking (P2):** This gives a `StreamingWrite` the lifecycle of a 
`BatchWrite`, whose docs present `Drop` as where a write releases its 
resources, but for streaming writes the coordinator is dropped later than that 
implies. `DriverWriter` keeps it until Spark closes the writer handle. The JVM 
closes a stream writer only in `NativeStreamWriters.register`, after 
`streamWriter` has created the next micro-batch's native writer 
(NativeDataSource.scala:156-168, 1409-1414), and it closes the last writer of a 
query only when the JVM collects it (spark_datasource.h:121-124). So a 
coordinator that takes an exclusive lease or lock in `new_streaming_write` and 
releases it in `Drop` still holds it when micro-batch 1 calls 
`new_streaming_write`. The acquisition then fails, or blocks forever, because 
`register` runs on the same thread only after the creation returns. An 
unplanned `ScanBuilder` is likewise dropped only once its reader is 
unreferenced, possibly on another thread, which its d
 ocs do not say. The example sink avoids this only because it releases its 
`.write-lock` in commit, skip and abort.
   
   This extends an [existing 
discussion](https://github.com/apache/spark/pull/59520#issuecomment-6694663098).
   
   **Recommended change:** Drop the connector's write coordinator as soon as 
its commit succeeds or its abort returns, instead of when Spark closes the 
writer handle. In the docs of BatchWrite, StreamingWrite and ScanBuilder and in 
the README, document that the coordinator is dropped right after a successful 
commit or an abort, and that a write that Spark neither commits nor aborts, and 
a scan builder that Spark never plans, can be dropped late and on another 
thread. Cover when coordinators are dropped in the SDK's batch write and 
streaming ABI tests.
   
   **Why this works:** After a successful commit, or after any abort, the C 
header guarantees that Spark calls nothing but close on the writer. So taking 
the coordinator out of the driver writer at that point and dropping it under 
the SDK's panic guard runs the connector's Drop before Spark creates the next 
micro-batch's writer, whatever order Spark closes handles in. A failed commit 
keeps the coordinator, because Spark aborts it next.
   
   **Scope:** The SDK's driver writer adapter and its lifecycle documentation, 
with ABI tests for when coordinators are dropped.
   
   **Compatibility:** A failed commit keeps the coordinator for the abort that 
follows, and the coordinator of a write whose creation Spark rejected, or that 
Spark neither commits nor aborts, is still dropped when Spark closes the writer.
   
   **Risks:** A connector's Drop now runs inside the successful commit or the 
abort, on the thread of that call, instead of when Spark closes the writer, so 
a connector that relied on keeping its coordinator alive until close would 
release it earlier.
   
   **Constraints:** Keep the coordinator after a failed commit, because Spark 
aborts it next, and keep dropping it under the panic guard, so that a panicking 
Drop is logged without changing the result of the commit or the abort and 
without crossing the C interface.
   
   **Exclusions:**
   - Changing when the JVM closes stream writers.
   - Dropping, before close, a write that Spark neither commits nor aborts, or 
a scan builder that Spark never plans; their late drop is documented instead.
   
   **Success:** After a successful commit, or after the abort of a write that 
failed, the connector's write coordinator has been dropped before the call 
returns. Creating the next micro-batch's write no longer overlaps with the 
previous micro-batch's coordinator, even while the previous writer handle is 
still open. The lifecycle docs state when coordinators are dropped, and that a 
write that Spark neither commits nor aborts, and a scan builder that Spark 
never plans, can be dropped late and on another thread.
   
   **Verification:**
   - **Regression:** A streaming write whose coordinator holds an exclusive 
resource from its creation until Drop can create the next micro-batch's write 
after the previous micro-batch commits, and after it aborts, while the previous 
writer handle is still open.
   - **Behavior:** A coordinator whose Drop panics right after a successful 
commit or an abort leaves the result of that call unchanged, and the panic is 
logged instead of crossing the C interface.
   - **Compatibility:** After a failed commit, the abort that follows still 
reaches the same coordinator, and closing the writer after a commit or an abort 
remains harmless for both batch and streaming writes.
   - **Inspection:** The SDK's documentation of batch writes, streaming writes 
and scan builders states when coordinators and builders are dropped, including 
that some drops happen late and on another thread.



##########
sql/native/rust/src/lib.rs:
##########
@@ -0,0 +1,772 @@
+// 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.
+
+//! Experimental SDK for native data sources in Rust, over version 1 of the C 
ABI of Spark,
+//! `spark_datasource.h`.
+//!
+//! Implement [`DataSource`], naming the types of the operations that it 
implements: a
+//! [`ScanBuilder`] for batch reads, a [`MicroBatchStream`] for micro-batch 
streaming reads, a
+//! [`BatchWrite`] for batch writes, and a [`StreamingWrite`] for streaming 
writes, or
+//! [`Unsupported`] for an operation that it does not implement. Then invoke
+//! [`export_data_source!`] once in a `cdylib` crate. The SDK
+//! owns handles, plan/message serialization, C ABI adaptation, and Arrow 
import/export.
+//! Rust traits stay inside the plugin; they are not an ABI between dynamic 
libraries.
+//!
+//! Methods receive their inputs in `#[non_exhaustive]` structs, so that new 
ABI fields
+//! can reach connectors without breaking them: `*Info` structs on the driver
+//! ([`CreateInfo`], [`ScanInfo`], [`MicroBatchStreamInfo`], 
[`LatestOffsetInfo`],
+//! [`WriteInfo`], [`StreamingWriteInfo`], and [`HostInfo`]), and `*Context` 
structs, which
+//! carry the live [`TaskContext`], on the executors ([`ReaderContext`] and 
[`WriterContext`]).
+
+use std::collections::BTreeMap;
+
+use arrow_array::RecordBatch;
+use arrow_schema::{ArrowError, SchemaRef};
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+
+mod abi;
+mod bridge;
+mod capabilities;
+mod export;
+mod host;
+mod task;
+mod unsupported;
+mod write;
+
+/// Implementation details of [`export_data_source!`] and of the SDK's own 
tests, not an API.
+#[doc(hidden)]
+pub mod __private {
+    pub use crate::bridge::Bridge;
+    pub use crate::export::{library, Exported};
+
+    pub mod abi {
+        pub use crate::abi::*;
+    }
+}
+
+/// The Arrow crate of [`RecordBatch`], which connectors can use to have the 
same version of
+/// Arrow as the SDK.
+pub use arrow_array;
+/// The Arrow crate of [`SchemaRef`] and [`ArrowError`], which connectors can 
use to have the
+/// same version of Arrow as the SDK.
+pub use arrow_schema;
+pub use capabilities::Capabilities;
+pub use host::HostInfo;
+/// The `log` crate, whose macros write to the log of the Spark driver or 
executor, with
+/// the path of the library, once Spark initializes the library.
+///
+/// Any thread can call them, including in the dependencies of the library. 
Outside
+/// Spark, for example in unit tests, their messages are dropped. The SDK sets 
the level of
+/// the `log` crate to that of the log of Spark, such as `Debug` when Spark 
logs debug
+/// messages, so the library does not set it.
+pub use log;
+pub use task::TaskContext;
+pub use unsupported::Unsupported;
+
+pub type Error = Box<dyn std::error::Error + Send + Sync>;
+pub type Result<T> = std::result::Result<T, Error>;
+pub type Options = BTreeMap<String, String>;
+
+// Data sources: Spark creates a DataSource for each operation, and its 
associated types
+// name the operations that the source implements.
+
+/// What Spark passes to create a data source.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct CreateInfo {
+    /// The name of the data source, as listed in the manifest of its package, 
or in
+    /// lower case for an installed library. A library that implements several 
data
+    /// sources, installed or listed under each of their names, can choose by 
this name.
+    pub name: String,
+    /// The options, with keys in lower case. A capability probe uses the 
options of the
+    /// table; an operation may override them with the options of its query.
+    pub options: Options,
+}
+
+impl CreateInfo {
+    /// The information of a source created outside Spark, for example in a 
test.
+    pub fn new(name: impl Into<String>, options: Options) -> Self {
+        Self {
+            name: name.into(),
+            options,
+        }
+    }
+}
+
+/// Driver-side source configuration, schema discovery, and the operations of 
a source.
+///
+/// The associated types name the operations that the source implements, and
+/// [`Unsupported`] stands for one that it does not implement:
+///
+/// ```rust,ignore
+/// impl DataSource for RangeSource {
+///     type ScanBuilder = RangeScan;
+///     type MicroBatchStream = RangeStream;
+///     type BatchWrite = Unsupported;
+///     type StreamingWrite = Unsupported;
+///     ...
+/// }
+/// ```
+///
+/// The SDK installs native callbacks and reports capabilities only for the 
implemented
+/// operations, and calls the `new_*` method of an operation only for them.
+///
+/// Spark creates a source for each schema inference, scan, stream, and write, 
including
+/// the write of each micro-batch, and may create one only to inspect its 
capabilities,
+/// then drop it. Keep construction lightweight. Scan builders, streams, and 
writes cannot
+/// borrow their source, which Spark drops first.
+pub trait DataSource: Send + Sized + 'static {
+    fn new(info: CreateInfo) -> Result<Self>;
+
+    /// Called once in each JVM when Spark loads the library, before it 
creates any
+    /// source. On failure, Spark does not use the library, and the error is 
logged.
+    fn init(_host: &HostInfo) -> Result<()> {
+        Ok(())
+    }
+
+    // Schema discovery.
+
+    /// Whether [`schema`](Self::schema) infers the schema of the data. When 
false, the
+    /// SDK leaves the native function unset: Spark then requires a 
user-specified
+    /// schema, reports its standard error without one, and never calls 
`schema`.
+    const INFERS_SCHEMA: bool = true;
+
+    /// Returns the schema of the data, when the user does not specify one.
+    fn schema(&self) -> Result<SchemaRef> {
+        Err(
+            "DataSource::schema is not implemented: implement it, or set \
+             DataSource::INFERS_SCHEMA to false to require a user-specified 
schema"
+                .into(),
+        )
+    }
+
+    // Batch reads.
+
+    /// The scan builder of batch reads, which [`new_scan`](Self::new_scan) 
creates, or
+    /// [`Unsupported`].
+    type ScanBuilder: ScanBuilder;
+
+    /// Creates an independent scan of [`ScanInfo::schema`], which the user 
may have
+    /// specified; reject unsupported schemas.
+    fn new_scan(&self, _info: ScanInfo) -> Result<Self::ScanBuilder> {
+        Err(
+            "DataSource::new_scan is not implemented: implement it, or set \
+             DataSource::ScanBuilder to Unsupported"
+                .into(),
+        )
+    }
+
+    // Micro-batch streaming reads.
+
+    /// The stream of micro-batch streaming reads, which
+    /// [`new_micro_batch_stream`](Self::new_micro_batch_stream) creates, or 
[`Unsupported`].
+    type MicroBatchStream: MicroBatchStream;
+
+    /// Creates the stream of a streaming query that reads the columns of
+    /// [`MicroBatchStreamInfo::schema`]; reject unsupported schemas.
+    fn new_micro_batch_stream(
+        &self,
+        _info: MicroBatchStreamInfo,
+    ) -> Result<Self::MicroBatchStream> {
+        Err(
+            "DataSource::new_micro_batch_stream is not implemented: implement 
it, or set \
+             DataSource::MicroBatchStream to Unsupported"
+                .into(),
+        )
+    }
+
+    // Batch writes.
+
+    /// The coordinator of batch writes, which [`new_write`](Self::new_write) 
creates, or
+    /// [`Unsupported`].
+    type BatchWrite: BatchWrite;
+
+    /// Validate the input schema and create an independent write. 
Construction may be
+    /// followed only by Drop, without commit or abort, so it must not make 
irreversible
+    /// changes. The SDK calls this only while the instance's capabilities 
include
+    /// `BATCH_WRITE`, and passes [`WriteMode::Truncate`] only when they 
include
+    /// `BATCH_TRUNCATE`, which the write declares with 
[`BatchWrite::SUPPORTS_TRUNCATE`].
+    fn new_write(&self, _info: WriteInfo) -> Result<Self::BatchWrite> {
+        Err(
+            "DataSource::new_write is not implemented: implement it, or set \
+             DataSource::BatchWrite to Unsupported"
+                .into(),
+        )
+    }
+
+    // Streaming writes.
+
+    /// The coordinator of the write of each micro-batch of a streaming query, 
which
+    /// [`new_streaming_write`](Self::new_streaming_write) creates, or 
[`Unsupported`].
+    type StreamingWrite: StreamingWrite;
+
+    /// Validate the input schema and create the write of a micro-batch. As 
with
+    /// [`new_write`](Self::new_write), construction may be followed only by 
Drop, so it must
+    /// not make irreversible changes. The SDK calls this only while the 
instance's
+    /// capabilities include `STREAMING_WRITE`, and passes 
[`WriteMode::Truncate`] only when
+    /// they include `STREAMING_TRUNCATE`, which the write declares with
+    /// [`StreamingWrite::SUPPORTS_TRUNCATE`].
+    fn new_streaming_write(&self, _info: StreamingWriteInfo) -> 
Result<Self::StreamingWrite> {
+        Err(
+            "DataSource::new_streaming_write is not implemented: implement it, 
or set \
+             DataSource::StreamingWrite to Unsupported"
+                .into(),
+        )
+    }
+
+    // Instance restrictions.
+
+    /// Returns the operations of this instance. The SDK keeps only those that 
the source
+    /// implements, so the default, [`Capabilities::all`], keeps them all. 
Override this to
+    /// restrict an instance, for example for a read-only destination. The SDK 
evaluates
+    /// it once when Spark creates the source. An instance without operations 
still
+    /// supports schema discovery.
+    fn capabilities(&self) -> Capabilities {
+        Capabilities::all()
+    }
+}
+
+// Batch reads: a ScanBuilder negotiates pushdown and plans the scan on the 
driver, and a
+// PartitionReaderFactory opens a reader of each partition on the executors.
+
+/// What Spark passes to create a scan.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct ScanInfo {
+    /// The schema to read: the schema of the source, or one that the user 
specified.
+    pub schema: SchemaRef,
+}
+
+impl ScanInfo {
+    /// The information of a scan created outside Spark, for example in a test.
+    pub fn new(schema: SchemaRef) -> Self {
+        Self { schema }
+    }
+}
+
+/// Negotiates pushdown on the driver, then plans the scan.
+///
+/// Spark calls [`push_limit`](Self::push_limit) and 
[`prune_columns`](Self::prune_columns),
+/// each at most once and in this order, then [`plan`](Self::plan), and drops 
the builder.
+/// After a call fails, it makes no other call. It drops a builder without 
planning it when it
+/// does not read the scan, for example to only explain a query. Only the 
serialized factory
+/// and partitions reach the executors.
+pub trait ScanBuilder: Send + Sized + 'static {
+    type Factory: PartitionReaderFactory;
+
+    /// False only for [`Unsupported`], from which the SDK derives the 
capabilities.
+    #[doc(hidden)]
+    const SUPPORTED: bool = true;
+
+    /// Count rows. Spark pushes a limit only when the query does not filter 
the rows, since

Review Comment:
   **Nit (P3):** Rustdoc shows "Count rows." as the summary of `push_limit`, 
but it says neither what Spark passes nor what the result promises. The header 
describes the function as "Pushes a LIMIT down to the reader", whose result 
says whether the reader returns at most `limit` rows in total 
(spark_datasource.h:696-703). A summary such as "Pushes a LIMIT of `limit` rows 
down to the scan; return `LimitSupport::Global` only if the whole scan returns 
at most `limit` rows." would state that contract.
   
   **Verification:**
   - **Inspection:** The rendered summary of push_limit describes its input and 
return values consistently with the documentation of LimitSupport and with the 
header's description of push_limit.



##########
sql/native/rust/src/stream.rs:
##########
@@ -0,0 +1,844 @@
+// 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::{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 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 = project(batch?, &self.expected)?;
+        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_nulls(column, field, field.name(), None)?;
+        }
+        Ok(Some(data))
+    }
+}
+
+/// 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(),
+    }
+}
+
+/// 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.
+fn project(batch: RecordBatch, expected: &Schema) -> Result<RecordBatch> {
+    let schema = batch.schema();
+    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(batch);
+    }
+    let indices =
+        wanted
+            .iter()
+            .map(|name| {
+                actual.iter().position(|actual| actual == name).ok_or_else(|| {

Review Comment:
   **Nit (P3):** For a reader that returns more columns than the schema to 
read, which the README endorses for scans without `prune_columns`, every batch 
repeats this linear search for each wanted column, after cloning every name of 
both schemas into new vectors (stream.rs:92-95). With 1000 returned columns and 
500 to read, that is up to 500,000 string comparisons per batch, for a mapping 
that depends only on the two schemas, which stay fixed after the first batch. 
Caching the indices per batch schema, or resolving the names once through a 
first-match map, keeps the same projection, order and errors.
   
   **Verification:**
   - **Behavior:** Batches with extra, reordered or exactly matching columns 
project to the schema to read as before, and a batch without a column of the 
schema to read fails with the same message.
   - **Inspection:** A stream whose batches share one schema resolves the 
column names once instead of on every batch.



##########
sql/native/rust/src/stream.rs:
##########
@@ -0,0 +1,844 @@
+// 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::{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 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 = project(batch?, &self.expected)?;
+        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_nulls(column, field, field.name(), None)?;
+        }
+        Ok(Some(data))
+    }
+}
+
+/// 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(),
+    }
+}
+
+/// 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.
+fn project(batch: RecordBatch, expected: &Schema) -> Result<RecordBatch> {
+    let schema = batch.schema();
+    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(batch);
+    }
+    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(batch.project(&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<'task>(
+    reader: PartitionReader<'task>,
+    expected_schema: &SchemaRef,
+) -> FFI_ArrowArrayStream {
+    let state = Box::new(StreamState {
+        reader: Some(reader),
+        expected: expected_schema.clone(),
+        schema: 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 {
+    let Err(message) = provider_call(|| action(state)) else {
+        return 0;
+    };
+    state.finished = true;
+    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.
+pub(crate) fn validate_schema(schema: &SchemaRef) -> Result<()> {
+    canonical_fields(schema.fields())?;
+    Ok(())
+}
+
+pub(crate) fn canonical_fields(fields: &Fields) -> Result<Fields> {
+    fields
+        .iter()
+        .map(|field| {
+            Ok(Arc::new(Field::new(
+                field.name(),
+                canonical_type(field.data_type())?,
+                false,
+            )))
+        })
+        .collect()
+}
+
+fn canonical_type(data_type: &DataType) -> Result<DataType> {
+    use DataType::*;
+    Ok(match data_type {
+        Boolean | Int8 | Int16 | Int32 | Int64 | Float32 | Float64 | Date32 => 
data_type.clone(),
+        Utf8 | LargeUtf8 | Utf8View => Utf8,
+        Binary | LargeBinary | BinaryView => Binary,
+        Decimal128(precision, _) if *precision > 0 && *precision <= 38 => 
data_type.clone(),
+        Timestamp(TimeUnit::Microsecond, tz) => {
+            Timestamp(TimeUnit::Microsecond, tz.as_ref().map(|_| "UTC".into()))
+        }
+        Struct(fields) => Struct(canonical_fields(fields)?),
+        List(field) => List(Arc::new(Field::new(
+            "item",
+            canonical_type(field.data_type())?,
+            false,
+        ))),
+        Map(entries, _) => {
+            let Struct(fields) = entries.data_type() else {
+                return Err("Arrow map entries must be a struct".into());
+            };
+            if fields.len() != 2 {
+                return Err("Arrow map entries must have a key and a 
value".into());
+            }
+            let entries = Struct(
+                vec![
+                    Field::new("key", canonical_type(fields[0].data_type())?, 
false),
+                    Field::new("value", 
canonical_type(fields[1].data_type())?, false),
+                ]
+                .into(),
+            );
+            Map(Arc::new(Field::new("entries", entries, false)), false)
+        }
+        _ => return Err(format!("unsupported Spark Arrow type: 
{data_type}").into()),
+    })
+}
+
+/// Rejects a null where the schema to read declares a column, a field, an 
element,
+/// or a map value not nullable, unless its parent is null, as Spark does 
after reading.
+/// `referenced` tells which values belong to a parent value that is not null.
+fn check_nulls(
+    data: &ArrayData,
+    field: &Field,
+    column: &str,
+    referenced: Option<&[bool]>,
+) -> Result<()> {
+    let is_referenced = |index: usize| referenced.is_none_or(|mask| 
mask[index]);
+    if !field.is_nullable()
+        && data.null_count() > 0
+        && (0..data.len()).any(|index| data.is_null(index) && 
is_referenced(index))
+    {
+        return Err(format!(
+            "The column {column} has a null, but the schema to read declares 
it not nullable"
+        )
+        .into());
+    }
+    let valid = |index: usize| data.is_valid(index) && is_referenced(index);
+    match field.data_type() {
+        DataType::Struct(fields) => {
+            let mask: Vec<bool> = (0..data.len()).map(valid).collect();

Review Comment:
   **Nit (P3):** This mask, and the element masks of lists and maps below it, 
are built for every nested column of every batch, but they are read only when a 
non-nullable field under them has nulls. For nested schemas whose fields are 
all nullable, as Spark infers them, every batch pays O(rows plus nested values) 
of allocation and traversal that can never produce an error. On the default 
reader path that comes on top of Spark's own per-batch check, which evaluates 
the same rule lazily (NativeDataSource.scala:732-782). Skipping a subtree that 
has no non-nullable field (map keys always count as one), or no nulls under 
one, and building a parent mask only when a child needs it, keeps every result 
and error message.
   
   **Verification:**
   - **Behavior:** Nested nullability violations in struct fields, list 
elements, map keys and map values still fail with the same messages, and nulls 
under null parents still pass.
   - **Inspection:** For a schema to read whose nested fields are all nullable, 
the check allocates no per-value mask.



##########
sql/native/rust/README.md:
##########
@@ -0,0 +1,478 @@
+<!--
+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.
+-->
+
+# Rust native data source SDK prototype
+
+This experimental SDK implements **batch and micro-batch streaming reads, with 
admission
+control, and batch and streaming writes** over version 1 of the C ABI of 
native data sources,
+[`spark_datasource.h`][header], which Spark 4.4.0 introduces. Spark calls the 
library through
+the Java Foreign Function and Memory (FFM) API, so running a library in Spark 
requires Java 22
+or newer on the driver and executors. The [guide of native data 
sources][guide] describes the
+ABI.
+
+The Rust and C tests run independently of Spark and Java. The workspace is not
+part of Maven/SBT and introduces no Rust requirement for building Spark. This 
is
+an API prototype, not a published crate or a compatibility commitment.
+
+The API uses the types of Arrow 58, such as `RecordBatch`, `SchemaRef`, and 
`ArrowError`, so
+a connector must use the same major version of Arrow: the SDK re-exports the 
crates as
+`spark_native_source::arrow_array` and `spark_native_source::arrow_schema`. 
Upgrading the
+major version of Arrow is a breaking change of the SDK.
+
+The [Range connector][range] is a separate workspace member under
+`examples/src/main/rust/native-data-source`, with a C integration test, 
packaging
+helper, and Spark smoke script. The [file sink example][sink] is a separate 
write-only
+connector. All crates share this directory's lockfile and `target` directory. 
Cargo commands
+select the SDK by default; use `--workspace` to include the examples.
+
+## Connector API and lifecycle
+
+A connector implements [`DataSource`](src/lib.rs) for construction, schema 
discovery,
+its operations, and optional capability restrictions. `DataSource::new` 
receives a
+`CreateInfo` with the name of the data source and its options. Spark can 
create and
+immediately drop a source just to discover capabilities; schema inference or an
+operation need not follow.
+
+Four associated types name the operations that the source implements, and
+`Unsupported` stands for one that it does not implement:
+
+```rust
+impl DataSource for RangeSource {
+    type ScanBuilder = RangeScan; // batch reads, created by new_scan
+    type MicroBatchStream = RangeStream; // streaming reads, by 
new_micro_batch_stream
+    type BatchWrite = Unsupported; // no batch writes
+    type StreamingWrite = Unsupported; // no streaming writes
+    // new, schema, new_scan, and new_micro_batch_stream
+}
+```
+
+Read support uses three pieces:
+
+* `DataSource::new_scan`: create an independent scan builder from a 
`ScanInfo`, which
+  carries the schema to read.
+* `ScanBuilder`: negotiate the limit and the columns to read, then consume 
itself
+  in `plan()` to return a typed `ScanPlan<Factory>`.
+* `PartitionReaderFactory`: serialize executor configuration and open one lazy 
reader,
+  an iterator of Arrow batches, from a typed partition and a `ReaderContext`, 
which
+  carries the schema to read and a borrowed `TaskContext`.
+
+Streaming reads reuse the executor side: `DataSource::new_micro_batch_stream` 
creates a
+`MicroBatchStream` from a `MicroBatchStreamInfo`, which carries the columns to 
read and the
+location of the checkpoint of the source, and the stream plans each 
micro-batch as a
+`ScanPlan` of a `PartitionReaderFactory`; see
+[Streaming reads and writes](#streaming-reads-and-writes).
+
+Write support is independent: a write-only connector sets `ScanBuilder` and
+`MicroBatchStream` to `Unsupported` and implements `DataSource::new_write`, 
`BatchWrite`,
+`DataWriterFactory`, and `DataWriter`. Streaming writes add
+`DataSource::new_streaming_write` and `StreamingWrite`, with the same task 
writers. The
+write lifecycle is described below.
+
+The inputs of these methods are `#[non_exhaustive]` structs, so that new ABI 
fields can
+reach connectors without breaking them: `*Info` structs on the driver 
(`CreateInfo`,
+`ScanInfo`, `MicroBatchStreamInfo`, `LatestOffsetInfo`, `WriteInfo`, 
`StreamingWriteInfo`,
+and `HostInfo`), and `*Context` structs, which carry the live `TaskContext`, 
on the executors
+(`ReaderContext` and `WriterContext`). `ScanPlan` has a constructor for the 
same reason.
+
+The factory and partition types implement `Serialize` and `Deserialize`.
+Connections, pointers, and open readers remain in their creating process.
+Include a snapshot identifier in the factory or partitions when retrying a task
+must read the same snapshot. Multiple task attempts open independent readers.
+
+```text
+Driver:
+  DataSource::new_scan -> ScanBuilder -> ScanPlan { factory, partitions }
+                              |                   |
+                       mutable negotiation   immutable serialized descriptors
+                                                  |
+Executor, per task:                               v
+  restored factory + partition + ReaderContext -> Arrow reader -> Arrow C 
Stream
+```
+
+The Rust API maps to the framework's driver-only `ColumnarBatchPlanner` and its
+`ColumnarPlannedBatch` containing a serializable `PartitionReaderFactory`.
+`ColumnarScanBuilder.build()` builds a single scan and transfers planner
+ownership; it does not plan partitions. `ColumnarBatchScan` plans on the first
+request for partitions or a reader factory and caches success or failure.
+
+For a native source, `NativeBatchPlanner` pushes the limit and the columns to 
read,
+each at most once and in this order, then calls `partitions` once, which 
returns the
+partitions and the state of the reader, and closes the native planner handle. 
The Rust
+`ScanBuilder::plan()` consumes its builder in that call, and the SDK encodes 
the factory
+as the state. After a call fails, Spark calls no other function on the handle 
than its
+close function. Batch planner creation remains lazy for scans that do not read 
in batch.
+
+The JVM's `NativePartitionReaderFactory` carries only the library location,
+source name, read schema, and serialized state. The native executor `read` 
entry
+point gets the kind of the read, batch or micro-batch, and the schema to read 
with
+the state and the partition, so it restores the Rust factory from those bytes 
without
+creating or accessing the driver registry, and passes the schema to the reader 
in
+`ReaderContext`. Closing the driver handles cannot invalidate factory or 
partition
+bytes already copied to Spark, including for retried tasks.
+
+The reader owns its executor resources and cannot borrow its temporary factory.
+It may borrow `TaskContext` until the returned Arrow stream is released. Every 
host
+provides the task IDs of version 1 of the ABI, so the SDK rejects a task 
context shorter
+than in version 1, as it rejects the info structures and the read limit that 
Spark passes to
+the calls when they are shorter. `is_interrupted()` checks
+Spark's live cancellation callback, not a snapshot of its initial value; for a 
reader, it
+is also true once the task ended. Check it during long operations; blocking 
I/O still
+requires timeouts. `TaskContext::for_testing()`, with its `with_*` methods and
+`interrupted_by`, builds a context with chosen IDs and an optional 
interruption flag for
+tests outside Spark.
+
+Export the source from the connector's `cdylib` crate:
+
+```rust
+spark_native_source::export_data_source!(RangeSource);
+```
+
+The macro exports only `spark_ds_init` and returns Spark's versioned function
+table. The connector uses safe Rust traits without C pointers. Rust trait 
objects
+never cross the binary boundary between libraries.
+
+`DataSource::init` runs once in each JVM when Spark loads the library, with the
+Spark version in `HostInfo`; a failure prevents Spark from using the library 
and is
+logged. The macros of the `log` crate, which the SDK re-exports as
+`spark_native_source::log`, write to the driver or executor log through Spark 
from any
+thread, including in the library's dependencies, and drop messages outside 
Spark, such
+as in unit tests. The SDK sets the level of the `log` crate to that of the log 
of Spark,
+which it asks with `SparkDsHost.is_log_enabled` when Spark loads the library 
and when an
+operation or a task starts, so it also follows a level that changes while 
Spark runs.
+
+A source that cannot infer its schema, such as a sink of any input, sets
+`DataSource::INFERS_SCHEMA` to false. The SDK then leaves the native `schema`
+function unset, so Spark requires a user-specified schema and reports its 
standard
+error without one.
+
+A library that implements several data sources is installed or listed in its
+package under each of their names. Spark passes the name in 
`CreateInfo::name`, so
+one exported `DataSource` can choose the source to create; the macro exports a
+single Rust type per library.
+
+The implementation separates public connector traits, driver handle state in
+`bridge.rs`, Arrow ownership in `stream.rs`, the writers in `write.rs`, C 
bindings in
+`abi.rs`, and the function table in `export.rs`. The macro reaches them 
through a
+hidden `__private` module, which is not part of the API.
+
+## Source capabilities
+
+The associated types of `DataSource` determine the operations of the source: 
batch
+reads unless `ScanBuilder` is `Unsupported`, micro-batch reads unless 
`MicroBatchStream`
+is, batch writes unless `BatchWrite` is, and streaming writes unless 
`StreamingWrite` is.
+The SDK installs the native callbacks of these operations, leaves the others 
null, and
+derives the default capability set from them, so the macro takes only the 
source type.
+A `BatchWrite` or a `StreamingWrite` opts into truncation with
+`const SUPPORTS_TRUNCATE: bool = true`, which declares `BATCH_TRUNCATE`, for 
the save mode
+"overwrite" of a batch write, or `STREAMING_TRUNCATE`, for the output mode 
"complete" of a
+streaming write. Its `new_*` method then gets `WriteMode::Truncate` for them; 
without it
+the write only appends. Every stream also declares the native capability
+`SPARK_DS_ADMISSION_CONTROL`, whose default read limit, all the available 
data, reads as
+a stream without it does. The macro also rejects a library built with `panic = 
"abort"`,
+because the SDK can report a panic as an error only when it unwinds.
+
+Most connectors do not implement `capabilities`. A connector can restrict the
+supported set for the current options by overriding this `DataSource` method:
+
+```rust
+fn capabilities(&self) -> Capabilities {
+    if self.read_only {
+        // The SDK also drops the truncations, which require their writes.
+        Capabilities::all().without(Capabilities::BATCH_WRITE | 
Capabilities::STREAMING_WRITE)
+    } else {
+        Capabilities::all()
+    }
+}
+```
+
+The SDK evaluates this once during `create` and keeps only implemented 
operations,
+so a source can narrow its capabilities but never enable one that it does not
+implement, and keeps each truncation only with its write.
+An empty set permits schema discovery and close, but rejects operation creation
+before calling the connector. The declaration stays fixed for that instance.
+The default declaration is `Capabilities::all()`, every operation of the SDK. 
Limit and
+column pruning remain per-scan contracts.
+
+Spark also calls `create` and `close` during query analysis to discover table
+capabilities. A probe uses the table's options, while an operation may override
+them with query options and checks capabilities again on a new source instance.
+Keep `DataSource::new` and `capabilities` lightweight and safe to drop
+immediately; do not assume that `schema` or `new_scan` will follow. Executor
+resources belong in `PartitionReaderFactory::open`.
+
+Spark propagates the native `BATCH_WRITE` and `BATCH_TRUNCATE` flags to
+`Table.capabilities()`, as `BATCH_WRITE` and `TRUNCATE`, so a read-only source 
rejects
+batch writes during analysis, before Spark computes their input. Its DSv2 read 
and
+streaming-write flags remain present to avoid V1 fallback; the native flags 
still reject
+unsupported reads or streaming writes during planning. Thus the DSv2 table's 
flags are not
+a literal copy of the native mask declared by the Rust source, and an 
unsupported
+streaming read or write fails when its query starts or plans its first 
micro-batch, after
+`start()` returns.
+
+## Batch write lifecycle
+
+```text
+Driver:
+  DataSource::new_write -> BatchWrite
+                             | writer_factory()  ^ commit(messages) / 
abort(messages)
+                    serialized factory           | typed messages
+                             |                   |
+Executor, per task attempt:  v                   |
+                       DataWriterFactory::open(WriterContext)
+                                -> DataWriter::write(RecordBatch)*
+                                -> commit() / abort() -> Drop
+```
+
+`DataSource::new_write(WriteInfo)` validates the input schema and returns an
+independent driver coordinator, a `BatchWrite`. Its `writer_factory` returns 
the
+serializable executor configuration of its task writers, which the SDK encodes 
as the
+state of the writer that native `create_writer` returns. Restoring an executor 
writer
+uses only those bytes and the schema that Spark passes with them, without 
creating a
+driver registry.
+
+Each `DataWriterFactory::open` receives a `WriterContext` with the input 
schema and
+the task, and returns a task-bound writer. `write` takes ownership of a
+`RecordBatch`, so its Arrow buffers can be retained after the callback, until 
the writer
+is dropped: they belong to the data writer of Spark, and the ABI requires the 
library to
+release them before Spark closes the writer. Spark cannot free a batch that is 
still
+retained when it closes the writer: it logs an error, and the memory stays 
allocated until
+the batch is dropped. The SDK
+moves the incoming Arrow array, which has the schema that the data writer got, 
and
+releases imported resources on failures. Input slices need not have zero 
offsets;
+the zero-offset restriction applies to arrays exported to Spark by readers. 
When Spark
+writes the batches of a native scan without converting them to rows, it copies 
their
+values as the scan returned them, without the checks of a conversion, such as 
the
+precision of a decimal. Check cancellation during lengthy writes and use I/O 
timeouts.
+
+Task `commit()` returns a typed, serde-serializable message, the `Message` of 
the
+`BatchWrite`. Driver `commit`
+receives one winning message per partition, at the position of its partition;
+driver `abort` receives `Vec<Option<Message>>`, with `None` for a partition 
whose
+message did not arrive or cannot be decoded, so a corrupted message cannot 
prevent
+cleanup. A failed task or driver commit leaves the same object available for 
abort.
+A task commit whose message cannot be serialized counts as failed, so `abort` 
can
+follow a `commit` that returned a message. Spark calls each method at most 
once, never
+writes after a failure or a commit, and never aborts a successful commit, as 
the header
+documents, so connectors do not need to track their own phase; the `# 
Lifecycle`
+sections of `BatchWrite` and `DataWriter` list the exact call-order 
guarantees. Drop only
+releases resources.
+
+Stage data per task attempt and publish it only at driver commit. In 
particular,
+`WriteMode::Truncate` must leave existing data intact until that commit. 
Retries
+and speculative attempts may stage data for the same partition; publish only 
the
+attempts whose messages Spark passes to commit. Executor loss can prevent 
cleanup,
+including after task commit, so connectors need a strategy for orphaned data.
+Spark provides no batch query ID: generate and serialize an operation identity
+when needed. Task-attempt IDs alone are not globally unique across 
applications.
+
+When `writer_factory` or the serialization of its factory fails, 
`create_writer` fails,
+and when Spark cannot copy the serialized factory, for example when it is too 
large, Spark
+fails the write. Either way, the SDK drops the coordinator without commit or 
abort, so
+Drop must also release what only that write staged. Spark also creates writers 
late, after
+prerequisite AQE shuffle stages, but input computation can still fail during 
write tasks.
+Constructors must therefore avoid irreversible changes. The epoch ID tells the 
task writers
+of batch writes, whose epoch ID is `-1`, from those of micro-batches.
+
+The [file sink][sink] demonstrates append/truncate using staged JSONL files and
+atomic publication of a manifest on a local or shared filesystem. Its 
documented
+single-writer assumption and orphan cleanup limitations are example 
constraints,
+not transaction guarantees provided by the SDK.
+
+## Streaming reads and writes
+
+Micro-batch streaming reads reuse the executor side of batch scans:
+
+```text
+Driver, for each run of a query:
+  DataSource::new_micro_batch_stream -> MicroBatchStream
+      initial_offset(), default_read_limit()
+      latest_offset(LatestOffsetInfo) -> Offset, stored as JSON in the 
checkpoint
+      plan(start, end) -> ScanPlan { factory, partitions }, for each 
micro-batch
+      commit(end)
+Executor, per task:
+  restored factory + partition + ReaderContext -> Arrow reader -> Arrow C 
Stream
+```
+
+Spark creates a stream when a query starts or restarts from its checkpoint, 
and closes it
+when the query stops. It keeps the initial offset in the checkpoint, and asks 
for it only
+when the checkpoint does not have it yet. For each micro-batch, it asks for 
the latest
+offset after the end of the previous micro-batch, and plans the data up to 
that offset.
+The executors read the partitions of a micro-batch exactly as those of a batch 
scan: the
+two share `read`, which gets the kind of the read. 
`MicroBatchStreamInfo::schema` has the
+columns to read, which are all the columns of the schema until Spark prunes 
the columns of
+streaming scans.
+
+`MicroBatchStream::default_read_limit` limits the data of each micro-batch, 
for example
+to `ReadLimit::MaxRows` from an option of the source; the default reads all 
the available
+data. Spark passes the limit to `latest_offset` in `LatestOffsetInfo::limit`, 
and with
+`Trigger.AvailableNow` and a `ReadLimit::MaxRows` limit, the end of the run in
+`LatestOffsetInfo::run_end`, which the latest offset must not go beyond. Spark 
also asks
+without a limit for the progress of the query, so a stream does not count the 
calls of
+`latest_offset` as micro-batches.
+
+The SDK serializes `MicroBatchStream::Offset` with serde as compact JSON on a 
single line,
+which Spark stores in the checkpoint as it is, without the SDK's versioned 
envelope, and
+decodes the offsets that Spark passes back. Spark compares offsets by their 
JSON to decide
+whether a micro-batch has new data, so a position must always serialize to the 
same JSON:
+use structs and `BTreeMap`, not `HashMap`. A restarted query may plan its last 
range again,
+with offsets from its checkpoint that an earlier version of the library may 
have written.
+When that version had a different `Offset` type, for example without a field 
that the new
+one adds with `#[serde(default)]`, the same position encodes to different 
JSON, so Spark
+runs one micro-batch without rows. A failed call, including a panic or an 
offset that does
+not decode, stops the query: Spark makes no other call on the stream before it 
closes it.
+
+Streaming writes reuse the task writers of batch writes. Spark creates a 
`StreamingWrite`
+for each micro-batch, from a `StreamingWriteInfo` with the ID of the query, 
which stays the
+same across restarts. It follows the lifecycle of a `BatchWrite`; the SDK 
passes the epoch ID
+of the micro-batch to `commit` and `abort`, and gives it to the task writers in
+`WriterContext::epoch_id`. Spark may commit an epoch again after a restart, 
with a new
+write, so a write must skip an epoch that is already committed: the query ID 
and the epoch
+ID identify the output of a micro-batch. A restarted query may also abort an 
epoch that an
+earlier run committed, so an abort removes only what its own task writers 
wrote. The
+[file sink][sink] records the last epoch of each query in its manifest for 
this. Continuous
+processing is not supported.
+
+## Arrow contract
+
+`PartitionReaderFactory::open` returns a lifetime-bound `PartitionReader`, a 
boxed
+`Send` iterator of `Result<RecordBatch, ArrowError>`, as any Arrow 
`RecordBatchReader`
+is. Return batches lazily with bounded memory, with the columns of
+`ReaderContext::schema`. A batch may also have other columns, such as all the 
columns of
+the source: the SDK keeps those of the schema to read, by name and in its 
order, since
+Spark rejects a stream with other columns. The first batch determines the 
Arrow schema of
+the stream, which every later batch must have; a reader without batches 
exports the
+schema to read. Exported arrays own their buffers independently of the reader: 
Spark may
+release a stream before releasing its previously returned batches.
+
+Stream callbacks, including release, may run on different threads, but never
+concurrently. Readers must be `Send`; they do not need to be `Sync` or tied to
+the thread that opened the stream. Stream errors are owned by the stream and
+remain readable after a callback moves to another thread.
+
+The SDK validates the schema to read before exporting a reader and checks each
+batch's schema and recursive array offsets. It compares Spark logical types,
+ignoring nullability and Arrow metadata, accepting the supported string/binary
+encodings and equivalent timestamp time zones. It rejects unsupported types, 
schema
+drift, and nonzero array offsets with explicit errors. It does not silently 
copy
+arrays, cast types, or expand dictionary encoding. Batches must also respect 
the
+nullability of the schema to read: as Spark does, the SDK rejects a null in a 
column,
+field, element, or map value that the schema declares not nullable, unless its 
parent
+value is null.
+
+The supported types are those of version 1 of the ABI: signed integers,
+float32/64, boolean, strings and binary (including Large and View variants), 
decimal128
+up to precision 38, date32, microsecond timestamps with or without a time zone,
+structs, lists, and maps. Spark rejects other Spark types, such as intervals,
+variant, time, and the null type, before it passes a schema to the library.
+Dictionary encoding, unsigned integers, decimal256, large/fixed-size lists, and
+non-microsecond timestamps are outside this prototype's contract. Normalize 
sliced
+arrays when necessary before returning them.
+
+An empty projection must retain the number of rows even with no columns. The
+[Range implementation][range-source] demonstrates this together with bounded
+batches, disjoint partitions, admission control, and cooperative cancellation.
+
+## Pushdown contracts
+
+| Limit result | ABI boolean | Meaning |
+| --- | --- | --- |
+| `Unsupported` | `false` | No promise; a connector may still cap each 
partition on its own |
+| `Global` | `true` | The entire scan returns at most the limit |
+
+Spark retains its final limit and pushes a limit only when the query does not 
filter
+the rows of the scan, since it filters them after reading.
+
+`ScanBuilder::prune_columns` gets the top-level columns that the query needs, 
in order,
+so that the scan can plan to read only them. The readers get them as the 
schema to read
+whether or not the scan implements it, and return exactly them, so a connector 
can add
+pruning to the planning of its scans incrementally.
+
+Version 1 of the ABI does not push filters down yet; Spark evaluates them 
after reading.
+
+## Build and test without Spark
+
+Use Rust 1.85 or newer (as required by Arrow 58) and a C compiler. The C 
integration
+test uses `dlopen` and pthreads on Linux or macOS. From this directory:
+
+```bash
+cargo test --workspace --locked
+cargo clippy --workspace --all-targets --locked -- -D warnings
+cargo fmt --all -- --check
+```
+
+The C harness loads the example dynamic library that `cargo test` builds. It 
compiles
+against [Spark's header][header], as a library that copies it would. It calls 
the actual
+function table and validates capability-only source discovery and optional 
slots,
+independent driver planners, pushdown and planning, serialized executor reads, 
rejection of
+structures shorter than in version 1, cancellation, sequential cross-thread 
stream
+callbacks, Arrow buffers surviving stream release, micro-batch reads with 
their offsets,
+including an offset that does not decode, and admission control. This checks 
the C
+boundary without requiring Java; it does not substitute for Spark planner and 
task-lifecycle
+testing.
+
+Rust tests additionally exercise the exported function table with 
option-dependent
+capabilities, narrowed and unimplemented declarations, the source name, library
+initialization, and logging that follows the level of the host, and panics 
during
+capability discovery. They also cover planning failures, retries after the 
driver registry
+is dropped, schema, layout, and nullability validation, the columns of the 
schema to read
+that the SDK keeps from a batch, sized ABI structures, task-context lifetimes, 
integer
+boundaries, projections, and deterministic partition plans. Write ABI tests 
cover typed
+factory/message round trips, retained Arrow buffers, cancellation, failed 
writes and
+commits, factory creation and serialization failures, missing and undecodable 
messages,
+and the epoch IDs that select the task writers. Streaming ABI tests cover 
single-line JSON
+offsets, the state of each planned micro-batch, reads that restore batch or 
micro-batch
+factories of different types, read limits and the end of a run, the checkpoint 
location,
+and the query and epoch IDs of streaming writes and their task writers. The 
sink tests
+cover append/truncate publication, losing attempts, messages at the wrong 
partition
+position, cleanup after failed publication while preserving the previous 
manifest, and
+streaming epochs that are published once.
+
+## Package and run with Spark
+
+See the [Range example guide][range] for packaging and `spark-submit` commands.
+Its `package.py` creates a single-platform `.sparkpkg`; `smoke.py` checks 
reading,
+filtered reads, projection, unfiltered limit pushdown, streaming reads with 
and without a

Review Comment:
   **Nit (P3):** `smoke.py` only asserts that `df.limit(4).collect()` returns 
four rows with ids in range. That also holds when nothing is pushed down, since 
Spark applies the limit again after reading either way 
(spark_datasource.h:700-701), and the script does not inspect the plan. The 
Range README calls this check "unfiltered and filtered limits":
   
   ```suggestion
   filtered reads, projection, unfiltered limits, streaming reads with and 
without a
   ```
   
   **Verification:**
   - **Inspection:** Each check that the SDK documentation attributes to the 
Range example's smoke script corresponds to an assertion that the script makes.



##########
examples/src/main/rust/native-data-sink/README.md:
##########
@@ -0,0 +1,164 @@
+<!--
+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.
+-->
+
+# Rust native sink
+
+This write-only example implements `DataSource`, `BatchWrite`, 
`StreamingWrite`,
+`DataWriterFactory`, and `DataWriter` from the [Rust native data source 
SDK][sdk]. Its
+`DataSource` sets `type ScanBuilder = Unsupported` and `type MicroBatchStream 
= Unsupported`,
+and its batch and streaming writes declare truncation support with
+`const SUPPORTS_TRUNCATE: bool = true`; it exports 
`export_data_source!(JsonSink)` and
+implements no read traits. The SDK supplies the C ABI entry point, typed 
factory and commit
+message serialization, Arrow batch import, capability checks, and error 
handling.
+
+The example targets version 1 of the C ABI of native data sources, 
`spark_datasource.h`,
+which Spark 4.4.0 introduces. Running it in Spark requires Java 22 or later on 
the driver
+and executors. The standalone Rust tests do not need Spark or a JVM.
+
+## Supported data and options
+
+The sink accepts exactly two columns, in this order: `id BIGINT` and `label 
STRING`.
+Both nullable and non-nullable input fields are accepted. Null values are 
preserved.
+Task writers encode batches incrementally as JSON lines, avoiding an additional
+file-format dependency in this small example.
+
+| Option | Default | Meaning |
+| --- | --- | --- |
+| `path` | Required | Absolute directory shared by the driver and every 
executor |
+| `readonly` | `false` | Remove all the capabilities, which are those of 
writes, when `true` |
+
+Unknown options are rejected, except `checkpointLocation`, which Spark passes 
to the sink of
+a streaming query. Source creation and capability discovery do not create 
files. The default
+instance advertises only native `BATCH_WRITE`, `STREAMING_WRITE`, 
`BATCH_TRUNCATE`, and
+`STREAMING_TRUNCATE`; it does not advertise reads. Spark performs its native 
capability check
+again with the operation's effective options.
+
+## Commit and abort protocol
+
+Each write operation holds a `.write-lock` directory under `path`, rejecting 
another
+concurrent writer. It assigns an operation ID and stages tasks in 
`.staging/<operation>`.
+Each task attempt exclusively creates its own file, writes Arrow batches, 
flushes and
+syncs the file, then returns a typed message containing its operation, file, 
partition,
+and row count. Task commit alone does not publish data.
+
+The driver receives the winning attempt messages, the message of partition `i` 
at
+position `i`. It validates those messages and renames the entire staging 
directory
+to `objects/<operation>`, preventing new tasks from opening files for that
+operation. It removes every file not named by a winning
+message, including speculative attempts and attempts whose messages never 
arrived.
+It then writes and syncs a new manifest and atomically renames it to 
`manifest.json`.
+That one manifest replacement is the commit point:
+
+- Append includes the previous manifest's files plus the winning new files.
+- Truncate includes only the winning new files, including an empty result.
+- Previously published data files are retained, so an existing manifest 
snapshot
+  stays readable and a failed overwrite cannot delete the old data.
+- Abort removes the entire operation, including files with no commit message 
and
+  a sealed directory whose manifest publication failed. It leaves the current
+  manifest and its data unchanged. Dropping an unfinished coordinator also 
performs
+  best-effort cleanup. Dropping a committed task writer leaves its file for 
the driver.
+
+To inspect output, read only the files listed in `manifest.json`. Recursively 
reading
+the destination directory would also pick up data from previous truncate 
operations.
+
+## Streaming writes
+
+A streaming query writes each micro-batch, or epoch, with the protocol above: 
Spark creates a
+`JsonStreamingWrite` for each micro-batch, which stages, seals, and publishes 
its files as a
+batch write does. The output mode "append" appends to the manifest, and 
"complete" replaces its
+files, as a truncate does.
+
+The manifest also records the last epoch that each streaming query committed, 
by the ID of the
+query, which stays the same when the query restarts from its checkpoint. Spark 
may commit an
+epoch again after a restart, so a micro-batch whose epoch the manifest already 
records for its
+query publishes nothing: it removes what it staged and leaves the manifest 
unchanged. Each epoch
+of a query is therefore published once, and the queries that write to the same 
destination keep
+their epochs apart.
+For example, after a successful write:

Review Comment:
   **Nit (P3):** Without a blank line, this continues the paragraph about the 
epochs that streaming queries record, so the snippet reads as an example of 
epochs being published once. It only reads the files that `manifest.json` 
lists, which illustrates "To inspect output, read only the files listed in 
`manifest.json`" in the previous section (README.md:75-76). Moving it there, or 
introducing it as reading the published output, fixes the reference.
   
   **Verification:**
   - **Inspection:** The example of reading the output follows the advice to 
read only the files listed in manifest.json, and the streaming section no 
longer introduces it.



##########
sql/native/rust/src/lib.rs:
##########
@@ -0,0 +1,772 @@
+// 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.
+
+//! Experimental SDK for native data sources in Rust, over version 1 of the C 
ABI of Spark,
+//! `spark_datasource.h`.
+//!
+//! Implement [`DataSource`], naming the types of the operations that it 
implements: a
+//! [`ScanBuilder`] for batch reads, a [`MicroBatchStream`] for micro-batch 
streaming reads, a
+//! [`BatchWrite`] for batch writes, and a [`StreamingWrite`] for streaming 
writes, or
+//! [`Unsupported`] for an operation that it does not implement. Then invoke
+//! [`export_data_source!`] once in a `cdylib` crate. The SDK
+//! owns handles, plan/message serialization, C ABI adaptation, and Arrow 
import/export.
+//! Rust traits stay inside the plugin; they are not an ABI between dynamic 
libraries.
+//!
+//! Methods receive their inputs in `#[non_exhaustive]` structs, so that new 
ABI fields
+//! can reach connectors without breaking them: `*Info` structs on the driver
+//! ([`CreateInfo`], [`ScanInfo`], [`MicroBatchStreamInfo`], 
[`LatestOffsetInfo`],
+//! [`WriteInfo`], [`StreamingWriteInfo`], and [`HostInfo`]), and `*Context` 
structs, which

Review Comment:
   **Nit (P3):** `HostInfo` is listed with the inputs on the driver, but its 
only consumer is `DataSource::init`, which `spark_ds_init` runs once in every 
JVM that loads the library, executors included (spark_datasource.h:48), as the 
`init` docs say (lib.rs:134). A connector that follows this split may put 
driver-only setup, such as opening a catalog or metastore connection, in 
`init`, which then also runs on every executor. The README's list 
(README.md:86-88) has the same entry.
   
   **Verification:**
   - **Inspection:** The SDK's documentation describes where HostInfo is 
delivered consistently with the documentation of DataSource::init.



##########
sql/native/rust/src/lib.rs:
##########
@@ -0,0 +1,772 @@
+// 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.
+
+//! Experimental SDK for native data sources in Rust, over version 1 of the C 
ABI of Spark,
+//! `spark_datasource.h`.
+//!
+//! Implement [`DataSource`], naming the types of the operations that it 
implements: a
+//! [`ScanBuilder`] for batch reads, a [`MicroBatchStream`] for micro-batch 
streaming reads, a
+//! [`BatchWrite`] for batch writes, and a [`StreamingWrite`] for streaming 
writes, or
+//! [`Unsupported`] for an operation that it does not implement. Then invoke
+//! [`export_data_source!`] once in a `cdylib` crate. The SDK
+//! owns handles, plan/message serialization, C ABI adaptation, and Arrow 
import/export.
+//! Rust traits stay inside the plugin; they are not an ABI between dynamic 
libraries.
+//!
+//! Methods receive their inputs in `#[non_exhaustive]` structs, so that new 
ABI fields
+//! can reach connectors without breaking them: `*Info` structs on the driver
+//! ([`CreateInfo`], [`ScanInfo`], [`MicroBatchStreamInfo`], 
[`LatestOffsetInfo`],
+//! [`WriteInfo`], [`StreamingWriteInfo`], and [`HostInfo`]), and `*Context` 
structs, which
+//! carry the live [`TaskContext`], on the executors ([`ReaderContext`] and 
[`WriterContext`]).
+
+use std::collections::BTreeMap;
+
+use arrow_array::RecordBatch;
+use arrow_schema::{ArrowError, SchemaRef};
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+
+mod abi;
+mod bridge;
+mod capabilities;
+mod export;
+mod host;
+mod task;
+mod unsupported;
+mod write;
+
+/// Implementation details of [`export_data_source!`] and of the SDK's own 
tests, not an API.
+#[doc(hidden)]
+pub mod __private {
+    pub use crate::bridge::Bridge;
+    pub use crate::export::{library, Exported};
+
+    pub mod abi {
+        pub use crate::abi::*;
+    }
+}
+
+/// The Arrow crate of [`RecordBatch`], which connectors can use to have the 
same version of
+/// Arrow as the SDK.
+pub use arrow_array;
+/// The Arrow crate of [`SchemaRef`] and [`ArrowError`], which connectors can 
use to have the
+/// same version of Arrow as the SDK.
+pub use arrow_schema;
+pub use capabilities::Capabilities;
+pub use host::HostInfo;
+/// The `log` crate, whose macros write to the log of the Spark driver or 
executor, with
+/// the path of the library, once Spark initializes the library.
+///
+/// Any thread can call them, including in the dependencies of the library. 
Outside
+/// Spark, for example in unit tests, their messages are dropped. The SDK sets 
the level of
+/// the `log` crate to that of the log of Spark, such as `Debug` when Spark 
logs debug
+/// messages, so the library does not set it.
+pub use log;
+pub use task::TaskContext;
+pub use unsupported::Unsupported;
+
+pub type Error = Box<dyn std::error::Error + Send + Sync>;
+pub type Result<T> = std::result::Result<T, Error>;
+pub type Options = BTreeMap<String, String>;
+
+// Data sources: Spark creates a DataSource for each operation, and its 
associated types
+// name the operations that the source implements.
+
+/// What Spark passes to create a data source.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct CreateInfo {
+    /// The name of the data source, as listed in the manifest of its package, 
or in
+    /// lower case for an installed library. A library that implements several 
data
+    /// sources, installed or listed under each of their names, can choose by 
this name.
+    pub name: String,
+    /// The options, with keys in lower case. A capability probe uses the 
options of the
+    /// table; an operation may override them with the options of its query.
+    pub options: Options,
+}
+
+impl CreateInfo {
+    /// The information of a source created outside Spark, for example in a 
test.
+    pub fn new(name: impl Into<String>, options: Options) -> Self {
+        Self {
+            name: name.into(),
+            options,
+        }
+    }
+}
+
+/// Driver-side source configuration, schema discovery, and the operations of 
a source.
+///
+/// The associated types name the operations that the source implements, and
+/// [`Unsupported`] stands for one that it does not implement:
+///
+/// ```rust,ignore
+/// impl DataSource for RangeSource {
+///     type ScanBuilder = RangeScan;
+///     type MicroBatchStream = RangeStream;
+///     type BatchWrite = Unsupported;
+///     type StreamingWrite = Unsupported;
+///     ...
+/// }
+/// ```
+///
+/// The SDK installs native callbacks and reports capabilities only for the 
implemented
+/// operations, and calls the `new_*` method of an operation only for them.
+///
+/// Spark creates a source for each schema inference, scan, stream, and write, 
including
+/// the write of each micro-batch, and may create one only to inspect its 
capabilities,
+/// then drop it. Keep construction lightweight. Scan builders, streams, and 
writes cannot
+/// borrow their source, which Spark drops first.
+pub trait DataSource: Send + Sized + 'static {
+    fn new(info: CreateInfo) -> Result<Self>;
+
+    /// Called once in each JVM when Spark loads the library, before it 
creates any
+    /// source. On failure, Spark does not use the library, and the error is 
logged.
+    fn init(_host: &HostInfo) -> Result<()> {
+        Ok(())
+    }
+
+    // Schema discovery.
+
+    /// Whether [`schema`](Self::schema) infers the schema of the data. When 
false, the
+    /// SDK leaves the native function unset: Spark then requires a 
user-specified
+    /// schema, reports its standard error without one, and never calls 
`schema`.
+    const INFERS_SCHEMA: bool = true;
+
+    /// Returns the schema of the data, when the user does not specify one.
+    fn schema(&self) -> Result<SchemaRef> {
+        Err(
+            "DataSource::schema is not implemented: implement it, or set \
+             DataSource::INFERS_SCHEMA to false to require a user-specified 
schema"
+                .into(),
+        )
+    }
+
+    // Batch reads.
+
+    /// The scan builder of batch reads, which [`new_scan`](Self::new_scan) 
creates, or
+    /// [`Unsupported`].
+    type ScanBuilder: ScanBuilder;
+
+    /// Creates an independent scan of [`ScanInfo::schema`], which the user 
may have
+    /// specified; reject unsupported schemas.
+    fn new_scan(&self, _info: ScanInfo) -> Result<Self::ScanBuilder> {
+        Err(
+            "DataSource::new_scan is not implemented: implement it, or set \
+             DataSource::ScanBuilder to Unsupported"
+                .into(),
+        )
+    }
+
+    // Micro-batch streaming reads.
+
+    /// The stream of micro-batch streaming reads, which
+    /// [`new_micro_batch_stream`](Self::new_micro_batch_stream) creates, or 
[`Unsupported`].
+    type MicroBatchStream: MicroBatchStream;
+
+    /// Creates the stream of a streaming query that reads the columns of
+    /// [`MicroBatchStreamInfo::schema`]; reject unsupported schemas.
+    fn new_micro_batch_stream(
+        &self,
+        _info: MicroBatchStreamInfo,
+    ) -> Result<Self::MicroBatchStream> {
+        Err(
+            "DataSource::new_micro_batch_stream is not implemented: implement 
it, or set \
+             DataSource::MicroBatchStream to Unsupported"
+                .into(),
+        )
+    }
+
+    // Batch writes.
+
+    /// The coordinator of batch writes, which [`new_write`](Self::new_write) 
creates, or
+    /// [`Unsupported`].
+    type BatchWrite: BatchWrite;
+
+    /// Validate the input schema and create an independent write. 
Construction may be
+    /// followed only by Drop, without commit or abort, so it must not make 
irreversible
+    /// changes. The SDK calls this only while the instance's capabilities 
include
+    /// `BATCH_WRITE`, and passes [`WriteMode::Truncate`] only when they 
include
+    /// `BATCH_TRUNCATE`, which the write declares with 
[`BatchWrite::SUPPORTS_TRUNCATE`].
+    fn new_write(&self, _info: WriteInfo) -> Result<Self::BatchWrite> {
+        Err(
+            "DataSource::new_write is not implemented: implement it, or set \
+             DataSource::BatchWrite to Unsupported"
+                .into(),
+        )
+    }
+
+    // Streaming writes.
+
+    /// The coordinator of the write of each micro-batch of a streaming query, 
which
+    /// [`new_streaming_write`](Self::new_streaming_write) creates, or 
[`Unsupported`].
+    type StreamingWrite: StreamingWrite;
+
+    /// Validate the input schema and create the write of a micro-batch. As 
with
+    /// [`new_write`](Self::new_write), construction may be followed only by 
Drop, so it must
+    /// not make irreversible changes. The SDK calls this only while the 
instance's
+    /// capabilities include `STREAMING_WRITE`, and passes 
[`WriteMode::Truncate`] only when
+    /// they include `STREAMING_TRUNCATE`, which the write declares with
+    /// [`StreamingWrite::SUPPORTS_TRUNCATE`].
+    fn new_streaming_write(&self, _info: StreamingWriteInfo) -> 
Result<Self::StreamingWrite> {
+        Err(
+            "DataSource::new_streaming_write is not implemented: implement it, 
or set \
+             DataSource::StreamingWrite to Unsupported"
+                .into(),
+        )
+    }
+
+    // Instance restrictions.
+
+    /// Returns the operations of this instance. The SDK keeps only those that 
the source
+    /// implements, so the default, [`Capabilities::all`], keeps them all. 
Override this to
+    /// restrict an instance, for example for a read-only destination. The SDK 
evaluates
+    /// it once when Spark creates the source. An instance without operations 
still
+    /// supports schema discovery.
+    fn capabilities(&self) -> Capabilities {
+        Capabilities::all()
+    }
+}
+
+// Batch reads: a ScanBuilder negotiates pushdown and plans the scan on the 
driver, and a
+// PartitionReaderFactory opens a reader of each partition on the executors.
+
+/// What Spark passes to create a scan.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct ScanInfo {
+    /// The schema to read: the schema of the source, or one that the user 
specified.
+    pub schema: SchemaRef,
+}
+
+impl ScanInfo {
+    /// The information of a scan created outside Spark, for example in a test.
+    pub fn new(schema: SchemaRef) -> Self {
+        Self { schema }
+    }
+}
+
+/// Negotiates pushdown on the driver, then plans the scan.
+///
+/// Spark calls [`push_limit`](Self::push_limit) and 
[`prune_columns`](Self::prune_columns),
+/// each at most once and in this order, then [`plan`](Self::plan), and drops 
the builder.
+/// After a call fails, it makes no other call. It drops a builder without 
planning it when it
+/// does not read the scan, for example to only explain a query. Only the 
serialized factory
+/// and partitions reach the executors.
+pub trait ScanBuilder: Send + Sized + 'static {
+    type Factory: PartitionReaderFactory;
+
+    /// False only for [`Unsupported`], from which the SDK derives the 
capabilities.
+    #[doc(hidden)]
+    const SUPPORTED: bool = true;
+
+    /// Count rows. Spark pushes a limit only when the query does not filter 
the rows, since
+    /// it filters them after reading.
+    fn push_limit(&mut self, _limit: usize) -> Result<LimitSupport> {
+        Ok(LimitSupport::Unsupported)
+    }
+
+    /// Tells the scan the top-level columns that the query needs, in order, 
so that it can
+    /// plan to read only them. There may be none, for example for `SELECT 
count(*)`: the
+    /// batches then only have a number of rows. Readers get these columns in
+    /// [`ReaderContext::schema`] whether or not the scan implements this 
method.
+    fn prune_columns(&mut self, _columns: &[String]) -> Result<()> {
+        Ok(())
+    }
+
+    fn plan(self) -> Result<ScanPlan<Self::Factory>>;
+}
+
+/// Whether a connector limits the rows produced by the whole scan.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum LimitSupport {
+    /// The scan may return more rows than the limit. A connector may still 
cap the
+    /// rows of each partition on its own: Spark applies its limit after 
reading.
+    Unsupported,
+    /// The whole scan returns at most the limit. Spark still applies its 
limit.
+    Global,
+}
+
+/// A driver-created plan containing only serializable values.
+///
+/// The SDK serializes the reader factory once and each partition 
independently.
+/// Include snapshot identifiers when needed for repeatable task attempts. Do 
not
+/// put pointers, open files, connections, or process-local resources here.
+#[non_exhaustive]
+pub struct ScanPlan<F: PartitionReaderFactory> {
+    pub factory: F,
+    pub partitions: Vec<F::Partition>,
+}
+
+impl<F: PartitionReaderFactory> ScanPlan<F> {
+    pub fn new(factory: F, partitions: Vec<F::Partition>) -> Self {
+        Self {
+            factory,
+            partitions,
+        }
+    }
+}
+
+/// Serializable configuration from which executors open partition readers.
+///
+/// The factory carries configuration or a snapshot descriptor; open 
connections and
+/// other live resources in [`open`](Self::open). Spark passes the schema to 
read with
+/// each partition, so the factory need not carry it.
+pub trait PartitionReaderFactory: Serialize + DeserializeOwned + Send + 
'static {
+    type Partition: Serialize + DeserializeOwned + Send + 'static;
+
+    /// Opens a lazy reader of the batches of `partition`, with the columns of
+    /// [`ReaderContext::schema`].
+    ///
+    /// - Return batches lazily, with bounded memory.
+    /// - The reader owns its resources and cannot borrow this short-lived 
factory. It
+    ///   may keep `context` until Spark releases the stream.
+    /// - Spark may call the reader on different threads, never concurrently, 
so it must
+    ///   be `Send` but not necessarily `Sync`.
+    /// - Check [`TaskContext::is_interrupted`] during long operations, and 
use timeouts
+    ///   for blocking I/O.
+    /// - Batches must own their buffers, because Spark may release the stream 
before
+    ///   its batches.
+    ///
+    /// The SDK checks Spark-compatible Arrow types, the schema to read and its
+    /// nullability, and zero array offsets recursively. It reports 
incompatible layouts
+    /// instead of copying buffers. A batch may have more columns than the 
schema to read,
+    /// such as all the columns of the source: the SDK keeps those of the 
schema, by name.
+    /// Batches may use any supported Arrow encoding of a Spark type, such as 
`LargeUtf8`
+    /// for a string, but the first batch determines the Arrow schema of the 
stream, which
+    /// every later batch must have.
+    fn open<'task>(
+        &self,
+        partition: Self::Partition,
+        context: ReaderContext<'task>,
+    ) -> Result<PartitionReader<'task>>;
+}
+
+/// What an executor reader receives with its partition.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct ReaderContext<'task> {
+    /// The schema to read: the columns that the scan reads, in order, which 
are those of
+    /// [`ScanBuilder::prune_columns`] for a batch scan, and of
+    /// [`MicroBatchStreamInfo::schema`] for a micro-batch.
+    pub schema: SchemaRef,
+    /// The task that reads the partition.
+    pub task: TaskContext<'task>,
+}
+
+impl<'task> ReaderContext<'task> {
+    /// The context of a reader opened outside Spark, for example in a test.
+    pub fn new(schema: SchemaRef, task: TaskContext<'task>) -> Self {
+        Self { schema, task }
+    }
+}
+
+/// The lazy batches of one partition, which [`PartitionReaderFactory::open`] 
returns.
+/// Any Arrow `RecordBatchReader`, such as a Parquet reader, is such an 
iterator.
+pub type PartitionReader<'task> =
+    Box<dyn Iterator<Item = std::result::Result<RecordBatch, ArrowError>> + 
Send + 'task>;
+
+// Micro-batch streaming reads: a MicroBatchStream finds new data and plans 
each micro-batch on
+// the driver, and the PartitionReaderFactory of each plan reads its 
partitions on the executors,
+// as in batch reads.
+
+/// What Spark passes to create the stream of a streaming query.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct MicroBatchStreamInfo {
+    /// The columns to read: those of the schema of the source, or of one that 
the user
+    /// specified, or only the top-level columns of it that the query needs. 
The readers of
+    /// the micro-batches get it in [`ReaderContext::schema`].
+    pub schema: SchemaRef,
+    /// A directory in the checkpoint of the query that is reserved for this 
source, such as
+    /// `file:/tmp/checkpoint/sources/0`, where the stream may keep what it 
needs to recover
+    /// from a failure. It stays the same when the query restarts. It is a 
fully qualified
+    /// Hadoop path, whose characters are not escaped as in a URI, on a file 
system that the
+    /// library may not be able to access, such as `s3a`. Spark keeps what it 
needs there under
+    /// the names that start with `_spark`, which the library must not use.
+    pub checkpoint_location: String,
+}
+
+impl MicroBatchStreamInfo {
+    /// The information of a stream created outside Spark, for example in a 
test.
+    pub fn new(schema: SchemaRef, checkpoint_location: impl Into<String>) -> 
Self {
+        Self {
+            schema,
+            checkpoint_location: checkpoint_location.into(),
+        }
+    }
+}
+
+/// Finds new data and plans the micro-batches of a streaming query, on the 
driver.
+///
+/// Spark creates a stream when a streaming query starts, or restarts from its 
checkpoint,
+/// and drops it when the query stops. For each micro-batch, it asks for the
+/// [`latest_offset`](Self::latest_offset), and when that differs from the end 
of the
+/// previous micro-batch, [`plan`](Self::plan)s the data in between. Only the 
serialized
+/// factory and partitions of each plan reach the executors, which read them 
as those of a
+/// batch scan.
+///
+/// # Offsets
+///
+/// Spark stores offsets in the checkpoint of the query, as the JSON of
+/// [`Offset`](Self::Offset), and compares them by that JSON, so serialize a 
position to the
+/// same JSON each time: for example, use structs and `BTreeMap` rather than 
`HashMap`. A
+/// restarted query passes the offsets of its checkpoint, which an earlier 
version of the
+/// library may have written, to `latest_offset`, `plan`, and `commit`. When 
that version had a
+/// different `Offset` type, the same position may encode to different JSON, 
so Spark runs one
+/// micro-batch without rows.
+///
+/// # Admission control
+///
+/// [`default_read_limit`](Self::default_read_limit) limits the data of each 
micro-batch,
+/// typically with an option of the source. Spark passes the limit to 
`latest_offset`, except
+/// when a micro-batch reads all the available data, as with `Trigger.Once`. 
With
+/// `Trigger.AvailableNow`, a run reads the data that was available when it 
started: with a
+/// limit, in several micro-batches, whose latest offsets must not go beyond
+/// [`LatestOffsetInfo::run_end`].
+///
+/// # Lifecycle
+///
+/// - Calls never run concurrently.
+/// - After a call fails, including with a panic, Spark makes no other call: 
it stops the
+///   query, and drops the stream.
+/// - After a restart, Spark may plan the last range of the query again, so 
`plan` must
+///   return partitions that read the same data for the same range.
+pub trait MicroBatchStream: Send + 'static {
+    /// A position in the data, such as the next record of each partition of a 
log.
+    type Offset: Serialize + DeserializeOwned;
+
+    /// The reader factory of the micro-batches, which can be that of batch 
scans.
+    type Factory: PartitionReaderFactory;
+
+    /// False only for [`Unsupported`], from which the SDK derives the 
capabilities.
+    #[doc(hidden)]
+    const SUPPORTED: bool = true;
+
+    /// Returns the offset to start from when the query has no checkpoint: the 
first
+    /// micro-batch reads the data after it. Spark keeps it in the checkpoint, 
and asks only
+    /// when the checkpoint does not have it yet, so a query that restarts 
before its first
+    /// micro-batch is committed starts from the same offset.
+    fn initial_offset(&mut self) -> Result<Self::Offset>;
+
+    /// Returns the limit on the data of each micro-batch. Spark asks once, 
when the query
+    /// starts. The default, [`ReadLimit::AllAvailable`], reads all the 
available data in
+    /// each micro-batch.
+    fn default_read_limit(&self) -> Result<ReadLimit> {
+        Ok(ReadLimit::AllAvailable)
+    }
+
+    /// Returns the end of the next micro-batch: the offset of the most recent 
data after
+    /// [`LatestOffsetInfo::start`], within its limit, and not beyond its end 
of the run.
+    /// Return `start` when there is no new data. When there is, return an 
offset after
+    /// `start`, even if the next unit of data, such as a file, is larger than 
the limit:
+    /// Spark sees no new data otherwise, and never reads further.
+    ///
+    /// With a limit, Spark also asks without a limit for some micro-batches, 
to report the
+    /// progress of the query, so do not count the calls as micro-batches, or 
reserve data in
+    /// them.
+    fn latest_offset(&mut self, info: LatestOffsetInfo<Self::Offset>) -> 
Result<Self::Offset>;
+
+    /// Plans the micro-batch that reads the data after `start`, up to and 
including `end`.
+    fn plan(&mut self, start: Self::Offset, end: Self::Offset) -> 
Result<ScanPlan<Self::Factory>>;
+
+    /// Tells the stream that Spark has processed the data up to and including 
`end` and
+    /// will not read it again, so that the stream can release it.
+    fn commit(&mut self, _end: Self::Offset) -> Result<()> {
+        Ok(())
+    }
+}
+
+/// A limit on the data of a micro-batch.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[non_exhaustive]
+pub enum ReadLimit {
+    /// All the available data.
+    AllAvailable,
+    /// At most this number of rows, at least 1.
+    MaxRows(u64),
+}
+
+/// What Spark passes to ask a stream for its latest offset.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct LatestOffsetInfo<O> {
+    /// The offset that the next micro-batch starts after: the end of the 
previous one, or
+    /// the initial offset.
+    pub start: O,
+    /// The limit on the data after `start`: that of
+    /// [`MicroBatchStream::default_read_limit`], or 
[`ReadLimit::AllAvailable`] when Spark
+    /// reads all the available data, such as for the progress of the query or 
with
+    /// `Trigger.Once`.
+    pub limit: ReadLimit,
+    /// With `Trigger.AvailableNow` and a limit, the end of the run: the 
latest offset must not
+    /// go beyond it, so that the run reads the data that was available when 
it started. It is
+    /// not the end of the next micro-batch. `None` otherwise.
+    pub run_end: Option<O>,
+}
+
+impl<O> LatestOffsetInfo<O> {
+    /// A request without a limit, made outside Spark, for example in a test. 
Set
+    /// [`limit`](Self::limit) and [`run_end`](Self::run_end) for other 
requests.
+    pub fn new(start: O) -> Self {
+        Self {
+            start,
+            limit: ReadLimit::AllAvailable,
+            run_end: None,
+        }
+    }
+}
+
+// Batch writes: a BatchWrite coordinates the write on the driver, and a 
DataWriterFactory
+// opens a DataWriter for each task attempt on the executors.
+
+/// What Spark passes to create a batch write.
+#[derive(Debug, Clone)]
+#[non_exhaustive]
+pub struct WriteInfo {
+    /// The schema of the data to write.
+    pub schema: SchemaRef,
+    /// How the write changes the destination.
+    pub mode: WriteMode,
+}
+
+impl WriteInfo {
+    /// The information of a write created outside Spark, for example in a 
test.
+    pub fn new(schema: SchemaRef, mode: WriteMode) -> Self {
+        Self { schema, mode }
+    }
+}
+
+/// How a batch write changes the destination.

Review Comment:
   **Nit (P3):** `StreamingWriteInfo::mode` uses this enum too, with 
`WriteMode::Truncate` for the output mode "complete" (lib.rs:713-715), so this 
summary understates where it applies:
   
   ```suggestion
   /// How a write, or the write of a micro-batch, changes the destination.
   ```
   
   **Verification:**
   - **Inspection:** The documentation of WriteMode agrees with the 
documentation of the write modes that batch and streaming writes receive.



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