tdcmeehan commented on code in PR #59520: URL: https://github.com/apache/spark/pull/59520#discussion_r4544803788
########## examples/src/main/rust/native-data-sink/src/lib.rs: ########## @@ -0,0 +1,1036 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You under the Apache License, Version 2.0 +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! A write-only JSONL sink demonstrating task staging, atomic manifest commits, and +//! exactly-once streaming writes. +//! +//! This example requires one local or shared POSIX filesystem. It is not an +//! object-store connector, a concurrent writer protocol, or a durable table format. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::{self, File, OpenOptions}; +use std::io::{BufWriter, ErrorKind, Write}; +use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{SystemTime, UNIX_EPOCH}; + +use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use serde::{Deserialize, Serialize}; +use spark_datasource::{ + AbortInfo, BatchWrite, Capabilities, CommitInfo, CreateInfo, DataSource, DataWriter, + DataWriterFactory, PartitionWriter, Result, StreamingAbortInfo, StreamingCommitInfo, + StreamingWrite, StreamingWriteInfo, TaskContext, Unsupported, WriteInfo, WriteMode, + WriterContext, +}; + +spark_datasource::export_data_source!(JsonSink); + +static NEXT_ID: AtomicU64 = AtomicU64::new(0); + +/// Construction and capability discovery do not access the filesystem. +pub struct JsonSink { + path: PathBuf, + readonly: bool, +} + +impl DataSource for JsonSink { + // A write-only sink. + type ScanBuilder = Unsupported; + type MicroBatchStream = Unsupported; + type BatchWrite = JsonWrite; + type StreamingWrite = JsonStreamingWrite; + + fn new(info: CreateInfo) -> Result<Self> { + let mut options = info.options; + let path = PathBuf::from( + options + .remove("path") + .ok_or("The path option is required")?, + ); + if !path.is_absolute() { + return Err("The path must be absolute and shared by the driver and executors".into()); + } + let readonly = match options.remove("readonly").as_deref() { + None | Some("false") => false, + Some("true") => true, + _ => return Err("The readonly option must be true or false".into()), + }; + // Spark passes the checkpoint and the name of a streaming query among the options of + // its sink. + options.remove("checkpointlocation"); + options.remove("queryname"); + if !options.is_empty() { + return Err( + format!("Unknown options: {:?}", options.keys().collect::<Vec<_>>()).into(), + ); + } + Ok(Self { path, readonly }) + } + + fn infer_schema(&self) -> Result<SchemaRef> { + Ok(sink_schema()) + } + + fn capabilities(&self) -> Capabilities { + if self.readonly { + // A write-only sink without its writes. + Capabilities::empty() + } else { + Capabilities::all() + } + } + + fn new_write(&self, info: WriteInfo) -> Result<JsonWrite> { + if self.readonly { + return Err("This sink is readonly".into()); + } + validate_schema(&info.schema)?; + JsonWrite::new(self.path.clone(), info.mode) + } + + fn new_streaming_write(&self, info: StreamingWriteInfo) -> Result<JsonStreamingWrite> { + Ok(JsonStreamingWrite { + write: self.new_write(WriteInfo::new(info.schema, info.mode))?, + query_id: info.query_id, + }) + } +} + +fn sink_schema() -> SchemaRef { + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, true), + Field::new("label", DataType::Utf8, true), + ])) +} + +fn validate_schema(schema: &Schema) -> Result<()> { + let fields = schema.fields(); + if fields.len() != 2 + || fields[0].name() != "id" + || fields[0].data_type() != &DataType::Int64 + || fields[1].name() != "label" + || fields[1].data_type() != &DataType::Utf8 + { + return Err("Expected columns id BIGINT, label STRING, in that order".into()); + } + Ok(()) +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +struct DataFile { + path: String, + rows: u64, +} + +#[derive(Debug, Deserialize, Serialize)] +struct Manifest { + version: u32, + files: Vec<DataFile>, + /// The last epoch that each streaming query committed, by the ID of the query. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + epochs: BTreeMap<String, i64>, +} + +impl Default for Manifest { + fn default() -> Self { + Self { + version: 1, + files: Vec::new(), + epochs: BTreeMap::new(), + } + } +} + +fn read_manifest(root: &Path) -> Result<Manifest> { + let file = match File::open(root.join("manifest.json")) { + Ok(file) => file, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Manifest::default()), + Err(error) => return Err(error.into()), + }; + let manifest: Manifest = serde_json::from_reader(file)?; + if manifest.version != 1 { + return Err("Unsupported sink manifest version".into()); + } + for file in &manifest.files { + let components = Path::new(&file.path).components().collect::<Vec<_>>(); + if components.len() != 3 + || components[0] != Component::Normal("objects".as_ref()) + || !components.iter().all(|c| matches!(c, Component::Normal(_))) + { + return Err("Invalid sink manifest data path".into()); + } + } + Ok(manifest) +} + +/// This lock is held for the whole write operation, including all task attempts. +struct WriteLock(PathBuf); + +impl WriteLock { + fn acquire(root: &Path) -> Result<Self> { + let path = root.join(".write-lock"); + match fs::create_dir(&path) { + Ok(()) => Ok(Self(path)), + Err(error) if error.kind() == ErrorKind::AlreadyExists => { + Err("Another write owns .write-lock; concurrent writes are unsupported".into()) + } + Err(error) => Err(error.into()), + } + } +} + +impl Drop for WriteLock { + fn drop(&mut self) { + let _ = fs::remove_dir(&self.0); + } +} + +pub struct JsonWrite { + root: PathBuf, + operation: String, + staging: PathBuf, + objects: PathBuf, + temporary_manifest: PathBuf, + previous: Manifest, + truncate: bool, + committed: bool, + sealed: bool, + lock: Option<WriteLock>, +} + +impl JsonWrite { + fn new(root: PathBuf, mode: WriteMode) -> Result<Self> { + if !cfg!(unix) { + return Err("This demo requires a POSIX filesystem".into()); + } + let truncate = match mode { + WriteMode::Append => false, + WriteMode::Truncate => true, + _ => return Err("Unsupported write mode".into()), + }; + fs::create_dir_all(&root)?; + let lock = WriteLock::acquire(&root)?; + let previous = read_manifest(&root)?; + fs::create_dir_all(root.join(".staging"))?; + fs::create_dir_all(root.join("objects"))?; + let staging = unique_directory(&root.join(".staging"))?; + let operation = staging.file_name().unwrap().to_str().unwrap().to_owned(); + Ok(Self { + objects: root.join("objects").join(&operation), + temporary_manifest: root.join(format!(".manifest-{operation}.json")), + root, + operation, + staging, + previous, + truncate, + committed: false, + sealed: false, + lock: Some(lock), + }) + } + + /// Publishes the winning attempts, and records the epoch of a streaming query. + fn publish( + &mut self, + messages: Vec<CommitMessage>, + epoch: Option<(String, i64)>, + ) -> Result<()> { + let mut filenames = BTreeSet::new(); + for (index, message) in messages.iter().enumerate() { + if message.operation != self.operation + || !is_filename(&message.filename) + || !filenames.insert(message.filename.clone()) + { + return Err("Invalid or duplicate task commit message".into()); + } + // Spark passes the message of partition i at position i. + if usize::try_from(message.partition).ok() != Some(index) { + return Err("A commit message does not match its partition".into()); + } + if !self.staging.join(&message.filename).is_file() { + return Err("A winning task's staged file is missing".into()); + } + } + + // Seal the entire operation directory. New attempts can no longer open + // a staged file, and existing losing files remain invisible to readers. + // A killed attempt that is still running, such as a losing speculative one, + // may have resolved the staging directory just before this rename and create + // its file after the sweep below. That file stays in the sealed directory, + // unlisted, so readers never see it. + fs::rename(&self.staging, &self.objects)?; + self.sealed = true; + for entry in fs::read_dir(&self.objects)? { + let entry = entry?; + if !filenames.contains(&entry.file_name().to_string_lossy().into_owned()) { + fs::remove_file(entry.path())?; + } + } + + let mut files = if self.truncate { + Vec::new() + } else { + self.previous.files.clone() + }; + files.extend(messages.into_iter().map(|message| DataFile { + path: format!("objects/{}/{}", self.operation, message.filename), + rows: message.rows, + })); + let mut epochs = self.previous.epochs.clone(); + if let Some((query_id, epoch_id)) = epoch { + epochs.insert(query_id, epoch_id); + } + let manifest = Manifest { + version: 1, + files, + epochs, + }; + let file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&self.temporary_manifest)?; + let mut writer = BufWriter::new(file); + serde_json::to_writer(&mut writer, &manifest)?; + writer.write_all(b"\n")?; + writer.flush()?; + writer.get_ref().sync_all()?; + drop(writer); + + // This single rename is the commit point. No existing data is deleted, + // including during truncate. No fallible work follows publication. + if let Err(error) = fs::rename(&self.temporary_manifest, self.root.join("manifest.json")) { + // A rename that reports an error, for example on a network filesystem that loses + // the reply, may still have taken effect, and then the new manifest lists the + // objects. Abort and Drop keep them: unlisted objects are invisible to readers. + self.sealed = false; + return Err(error.into()); + } + self.committed = true; + self.lock.take(); + Ok(()) + } + + /// Publishes nothing, for an epoch whose output is already published: removes what this + /// write staged, and releases the lock. + fn skip(&mut self) -> Result<()> { + let result = self.cleanup(); + // Nothing is left for Drop to clean. + self.committed = true; + self.lock.take(); + result + } + + fn cleanup(&self) -> Result<()> { + // Do not rely on commit messages: failed tasks and losing attempts may + // have staged files without returning a message to the driver. A killed + // attempt that is still running may also create a file while its directory + // is removed, which then fails this cleanup or leaves the directory behind. + let mut first_error = None; + for result in [ + fs::remove_dir_all(&self.staging), + if self.sealed { + fs::remove_dir_all(&self.objects) + } else { + Ok(()) + }, + fs::remove_file(&self.temporary_manifest), + ] { + if let Err(error) = result { + if error.kind() != ErrorKind::NotFound && first_error.is_none() { + first_error = Some(error); + } + } + } + match first_error { + Some(error) => Err(error.into()), + None => Ok(()), + } + } +} + +// Spark calls each method at most once, and never aborts a successful commit, so this +// coordinator does not track its own phase. +impl BatchWrite for JsonWrite { + type Factory = JsonWriterFactory; + type Message = CommitMessage; + + // The sink also supports overwrites. + const SUPPORTS_TRUNCATE: bool = true; + + fn new_writer_factory(&self) -> Result<JsonWriterFactory> { + Ok(JsonWriterFactory { + staging: self.staging.clone(), + operation: self.operation.clone(), + }) + } + + fn commit(&mut self, info: CommitInfo<CommitMessage>) -> Result<()> { + self.publish(info.messages, None) + } + + fn abort(&mut self, _info: AbortInfo<CommitMessage>) -> Result<()> { + let result = self.cleanup(); + self.lock.take(); + result + } +} + +/// The write of a micro-batch, exactly once: the manifest records the last epoch that each +/// streaming query committed, so an epoch that Spark commits again after a restart adds +/// nothing. +pub struct JsonStreamingWrite { + write: JsonWrite, + query_id: String, +} + +impl StreamingWrite for JsonStreamingWrite { + type Factory = JsonWriterFactory; + type Message = CommitMessage; + + // The output mode complete replaces the output of the previous micro-batches. + const SUPPORTS_TRUNCATE: bool = true; + + fn new_writer_factory(&self) -> Result<JsonWriterFactory> { + self.write.new_writer_factory() + } + + fn commit(&mut self, info: StreamingCommitInfo<CommitMessage>) -> Result<()> { + // The write holds the lock, so the manifest that it read is still the latest one. + let committed = self.write.previous.epochs.get(&self.query_id); + if committed.is_some_and(|last| *last >= info.epoch_id) { + return self.write.skip(); + } + self.write + .publish(info.messages, Some((self.query_id.clone(), info.epoch_id))) + } + + fn abort(&mut self, info: StreamingAbortInfo<CommitMessage>) -> Result<()> { + self.write.abort(AbortInfo::new(info.messages)) + } +} + +// A write can be dropped without abort, for example when creating or serializing its +// factory fails, so an unfinished write also cleans up here. +impl Drop for JsonWrite { + fn drop(&mut self) { + if !self.committed { + let _ = self.cleanup(); + } + } +} + +/// Serializable values only: the driver lock and open files stay on their hosts. +#[derive(Deserialize, Serialize)] +pub struct JsonWriterFactory { + staging: PathBuf, + operation: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CommitMessage { + operation: String, + filename: String, + partition: i32, + rows: u64, +} + +impl DataWriterFactory for JsonWriterFactory { + type Message = CommitMessage; + + fn open<'task>( + &self, + context: WriterContext<'task>, + ) -> Result<PartitionWriter<'task, Self::Message>> { + // Each batch has this schema, so the writer checks it once. + validate_schema(&context.schema)?; + let task = context.task; + if task.is_interrupted() { + return Err("Task cancelled before opening the sink".into()); + } + // Do not recreate staging: its absence means the driver sealed or + // aborted this operation. create_new also separates speculative tasks. + for _ in 0..16 { + let filename = format!( + "part-{}-attempt-{}-{}.jsonl", + task.partition_id(), + task.task_attempt_id(), + unique_id()? + ); + let path = self.staging.join(&filename); + match OpenOptions::new().write(true).create_new(true).open(&path) { + Ok(file) => { + return Ok(Box::new(JsonTaskWriter { + task, + path, + message: CommitMessage { + operation: self.operation.clone(), + filename, + partition: task.partition_id(), + rows: 0, + }, + writer: Some(BufWriter::new(file)), + committed: false, + })); + } + Err(error) if error.kind() == ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error.into()), + } + } + Err("Could not create a unique task attempt file".into()) + } +} + +#[derive(Serialize)] +struct Row<'a> { + id: Option<i64>, + label: Option<&'a str>, +} + +struct JsonTaskWriter<'task> { + task: TaskContext<'task>, + path: PathBuf, + message: CommitMessage, + writer: Option<BufWriter<File>>, + committed: bool, +} + +impl JsonTaskWriter<'_> { + fn discard_buffer(&mut self) { + if let Some(writer) = self.writer.take() { + // BufWriter normally flushes on drop; abort discards buffered rows. + let (file, _) = writer.into_parts(); + drop(file); + } + } +} + +// Spark never writes after a failure, a commit, or an abort, and commits at most once, so this +// writer does not track its phase. Abort may follow a commit whose message the SDK could not +// serialize, so it removes the file in every case. +impl DataWriter for JsonTaskWriter<'_> { + type Message = CommitMessage; + + fn write(&mut self, batch: RecordBatch) -> Result<()> { + let writer = self.writer.as_mut().ok_or("The task writer is closed")?; + let ids = batch + .column(0) + .as_any() + .downcast_ref::<Int64Array>() + .ok_or("The id column must be an Arrow int64 array")?; + let labels = batch + .column(1) + .as_any() + .downcast_ref::<StringArray>() + .ok_or("The label column must be an Arrow utf8 array")?; + for index in 0..batch.num_rows() { + if index % 1024 == 0 && self.task.is_interrupted() { + return Err("Task cancelled while writing the sink".into()); + } + let row = Row { + id: (!ids.is_null(index)).then(|| ids.value(index)), + label: (!labels.is_null(index)).then(|| labels.value(index)), + }; + serde_json::to_writer(&mut *writer, &row)?; + writer.write_all(b"\n")?; + } + self.message.rows = self + .message + .rows + .checked_add(batch.num_rows() as u64) + .ok_or("Task row count overflow")?; + Ok(()) + } + + fn commit(&mut self) -> Result<Self::Message> { + if self.task.is_interrupted() { + return Err("Task cancelled before committing the sink".into()); + } + let mut writer = self.writer.take().ok_or("The task writer is closed")?; + writer.flush()?; + writer.get_ref().sync_all()?; + drop(writer); + self.committed = true; + Ok(self.message.clone()) + } + + fn abort(&mut self) -> Result<()> { + self.discard_buffer(); + match fs::remove_file(&self.path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == ErrorKind::NotFound => Ok(()), + Err(error) => Err(error.into()), + } + } +} + +impl Drop for JsonTaskWriter<'_> { + fn drop(&mut self) { + if !self.committed { + self.discard_buffer(); + let _ = fs::remove_file(&self.path); + } + } +} + +fn is_filename(name: &str) -> bool { + let mut components = Path::new(name).components(); + matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none() +} + +fn unique_id() -> Result<String> { + Ok(format!( + "{}-{}-{}", + std::process::id(), + SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos(), + NEXT_ID.fetch_add(1, Ordering::Relaxed) + )) +} + +fn unique_directory(parent: &Path) -> Result<PathBuf> { + for _ in 0..16 { + let path = parent.join(unique_id()?); + match fs::create_dir(&path) { + Ok(()) => return Ok(path), + Err(error) if error.kind() == ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error.into()), + } + } + Err("Could not create a unique write operation directory".into()) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::AtomicBool; + + use super::*; + + struct TempDirectory(PathBuf); + + impl TempDirectory { + fn new() -> Self { + Self(unique_directory(&std::env::temp_dir()).unwrap()) + } + + fn source(&self) -> JsonSink { + JsonSink::new(info(&[("path", self.0.to_str().unwrap())])).unwrap() + } + } + + impl Drop for TempDirectory { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn info(options: &[(&str, &str)]) -> CreateInfo { + let options = options + .iter() + .map(|(key, value)| (key.to_string(), value.to_string())) + .collect(); + CreateInfo::new("rust_sdk_sink", options) + } + + fn new_write(source: &JsonSink, mode: WriteMode) -> Result<(JsonWrite, JsonWriterFactory)> { + let write = source.new_write(WriteInfo::new(sink_schema(), mode))?; + let factory = write.new_writer_factory()?; + Ok((write, factory)) + } + + fn open( + factory: &JsonWriterFactory, + partition: i32, + ) -> PartitionWriter<'static, CommitMessage> { + let task = TaskContext::for_testing().with_partition_id(partition); + factory + .open(WriterContext::new(sink_schema(), task)) + .unwrap() + } + + fn batch(ids: Vec<Option<i64>>) -> RecordBatch { + let labels = ids + .iter() + .map(|id| id.map(|id| format!("row-{id}"))) + .collect::<Vec<_>>(); + RecordBatch::try_new( + sink_schema(), + vec![ + Arc::new(Int64Array::from(ids)), + Arc::new(StringArray::from(labels)), + ], + ) + .unwrap() + } + + fn stage(factory: &JsonWriterFactory, partition: i32, ids: Vec<Option<i64>>) -> CommitMessage { + // Executors reconstruct the factory without the source or driver write. + let factory: JsonWriterFactory = + serde_json::from_slice(&serde_json::to_vec(factory).unwrap()).unwrap(); + let mut writer = open(&factory, partition); + writer.write(batch(ids)).unwrap(); + let message = writer.commit().unwrap(); + serde_json::from_slice(&serde_json::to_vec(&message).unwrap()).unwrap() + } + + fn committed_rows(path: &Path) -> Vec<serde_json::Value> { + read_manifest(path) + .unwrap() + .files + .iter() + .flat_map(|file| { + let text = fs::read_to_string(path.join(&file.path)).unwrap(); + let rows = text + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect::<Vec<_>>(); + assert_eq!(rows.len() as u64, file.rows); + rows + }) + .collect() + } + + fn new_streaming_write( + source: &JsonSink, + query_id: &str, + mode: WriteMode, + ) -> Result<(JsonStreamingWrite, JsonWriterFactory)> { + let info = StreamingWriteInfo::new(sink_schema(), mode, query_id); + let write = source.new_streaming_write(info)?; + let factory = write.new_writer_factory()?; + Ok((write, factory)) + } + + fn commit_epoch( + source: &JsonSink, + query_id: &str, + mode: WriteMode, + epoch_id: i64, + ids: Vec<Option<i64>>, + ) { + let (mut write, factory) = new_streaming_write(source, query_id, mode).unwrap(); + let message = stage(&factory, 0, ids); + write + .commit(StreamingCommitInfo::new(epoch_id, vec![message])) + .unwrap(); + } + + fn commit_ids(source: &JsonSink, mode: WriteMode, ids: Vec<Option<i64>>) { + let (mut write, factory) = new_write(source, mode).unwrap(); + let message = stage(&factory, 0, ids); + write.commit(CommitInfo::new(vec![message])).unwrap(); + } + + #[test] + fn append_publishes_all_committed_rows_and_preserves_nulls() { + let directory = TempDirectory::new(); + let source = directory.source(); + commit_ids(&source, WriteMode::Append, vec![Some(1), None]); + commit_ids(&source, WriteMode::Append, vec![Some(2)]); + assert_eq!( + committed_rows(&directory.0), + vec![ + serde_json::json!({"id": 1, "label": "row-1"}), + serde_json::json!({"id": null, "label": null}), + serde_json::json!({"id": 2, "label": "row-2"}), + ] + ); + assert_eq!(read_manifest(&directory.0).unwrap().files.len(), 2); + assert!(!directory.0.join(".write-lock").exists()); + } + + #[test] + fn truncate_replaces_manifest_but_retains_previously_published_files() { + let directory = TempDirectory::new(); + let source = directory.source(); + commit_ids(&source, WriteMode::Append, vec![Some(1)]); + let previous = read_manifest(&directory.0).unwrap(); + commit_ids(&source, WriteMode::Truncate, vec![Some(2)]); + assert_eq!( + committed_rows(&directory.0), + vec![serde_json::json!({"id": 2, "label": "row-2"})] + ); + assert!(directory.0.join(&previous.files[0].path).is_file()); + commit_ids(&source, WriteMode::Truncate, Vec::new()); + assert!(committed_rows(&directory.0).is_empty()); + } + + #[test] + fn driver_publishes_only_winning_attempts_and_removes_unreported_files() { + let directory = TempDirectory::new(); + let (mut write, factory) = new_write(&directory.source(), WriteMode::Append).unwrap(); + let winning = stage(&factory, 0, vec![Some(1)]); + let _losing = stage(&factory, 0, vec![Some(2)]); + let _missing_message = stage(&factory, 1, vec![Some(3)]); + assert_eq!(fs::read_dir(&write.staging).unwrap().count(), 3); + write.commit(CommitInfo::new(vec![winning])).unwrap(); + assert!(!write.staging.exists()); + assert_eq!(fs::read_dir(&write.objects).unwrap().count(), 1); + assert_eq!( + committed_rows(&directory.0), + vec![serde_json::json!({"id": 1, "label": "row-1"})] + ); + let task = TaskContext::for_testing(); + assert!(factory + .open(WriterContext::new(sink_schema(), task)) + .is_err()); + } + + #[test] + fn commit_rejects_a_message_at_the_position_of_another_partition() { + let directory = TempDirectory::new(); + let (mut write, factory) = new_write(&directory.source(), WriteMode::Append).unwrap(); + let message = stage(&factory, 1, vec![Some(1)]); + assert!(write.commit(CommitInfo::new(vec![message])).is_err()); + assert!(!directory.0.join("manifest.json").exists()); + } + + #[test] + fn commit_rejects_invalid_messages_and_leaves_the_manifest_unchanged() { + let directory = TempDirectory::new(); + let source = directory.source(); + commit_ids(&source, WriteMode::Append, vec![Some(1)]); + let before = fs::read(directory.0.join("manifest.json")).unwrap(); + let cases: [(fn(&JsonWrite, &mut [CommitMessage]), &str); 4] = [ Review Comment: The `rust-sdk` job fails on this line at d782be9. `cargo build` and all 81 tests pass, but `cargo clippy --workspace --all-targets --locked -- -D warnings` then stops with `clippy::type_complexity` ("very complex type used") here, so `cargo fmt --check` and `cargo doc` never run ([job 130871535267](https://github.com/gengliangwang/spark/actions/runs/43123679943/job/130871535267)). As clippy suggests, a `type` definition avoids it without an `allow`: ```suggestion type Invalidate = fn(&JsonWrite, &mut [CommitMessage]); let cases: [(Invalidate, &str); 4] = [ ``` -- 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]
