This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git


The following commit(s) were added to refs/heads/main by this push:
     new b9d56a732a Reject mismatched input schemas in FlightDataEncoder 
(#11293)
b9d56a732a is described below

commit b9d56a732a23ad001dc9a8b3c08586cd96cbc878
Author: RanaPriyansh <[email protected]>
AuthorDate: Sun Oct 18 04:00:25 2026 +0000

    Reject mismatched input schemas in FlightDataEncoder (#11293)
    
    # Which issue does this PR close?
    
    - Closes #4234.
    
    # Rationale for this change
    
    `FlightDataEncoder` can encode a batch whose input schema differs from
    the stream schema. In Hydrate mode, an extra column can be omitted
    without an error.
    
    # What changes are included in this PR?
    
    The encoder compares each batch's original schema with the supplied
    schema or the first batch's schema. It returns a schema error before
    dictionary hydration or batch encoding when schemas differ.
    
    # Are these changes tested?
    
    Public encoder-stream tests cover first and later batch mismatches in
    Hydrate and Resend modes. They cover extra columns, field names, types,
    nullability, and metadata. A matching-schema control round-trips changed
    dictionary values.
    
    `cargo test -p arrow-flight`, `cargo test -p arrow-flight
    --all-features`, the Flight SQL example tests, Clippy, format, and crate
    documentation checks pass locally.
    
    # Are there any user-facing changes?
    
    Streams with mismatched input batch schemas now return an error and end.
    Matching-schema streams and the encoded schema remain unchanged.
    
    Codex used. AI generated the implementation, tests, and PR description.
---
 arrow-flight/src/encode.rs          |  23 ++++-
 arrow-flight/tests/encode_decode.rs | 174 +++++++++++++++++++++++++++++++++++-
 2 files changed, 193 insertions(+), 4 deletions(-)

diff --git a/arrow-flight/src/encode.rs b/arrow-flight/src/encode.rs
index 1bc4b9f005..5ae84850be 100644
--- a/arrow-flight/src/encode.rs
+++ b/arrow-flight/src/encode.rs
@@ -22,7 +22,7 @@ use crate::{FlightData, FlightDescriptor, SchemaAsIpc, 
error::Result};
 use arrow_array::{Array, ArrayRef, RecordBatch, RecordBatchOptions, 
UnionArray};
 use arrow_ipc::writer::{DictionaryTracker, IpcDataGenerator, IpcWriteContext, 
IpcWriteOptions};
 
-use arrow_schema::{DataType, Field, FieldRef, Fields, Schema, SchemaRef, 
UnionMode};
+use arrow_schema::{ArrowError, DataType, Field, FieldRef, Fields, Schema, 
SchemaRef, UnionMode};
 use bytes::Bytes;
 use futures::{Stream, StreamExt, ready, stream::BoxStream};
 
@@ -38,7 +38,11 @@ use futures::{Stream, StreamExt, ready, stream::BoxStream};
 /// several have already been successfully produced.
 ///
 /// # Caveats
-/// 1. When [`DictionaryHandling`] is [`DictionaryHandling::Hydrate`],
+///
+/// 1. All input record batches must have the same schema. The first batch 
sets the
+///    expected schema unless [`FlightDataEncoderBuilder::with_schema`] 
supplies it.
+///    A batch with a different schema produces an error and ends the stream.
+/// 2. When [`DictionaryHandling`] is [`DictionaryHandling::Hydrate`],
 ///    [`DictionaryArray`]s are converted to their underlying types prior to
 ///    transport.
 ///    When [`DictionaryHandling`] is [`DictionaryHandling::Resend`], 
Dictionary [`FlightData`] is sent with every
@@ -223,6 +227,7 @@ impl FlightDataEncoderBuilder {
     /// is not specified, an encoded Schema message will be sent when
     /// the first [`RecordBatch`], if any, is encoded. Some clients
     /// expect a Schema message even if there is no data sent.
+    /// Every input batch must match this schema.
     pub fn with_schema(mut self, schema: SchemaRef) -> Self {
         self.schema = Some(schema);
         self
@@ -269,6 +274,8 @@ impl FlightDataEncoderBuilder {
 pub struct FlightDataEncoder {
     /// Input stream
     inner: BoxStream<'static, Result<RecordBatch>>,
+    /// Schema of input batches before dictionary handling
+    input_schema: Option<SchemaRef>,
     /// schema, set after the first batch
     schema: Option<SchemaRef>,
     /// Target maximum size of flight data
@@ -301,6 +308,7 @@ impl FlightDataEncoder {
     ) -> Self {
         let mut encoder = Self {
             inner,
+            input_schema: schema.clone(),
             schema: None,
             max_flight_data_size,
             encoder: FlightIpcEncoder::new(
@@ -362,6 +370,17 @@ impl FlightDataEncoder {
 
     /// Encodes batch into one or more `FlightData` messages in self.queue
     fn encode_batch(&mut self, batch: RecordBatch) -> Result<()> {
+        match &self.input_schema {
+            Some(expected) if expected.as_ref() != batch.schema_ref().as_ref() 
=> {
+                return Err(ArrowError::SchemaError(
+                    "Record batch schema does not match input 
schema".to_string(),
+                )
+                .into());
+            }
+            None => self.input_schema = Some(batch.schema()),
+            _ => {}
+        }
+
         let schema = match &self.schema {
             Some(schema) => schema.clone(),
             // encode the schema if this is the first time we have seen it
diff --git a/arrow-flight/tests/encode_decode.rs 
b/arrow-flight/tests/encode_decode.rs
index df0036fd05..efc62964b9 100644
--- a/arrow-flight/tests/encode_decode.rs
+++ b/arrow-flight/tests/encode_decode.rs
@@ -27,7 +27,7 @@ use arrow_flight::FlightDescriptor;
 use arrow_flight::flight_descriptor::DescriptorType;
 use arrow_flight::{
     decode::{DecodedPayload, FlightDataDecoder, FlightRecordBatchStream},
-    encode::FlightDataEncoderBuilder,
+    encode::{DictionaryHandling, FlightDataEncoderBuilder},
     error::FlightError,
 };
 use arrow_ipc::reader;
@@ -308,10 +308,180 @@ async fn test_mismatched_record_batch_schema() {
     let err = result.unwrap_err();
     assert_eq!(
         err.to_string(),
-        "Arrow error: Invalid argument error: number of columns(1) must match 
number of fields(2) in schema"
+        "Arrow error: Schema error: Record batch schema does not match input 
schema"
     );
 }
 
+#[tokio::test]
+async fn test_encoder_hydrate_rejects_first_batch_with_different_schema() {
+    assert_first_batch_schema_mismatch(DictionaryHandling::Hydrate).await;
+}
+
+#[tokio::test]
+async fn test_encoder_resend_rejects_first_batch_with_different_schema() {
+    assert_first_batch_schema_mismatch(DictionaryHandling::Resend).await;
+}
+
+async fn assert_first_batch_schema_mismatch(handling: DictionaryHandling) {
+    let batch = RecordBatch::try_from_iter(vec![(
+        "actual",
+        Arc::new(Int32Array::from(vec![1])) as ArrayRef,
+    )])
+    .unwrap();
+    let expected = Arc::new(Schema::new(vec![Field::new(
+        "expected",
+        DataType::Int32,
+        true,
+    )]));
+
+    let mut stream = FlightDataEncoderBuilder::new()
+        .with_dictionary_handling(handling)
+        .with_schema(expected)
+        .build(futures::stream::iter(vec![Ok(batch)]));
+
+    assert!(stream.next().await.unwrap().is_ok());
+    let error = stream.next().await.unwrap().unwrap_err();
+    assert_eq!(
+        error.to_string(),
+        "Arrow error: Schema error: Record batch schema does not match input 
schema"
+    );
+    assert!(stream.next().await.is_none());
+}
+
+#[tokio::test]
+async fn test_encoder_hydrate_rejects_subsequent_schema_changes() {
+    assert_subsequent_schema_changes_rejected(false).await;
+}
+
+#[tokio::test]
+async fn test_encoder_resend_rejects_subsequent_schema_changes() {
+    assert_subsequent_schema_changes_rejected(true).await;
+}
+
+async fn assert_subsequent_schema_changes_rejected(resend: bool) {
+    let values = Arc::new(Int32Array::from(vec![1])) as ArrayRef;
+    let original = RecordBatch::try_new(
+        Arc::new(Schema::new(vec![Field::new(
+            "value",
+            DataType::Int32,
+            false,
+        )])),
+        vec![values.clone()],
+    )
+    .unwrap();
+    let changed = [
+        RecordBatch::try_new(
+            Arc::new(Schema::new(vec![
+                Field::new("value", DataType::Int32, false),
+                Field::new("extra", DataType::Int32, false),
+            ])),
+            vec![values.clone(), values.clone()],
+        )
+        .unwrap(),
+        RecordBatch::try_new(
+            Arc::new(Schema::new(vec![Field::new(
+                "renamed",
+                DataType::Int32,
+                false,
+            )])),
+            vec![values.clone()],
+        )
+        .unwrap(),
+        RecordBatch::try_new(
+            Arc::new(Schema::new(vec![Field::new(
+                "value",
+                DataType::Int32,
+                true,
+            )])),
+            vec![values.clone()],
+        )
+        .unwrap(),
+        RecordBatch::try_new(
+            Arc::new(Schema::new(vec![
+                Field::new("value", DataType::Int32, false)
+                    .with_metadata(HashMap::from([("key".to_string(), 
"changed".to_string())])),
+            ])),
+            vec![values.clone()],
+        )
+        .unwrap(),
+        RecordBatch::try_new(
+            Arc::new(Schema::new(vec![Field::new(
+                "value",
+                DataType::Int64,
+                false,
+            )])),
+            vec![Arc::new(arrow_array::Int64Array::from(vec![1])) as ArrayRef],
+        )
+        .unwrap(),
+        RecordBatch::try_new(
+            Arc::new(
+                original
+                    .schema()
+                    .as_ref()
+                    .clone()
+                    .with_metadata(HashMap::from([(
+                        "schema_key".to_string(),
+                        "changed".to_string(),
+                    )])),
+            ),
+            vec![values.clone()],
+        )
+        .unwrap(),
+    ];
+
+    for batch in &changed {
+        let handling = if resend {
+            DictionaryHandling::Resend
+        } else {
+            DictionaryHandling::Hydrate
+        };
+        let mut stream = FlightDataEncoderBuilder::new()
+            .with_dictionary_handling(handling)
+            .build(futures::stream::iter(vec![
+                Ok(original.clone()),
+                Ok(batch.clone()),
+            ]));
+
+        assert!(stream.next().await.unwrap().is_ok());
+        assert!(stream.next().await.unwrap().is_ok());
+        let error = stream.next().await.unwrap().unwrap_err();
+        assert_eq!(
+            error.to_string(),
+            "Arrow error: Schema error: Record batch schema does not match 
input schema"
+        );
+        assert!(stream.next().await.is_none());
+    }
+}
+
+#[tokio::test]
+async fn test_encoder_accepts_changed_dictionary_values_with_same_schema() {
+    let batches = vec![make_dictionary_batch(5), make_dictionary_batch(9)];
+    let schema = batches[0].schema();
+
+    for handling in [DictionaryHandling::Hydrate, DictionaryHandling::Resend] {
+        let resend = handling == DictionaryHandling::Resend;
+        let stream = FlightDataEncoderBuilder::new()
+            .with_dictionary_handling(handling)
+            .with_schema(schema.clone())
+            .build(futures::stream::iter(batches.clone().into_iter().map(Ok)));
+        let decoded: Vec<_> = 
FlightRecordBatchStream::new_from_flight_data(stream)
+            .try_collect()
+            .await
+            .unwrap();
+        assert_eq!(decoded.len(), batches.len());
+        if resend {
+            assert_eq!(decoded, batches);
+        } else {
+            let hydrated_schema = 
Arc::new(prepare_schema_for_flight(schema.as_ref()));
+            let expected: Vec<_> = batches
+                .iter()
+                .map(|batch| prepare_batch_for_flight(batch, 
hydrated_schema.clone()).unwrap())
+                .collect();
+            assert_eq!(decoded, expected);
+        }
+    }
+}
+
 #[tokio::test]
 async fn test_chained_streams_batch_decoder() {
     let batch1 = make_primitive_batch(5);

Reply via email to