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

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

commit 140673c0aa7255bef0bbcf0bd213a76c0a673eb9
Author: Timofey Brunko <[email protected]>
AuthorDate: Thu Nov 19 22:39:33 2026 +0000

    Fix memory leak when replacing FFI schema names (#11932)
    
    # Which issue does this PR close?
    
    None — standalone bug fix.
    
    # Rationale for this change
    
    Repeated calls to `FFI_ArrowSchema::with_name` leak the previous name
    allocation. For example, `.with_name("a")?.with_name("b")?` leaves the
    allocation for `"a"` unreleased even after the schema is dropped.
    
    # What changes are included in this PR?
    
    Store the name as an `Option<CString>` in `SchemaPrivateData`, following
    the ownership model already used for metadata. Replacing the name drops
    the previous allocation, and releasing the schema drops the final name.
    
    Make `with_name` unsafe because it accesses this crate's private
    storage. Callers must guarantee that the schema was produced by this
    crate and retains its original `private_data`. Ownership is no longer
    inferred by comparing release callbacks.
    
    Update the internal call sites and document the safety requirements.
    
    # Are these changes tested?
    
    Added regression coverage for releasing the previous name on replacement
    and the final name when the schema is dropped.
    
    Additional coverage checks invalid names containing nul bytes, renaming
    after an FFI move, coexistence with metadata, and cleanup through a
    wrapped release callback.
    
    The regression tests and targeted FFI tests pass under Miri.
    
    # Are there any significant user-facing changes?
    
    Yes. `FFI_ArrowSchema::with_name` becomes an unsafe method, so callers
    must add an unsafe block and uphold its documented safety requirements.
    
    This is a breaking API change intended for the v61 development window.
    
    # AI assistance
    
    Codex identified the issue, helped implement the fix and regression
    tests, ran validation, and drafted this PR description.
---
 arrow-schema/src/ffi.rs | 102 +++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 79 insertions(+), 23 deletions(-)

diff --git a/arrow-schema/src/ffi.rs b/arrow-schema/src/ffi.rs
index e8e2acc6ab..f6b9843470 100644
--- a/arrow-schema/src/ffi.rs
+++ b/arrow-schema/src/ffi.rs
@@ -87,6 +87,7 @@ pub struct FFI_ArrowSchema {
 struct SchemaPrivateData {
     children: Box<[*mut FFI_ArrowSchema]>,
     dictionary: *mut FFI_ArrowSchema,
+    name: Option<CString>,
     metadata: Option<Vec<u8>>,
 }
 
@@ -99,9 +100,6 @@ unsafe extern "C" fn release_schema(schema: *mut 
FFI_ArrowSchema) {
 
     // take ownership back to release it.
     drop(unsafe { CString::from_raw(schema.format.cast_mut()) });
-    if !schema.name.is_null() {
-        drop(unsafe { CString::from_raw(schema.name.cast_mut()) });
-    }
     if !schema.private_data.is_null() {
         let private_data =
             unsafe { 
Box::from_raw(schema.private_data.cast::<SchemaPrivateData>()) };
@@ -158,6 +156,7 @@ impl FFI_ArrowSchema {
         let mut private_data = Box::new(SchemaPrivateData {
             children: children_ptr,
             dictionary: dictionary_ptr,
+            name: None,
             metadata: None,
         });
 
@@ -171,16 +170,30 @@ impl FFI_ArrowSchema {
         Ok(this)
     }
 
-    /// Set the name of the schema
-    pub fn with_name(mut self, name: &str) -> Result<Self, ArrowError> {
-        self.name = CString::new(name)
-            .map_err(|e| {
-                ArrowError::CDataInterface(format!(
-                    "Null byte at position {} not allowed in name",
-                    e.nul_position()
-                ))
-            })?
-            .into_raw();
+    /// Set the name of the schema.
+    ///
+    /// # Errors
+    ///
+    /// Returns an error if `name` contains an interior nul byte.
+    ///
+    /// # Safety
+    ///
+    /// `self` must be a live schema produced by this crate (e.g. via
+    /// [`FFI_ArrowSchema::try_new`] or a `TryFrom`), with its original
+    /// `private_data`. It must not be a foreign schema or
+    /// [`FFI_ArrowSchema::empty`]. This method interprets `private_data` as
+    /// this crate's private storage.
+    pub unsafe fn with_name(mut self, name: &str) -> Result<Self, ArrowError> {
+        let name = CString::new(name).map_err(|e| {
+            ArrowError::CDataInterface(format!(
+                "Null byte at position {} not allowed in name",
+                e.nul_position()
+            ))
+        })?;
+        // SAFETY: the caller guarantees that private_data is this crate's 
original
+        // SchemaPrivateData, and self owns it exclusively during this update.
+        let private_data = unsafe { &mut 
*self.private_data.cast::<SchemaPrivateData>() };
+        self.name = private_data.name.insert(name).as_ptr();
         Ok(self)
     }
 
@@ -880,11 +893,14 @@ impl TryFrom<&Field> for FFI_ArrowSchema {
             flags |= Flags::MAP_KEYS_SORTED;
         }
 
-        let schema = FFI_ArrowSchema::try_from(field.data_type())?
-            .with_name(field.name())?
-            .with_flags(flags)?;
+        let schema = FFI_ArrowSchema::try_from(field.data_type())?;
         // SAFETY: schema was just constructed by this crate.
-        unsafe { schema.with_metadata(field.metadata()) }
+        unsafe {
+            schema
+                .with_name(field.name())?
+                .with_flags(flags)?
+                .with_metadata(field.metadata())
+        }
     }
 }
 
@@ -1141,15 +1157,15 @@ mod tests {
             .into(),
         ];
 
-        let mut schema = FFI_ArrowSchema::try_new("b", vec![], None)
-            .unwrap()
-            .with_name("test")
-            .unwrap();
+        let schema = FFI_ArrowSchema::try_new("b", vec![], None).unwrap();
+        // SAFETY: schema was just constructed by this crate.
+        let mut schema = unsafe { schema.with_name("test") }.unwrap();
 
         for metadata in metadata_cases {
             // SAFETY: schema was constructed by this crate via try_new.
             schema = unsafe { schema.with_metadata(&metadata) }.unwrap();
             let field = Field::try_from(&schema).unwrap();
+            assert_eq!(field.name(), "test");
             assert_eq!(field.metadata(), &metadata);
         }
     }
@@ -1157,7 +1173,46 @@ mod tests {
     #[test]
     fn test_name_with_null_byte() {
         let schema = FFI_ArrowSchema::try_new("i", vec![], None).unwrap();
-        assert!(schema.with_name("ab\0cd").is_err());
+        // SAFETY: schema was just constructed by this crate.
+        let schema = unsafe { schema.with_name("original") }.unwrap();
+        // SAFETY: schema still has its original private_data.
+        assert!(unsafe { schema.with_name("ab\0cd") }.is_err());
+    }
+
+    #[test]
+    fn test_replacing_name_releases_previous_allocation() {
+        // Miri's leak check verifies that neither name allocation is leaked.
+        let schema = FFI_ArrowSchema::try_from(&DataType::Int32).unwrap();
+        // SAFETY: schema was just constructed by this crate.
+        let schema = unsafe { schema.with_name("first") }.unwrap();
+        assert_eq!(schema.name(), Some("first"));
+
+        // SAFETY: schema still has its original private_data.
+        let schema = unsafe { schema.with_name("second") }.unwrap();
+        assert_eq!(schema.name(), Some("second"));
+        drop(schema);
+    }
+
+    #[test]
+    fn test_with_name_after_move() {
+        let field = Field::new("before", DataType::Int32, true)
+            .with_metadata(HashMap::from([("key".to_owned(), 
"old".to_owned())]));
+        let mut original = FFI_ArrowSchema::try_from(&field).unwrap();
+        // SAFETY: original is an initialized, exclusively owned schema.
+        let schema = unsafe { FFI_ArrowSchema::from_raw(&raw mut original) };
+        assert!(original.release().is_none());
+        drop(original);
+
+        // SAFETY: moving the schema preserves its original private_data.
+        let schema = unsafe { schema.with_name("after") }.unwrap();
+        assert_eq!(schema.metadata().unwrap()["key"], "old");
+
+        // SAFETY: schema still has its original private_data.
+        let schema = unsafe { schema.with_metadata([("key", "updated")]) 
}.unwrap();
+        assert_eq!(schema.name(), Some("after"));
+        let expected = Field::new("after", DataType::Int32, true)
+            .with_metadata(HashMap::from([("key".to_owned(), 
"updated".to_owned())]));
+        assert_eq!(Field::try_from(&schema).unwrap(), expected);
     }
 
     #[test]
@@ -1193,7 +1248,8 @@ mod tests {
 
     #[test]
     fn test_wrap_release_callback() {
-        let mut schema = FFI_ArrowSchema::try_from(&DataType::Int32).unwrap();
+        let field = Field::new("wrapped", DataType::Int32, false);
+        let mut schema = FFI_ArrowSchema::try_from(&field).unwrap();
 
         let data = Box::new(WrapperData {
             original_release: schema.release(),

Reply via email to