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

Xuanwo pushed a commit to branch xuanwo/fix-ocaml-ffi-safety
in repository https://gitbox.apache.org/repos/asf/opendal.git

commit 59ad8502f3324bfd29171daf6b097ea89006490b
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 08:55:03 2026 +0100

    fix(bindings/ocaml): validate UTF-8, avoid FFI panics, and drop shared &mut 
custom handles
---
 bindings/ocaml/src/lib.rs               |  17 +++--
 bindings/ocaml/src/operator/_type.rs    |   6 +-
 bindings/ocaml/src/operator/entry.rs    |   6 +-
 bindings/ocaml/src/operator/lister.rs   |  11 ++-
 bindings/ocaml/src/operator/metadata.rs |  16 ++---
 bindings/ocaml/src/operator/mod.rs      | 118 +++++++++++++++++-------------
 bindings/ocaml/src/operator/reader.rs   |   2 +-
 bindings/ocaml/src/operator/writer.rs   |  19 +++--
 bindings/ocaml/test/test.ml             | 123 +++++++++++++++++++++++++++++---
 9 files changed, 229 insertions(+), 89 deletions(-)

diff --git a/bindings/ocaml/src/lib.rs b/bindings/ocaml/src/lib.rs
index 219c3c86c0..268558b115 100644
--- a/bindings/ocaml/src/lib.rs
+++ b/bindings/ocaml/src/lib.rs
@@ -15,7 +15,6 @@
 // specific language governing permissions and limitations
 // under the License.
 
-use std::collections::BTreeMap;
 use std::collections::HashMap;
 use std::sync::LazyLock;
 
@@ -24,21 +23,21 @@ use ::opendal as od;
 mod operator;
 mod seek_from;
 
-static RUNTIME: LazyLock<tokio::runtime::Runtime> = LazyLock::new(|| {
+static RUNTIME: LazyLock<Result<tokio::runtime::Runtime, String>> = 
LazyLock::new(|| {
     tokio::runtime::Builder::new_multi_thread()
         .enable_all()
         .build()
-        .unwrap()
+        .map_err(|e| format!("failed to initialize tokio runtime: {e}"))
 });
 
-pub fn new_operator(
-    scheme: String,
-    map: BTreeMap<String, String>,
-) -> Result<od::Operator, od::Error> {
-    let hm: HashMap<String, String> = map.into_iter().collect();
-    od::Operator::via_iter(scheme, hm)
+pub fn new_operator(scheme: &str, map: HashMap<String, String>) -> 
Result<od::Operator, od::Error> {
+    od::Operator::via_iter(scheme, map)
 }
 
 pub fn map_res_error<T>(res: Result<T, od::Error>) -> Result<T, String> {
     res.map_err(|e| e.to_string())
 }
+
+pub fn parse_utf8<'a>(bytes: &'a [u8], field: &str) -> Result<&'a str, String> 
{
+    std::str::from_utf8(bytes).map_err(|e| format!("{field} is not valid 
UTF-8: {e}"))
+}
diff --git a/bindings/ocaml/src/operator/_type.rs 
b/bindings/ocaml/src/operator/_type.rs
index 10d715ba76..b892a2cf71 100644
--- a/bindings/ocaml/src/operator/_type.rs
+++ b/bindings/ocaml/src/operator/_type.rs
@@ -17,6 +17,8 @@
 
 // For ocaml-rs, the build order in the same build group is the order of the 
file names.
 // In order to use the type in the function in the generated ocaml file, it 
must be defined on the first generated file.
+use std::sync::Mutex;
+
 use super::*;
 
 #[ocaml::sig]
@@ -28,11 +30,11 @@ pub struct Reader(pub(crate) od::blocking::Reader);
 ocaml::custom!(Reader);
 
 #[ocaml::sig]
-pub struct Writer(pub(crate) od::blocking::Writer);
+pub struct Writer(pub(crate) Mutex<od::blocking::Writer>);
 ocaml::custom!(Writer);
 
 #[ocaml::sig]
-pub struct Lister(pub(crate) od::blocking::Lister);
+pub struct Lister(pub(crate) Mutex<od::blocking::Lister>);
 ocaml::custom!(Lister);
 
 #[ocaml::sig]
diff --git a/bindings/ocaml/src/operator/entry.rs 
b/bindings/ocaml/src/operator/entry.rs
index cf5b70a92c..c8d66c8670 100644
--- a/bindings/ocaml/src/operator/entry.rs
+++ b/bindings/ocaml/src/operator/entry.rs
@@ -19,18 +19,18 @@ use super::*;
 
 #[ocaml::func]
 #[ocaml::sig("entry -> string ")]
-pub fn entry_path(entry: &mut Entry) -> String {
+pub fn entry_path(entry: &Entry) -> String {
     entry.0.path().to_string()
 }
 
 #[ocaml::func]
 #[ocaml::sig("entry -> string ")]
-pub fn entry_name(entry: &mut Entry) -> String {
+pub fn entry_name(entry: &Entry) -> String {
     entry.0.name().to_string()
 }
 
 #[ocaml::func]
 #[ocaml::sig("entry -> metadata ")]
-pub fn entry_metadata(entry: &mut Entry) -> ocaml::Pointer<Metadata> {
+pub fn entry_metadata(entry: &Entry) -> ocaml::Pointer<Metadata> {
     Metadata(entry.0.metadata().clone()).into()
 }
diff --git a/bindings/ocaml/src/operator/lister.rs 
b/bindings/ocaml/src/operator/lister.rs
index 16dbf2a071..2e3c063b75 100644
--- a/bindings/ocaml/src/operator/lister.rs
+++ b/bindings/ocaml/src/operator/lister.rs
@@ -19,8 +19,15 @@ use super::*;
 
 #[ocaml::func]
 #[ocaml::sig("lister -> (entry option, string) Result.t ")]
-pub fn lister_next(lister: &mut Lister) -> 
Result<Option<ocaml::Pointer<Entry>>, String> {
-    match lister.0.next() {
+pub fn lister_next(lister: &Lister) -> Result<Option<ocaml::Pointer<Entry>>, 
String> {
+    let next = {
+        let mut lister = lister
+            .0
+            .lock()
+            .map_err(|_| "lister mutex poisoned".to_string())?;
+        lister.next()
+    };
+    match next {
         Some(Ok(entry)) => Ok(Some(Entry(entry).into())),
         Some(Err(e)) => Err(e.to_string()),
         None => Ok(None),
diff --git a/bindings/ocaml/src/operator/metadata.rs 
b/bindings/ocaml/src/operator/metadata.rs
index c7cd3d3c7f..9eecde69f1 100644
--- a/bindings/ocaml/src/operator/metadata.rs
+++ b/bindings/ocaml/src/operator/metadata.rs
@@ -19,49 +19,49 @@ use super::*;
 
 #[ocaml::func]
 #[ocaml::sig("metadata -> bool ")]
-pub fn metadata_is_file(metadata: &mut Metadata) -> bool {
+pub fn metadata_is_file(metadata: &Metadata) -> bool {
     metadata.0.is_file()
 }
 
 #[ocaml::func]
 #[ocaml::sig("metadata -> bool ")]
-pub fn metadata_is_dir(metadata: &mut Metadata) -> bool {
+pub fn metadata_is_dir(metadata: &Metadata) -> bool {
     metadata.0.is_dir()
 }
 
 #[ocaml::func]
 #[ocaml::sig("metadata -> int64 ")]
-pub fn metadata_content_length(metadata: &mut Metadata) -> u64 {
+pub fn metadata_content_length(metadata: &Metadata) -> u64 {
     metadata.0.content_length()
 }
 
 #[ocaml::func]
 #[ocaml::sig("metadata -> string option ")]
-pub fn metadata_content_md5(metadata: &mut Metadata) -> Option<String> {
+pub fn metadata_content_md5(metadata: &Metadata) -> Option<String> {
     metadata.0.content_md5().map(String::from)
 }
 
 #[ocaml::func]
 #[ocaml::sig("metadata -> string option ")]
-pub fn metadata_content_type(metadata: &mut Metadata) -> Option<String> {
+pub fn metadata_content_type(metadata: &Metadata) -> Option<String> {
     metadata.0.content_type().map(String::from)
 }
 
 #[ocaml::func]
 #[ocaml::sig("metadata -> string option ")]
-pub fn metadata_content_disposition(metadata: &mut Metadata) -> Option<String> 
{
+pub fn metadata_content_disposition(metadata: &Metadata) -> Option<String> {
     metadata.0.content_disposition().map(String::from)
 }
 
 #[ocaml::func]
 #[ocaml::sig("metadata -> string option ")]
-pub fn metadata_etag(metadata: &mut Metadata) -> Option<String> {
+pub fn metadata_etag(metadata: &Metadata) -> Option<String> {
     metadata.0.etag().map(String::from)
 }
 
 #[ocaml::func]
 #[ocaml::sig("metadata -> int64 option ")]
-pub fn metadata_last_modified(metadata: &mut Metadata) -> Option<i64> {
+pub fn metadata_last_modified(metadata: &Metadata) -> Option<i64> {
     metadata
         .0
         .last_modified()
diff --git a/bindings/ocaml/src/operator/mod.rs 
b/bindings/ocaml/src/operator/mod.rs
index e2ac6ec973..80a6c6791b 100644
--- a/bindings/ocaml/src/operator/mod.rs
+++ b/bindings/ocaml/src/operator/mod.rs
@@ -24,6 +24,9 @@ mod operator_info;
 mod reader;
 mod writer;
 
+use std::collections::LinkedList;
+use std::sync::Mutex;
+
 use _type::*;
 
 use super::*;
@@ -31,14 +34,22 @@ use super::*;
 #[ocaml::func]
 #[ocaml::sig("string -> (string * string) list -> (operator, string) Result.t 
")]
 pub fn operator(
-    scheme_str: String,
-    map: BTreeMap<String, String>,
+    scheme_str: &[u8],
+    map: LinkedList<(&[u8], &[u8])>,
 ) -> Result<ocaml::Pointer<Operator>, String> {
-    let op = map_res_error(new_operator(scheme_str, map))?;
+    let scheme = parse_utf8(scheme_str, "scheme")?;
+    let mut configs = HashMap::with_capacity(map.len());
+    for (key, value) in map {
+        let key = parse_utf8(key, "config key")?;
+        let value = parse_utf8(value, "config value")?;
+        configs.insert(key.to_owned(), value.to_owned());
+    }
+
+    let op = map_res_error(new_operator(scheme, configs))?;
 
-    let handle = RUNTIME.handle();
-    let _enter = handle.enter();
-    let blocking_op = od::blocking::Operator::new(op.clone()).unwrap();
+    let runtime = RUNTIME.as_ref().map_err(|e| e.clone())?;
+    let _enter = runtime.enter();
+    let blocking_op = map_res_error(od::blocking::Operator::new(op))?;
 
     Ok(Operator(blocking_op).into())
 }
@@ -46,109 +57,116 @@ pub fn operator(
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> (entry array, string) Result.t ")]
 pub fn blocking_list(
-    operator: &mut Operator,
-    path: String,
+    operator: &Operator,
+    path: &[u8],
 ) -> Result<Vec<ocaml::Pointer<Entry>>, String> {
+    let path = parse_utf8(path, "path")?;
     map_res_error(
         operator
             .0
-            .list(path.as_str())
+            .list(path)
             .map(|m| m.into_iter().map(|it| Entry(it).into()).collect()),
     )
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> (lister, string) Result.t ")]
-pub fn blocking_lister(
-    operator: &mut Operator,
-    path: String,
-) -> Result<ocaml::Pointer<Lister>, String> {
-    map_res_error(operator.0.lister(path.as_str())).map(|op| Lister(op).into())
+pub fn blocking_lister(operator: &Operator, path: &[u8]) -> 
Result<ocaml::Pointer<Lister>, String> {
+    let path = parse_utf8(path, "path")?;
+    map_res_error(operator.0.lister(path)).map(|op| 
Lister(Mutex::new(op)).into())
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> (metadata, string) Result.t ")]
-pub fn blocking_stat(
-    operator: &mut Operator,
-    path: String,
-) -> Result<ocaml::Pointer<Metadata>, String> {
-    map_res_error(operator.0.stat(path.as_str()).map(|m| Metadata(m).into()))
+pub fn blocking_stat(operator: &Operator, path: &[u8]) -> 
Result<ocaml::Pointer<Metadata>, String> {
+    let path = parse_utf8(path, "path")?;
+    map_res_error(operator.0.stat(path).map(|m| Metadata(m).into()))
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> (bool, string) Result.t ")]
-pub fn blocking_is_exist(operator: &mut Operator, path: String) -> 
Result<bool, String> {
-    map_res_error(operator.0.exists(path.as_str()))
+pub fn blocking_is_exist(operator: &Operator, path: &[u8]) -> Result<bool, 
String> {
+    let path = parse_utf8(path, "path")?;
+    map_res_error(operator.0.exists(path))
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> (bool, string) Result.t ")]
-pub fn blocking_create_dir(operator: &mut Operator, path: String) -> 
Result<bool, String> {
-    map_res_error(operator.0.create_dir(path.as_str())).map(|()| true)
+pub fn blocking_create_dir(operator: &Operator, path: &[u8]) -> Result<bool, 
String> {
+    let path = parse_utf8(path, "path")?;
+    map_res_error(operator.0.create_dir(path)).map(|()| true)
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> (char array, string) Result.t ")]
-pub fn blocking_read(operator: &mut Operator, path: String) -> Result<Vec<u8>, 
String> {
-    map_res_error(operator.0.read(path.as_str()).map(|v| v.to_vec()))
+pub fn blocking_read(operator: &Operator, path: &[u8]) -> Result<Vec<u8>, 
String> {
+    let path = parse_utf8(path, "path")?;
+    map_res_error(operator.0.read(path).map(|v| v.to_vec()))
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> (reader, string) Result.t ")]
-pub fn blocking_reader(
-    operator: &mut Operator,
-    path: String,
-) -> Result<ocaml::Pointer<Reader>, String> {
-    map_res_error(operator.0.reader(path.as_str())).map(|op| Reader(op).into())
+pub fn blocking_reader(operator: &Operator, path: &[u8]) -> 
Result<ocaml::Pointer<Reader>, String> {
+    let path = parse_utf8(path, "path")?;
+    map_res_error(operator.0.reader(path)).map(|op| Reader(op).into())
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> bytes -> (unit, string) Result.t ")]
-pub fn blocking_write(operator: &mut Operator, path: String, bs: &[u8]) -> 
Result<(), String> {
+pub fn blocking_write(operator: &Operator, path: &[u8], bs: &[u8]) -> 
Result<(), String> {
+    let path = parse_utf8(path, "path")?;
     // Core may retain the buffer after this call, but `bs` points into the 
OCaml
     // heap and can be mutated or moved by the GC. Hand over an owned copy.
-    map_res_error(operator.0.write(path.as_str(), bs.to_vec()).map(|_| ()))
+    map_res_error(operator.0.write(path, bs.to_vec()).map(|_| ()))
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> (writer, string) Result.t ")]
-pub fn blocking_writer(
-    operator: &mut Operator,
-    path: String,
-) -> Result<ocaml::Pointer<Writer>, String> {
-    map_res_error(operator.0.writer(path.as_str())).map(|op| Writer(op).into())
+pub fn blocking_writer(operator: &Operator, path: &[u8]) -> 
Result<ocaml::Pointer<Writer>, String> {
+    let path = parse_utf8(path, "path")?;
+    map_res_error(operator.0.writer(path)).map(|op| 
Writer(Mutex::new(op)).into())
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> string -> (unit, string) Result.t ")]
-pub fn blocking_copy(operator: &mut Operator, from: String, to: String) -> 
Result<(), String> {
-    map_res_error(operator.0.copy(from.as_str(), to.as_str())).map(|_| ())
+pub fn blocking_copy(operator: &Operator, from: &[u8], to: &[u8]) -> 
Result<(), String> {
+    let from = parse_utf8(from, "from")?;
+    let to = parse_utf8(to, "to")?;
+    map_res_error(operator.0.copy(from, to).map(|_| ()))
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> string -> (unit, string) Result.t ")]
-pub fn blocking_rename(operator: &mut Operator, from: String, to: String) -> 
Result<(), String> {
-    map_res_error(operator.0.rename(from.as_str(), to.as_str()))
+pub fn blocking_rename(operator: &Operator, from: &[u8], to: &[u8]) -> 
Result<(), String> {
+    let from = parse_utf8(from, "from")?;
+    let to = parse_utf8(to, "to")?;
+    map_res_error(operator.0.rename(from, to))
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> (unit, string) Result.t ")]
-pub fn blocking_delete(operator: &mut Operator, path: String) -> Result<(), 
String> {
-    map_res_error(operator.0.delete(path.as_str()))
+pub fn blocking_delete(operator: &Operator, path: &[u8]) -> Result<(), String> 
{
+    let path = parse_utf8(path, "path")?;
+    map_res_error(operator.0.delete(path))
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string array -> (unit, string) Result.t ")]
-pub fn blocking_remove(operator: &mut Operator, path: Vec<String>) -> 
Result<(), String> {
-    map_res_error(operator.0.delete_iter(path))
+pub fn blocking_remove(operator: &Operator, path: Vec<&[u8]>) -> Result<(), 
String> {
+    let paths = path
+        .into_iter()
+        .map(|p| parse_utf8(p, "path"))
+        .collect::<Result<Vec<_>, _>>()?;
+    map_res_error(operator.0.delete_iter(paths))
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> string -> (unit, string) Result.t ")]
-pub fn blocking_remove_all(operator: &mut Operator, path: String) -> 
Result<(), String> {
+pub fn blocking_remove_all(operator: &Operator, path: &[u8]) -> Result<(), 
String> {
     use opendal::options::DeleteOptions;
+    let path = parse_utf8(path, "path")?;
     map_res_error(operator.0.delete_options(
-        path.as_str(),
+        path,
         DeleteOptions {
             recursive: true,
             ..Default::default()
@@ -158,18 +176,18 @@ pub fn blocking_remove_all(operator: &mut Operator, path: 
String) -> Result<(),
 
 #[ocaml::func]
 #[ocaml::sig("operator -> (unit, string) Result.t ")]
-pub fn blocking_check(operator: &mut Operator) -> Result<(), String> {
+pub fn blocking_check(operator: &Operator) -> Result<(), String> {
     map_res_error(operator.0.check())
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator -> operator_info ")]
-pub fn operator_info(operator: &mut Operator) -> ocaml::Pointer<OperatorInfo> {
+pub fn operator_info(operator: &Operator) -> ocaml::Pointer<OperatorInfo> {
     OperatorInfo(operator.0.info()).into()
 }
 
 #[ocaml::func]
 #[ocaml::sig("operator_info -> capability ")]
-pub fn operator_info_capability(info: &mut OperatorInfo) -> 
ocaml::Pointer<Capability> {
+pub fn operator_info_capability(info: &OperatorInfo) -> 
ocaml::Pointer<Capability> {
     Capability(info.0.capability()).into()
 }
diff --git a/bindings/ocaml/src/operator/reader.rs 
b/bindings/ocaml/src/operator/reader.rs
index fa045c2821..5138a7b067 100644
--- a/bindings/ocaml/src/operator/reader.rs
+++ b/bindings/ocaml/src/operator/reader.rs
@@ -21,7 +21,7 @@ use super::*;
 
 #[ocaml::func]
 #[ocaml::sig("reader -> bytes -> int64 -> (int, string) Result.t ")]
-pub fn reader_pread(reader: &mut Reader, buf: &mut [u8], offset: i64) -> 
Result<usize, String> {
+pub fn reader_pread(reader: &Reader, buf: &mut [u8], offset: i64) -> 
Result<usize, String> {
     let offset =
         u64::try_from(offset).map_err(|_| format!("offset must be 
non-negative, got {offset}"))?;
     if buf.is_empty() {
diff --git a/bindings/ocaml/src/operator/writer.rs 
b/bindings/ocaml/src/operator/writer.rs
index 6ab3193ffb..3ae205a344 100644
--- a/bindings/ocaml/src/operator/writer.rs
+++ b/bindings/ocaml/src/operator/writer.rs
@@ -19,14 +19,25 @@ use super::*;
 
 #[ocaml::func]
 #[ocaml::sig("writer -> bytes -> (unit, string) Result.t ")]
-pub fn writer_write(writer: &mut Writer, bs: &[u8]) -> Result<(), String> {
+pub fn writer_write(writer: &Writer, bs: &[u8]) -> Result<(), String> {
+    let mut writer = writer
+        .0
+        .lock()
+        .map_err(|_| "writer mutex poisoned".to_string())?;
     // Core may retain the buffer after this call, but `bs` points into the 
OCaml
     // heap and can be mutated or moved by the GC. Hand over an owned copy.
-    map_res_error(writer.0.write(bs.to_vec()))
+    map_res_error(writer.write(bs.to_vec()))
 }
 
 #[ocaml::func]
 #[ocaml::sig("writer -> (metadata, string) Result.t ")]
-pub fn writer_close(writer: &mut Writer) -> Result<ocaml::Pointer<Metadata>, 
String> {
-    map_res_error(writer.0.close()).map(|m| Metadata(m).into())
+pub fn writer_close(writer: &Writer) -> Result<ocaml::Pointer<Metadata>, 
String> {
+    let meta = {
+        let mut writer = writer
+            .0
+            .lock()
+            .map_err(|_| "writer mutex poisoned".to_string())?;
+        map_res_error(writer.close())?
+    };
+    Ok(Metadata(meta).into())
 }
diff --git a/bindings/ocaml/test/test.ml b/bindings/ocaml/test/test.ml
index e976310155..00d87c88a0 100644
--- a/bindings/ocaml/test/test.ml
+++ b/bindings/ocaml/test/test.ml
@@ -35,6 +35,23 @@ let read_string bo path =
   test_check_result (Operator.read bo path)
   |> Array.to_seq |> Bytes.of_seq |> Bytes.to_string
 
+let contains_substring s sub =
+  let len_s = String.length s in
+  let len_sub = String.length sub in
+  let rec check i =
+    if i > len_s - len_sub then false
+    else if String.sub s i len_sub = sub then true
+    else check (i + 1)
+  in
+  if len_sub = 0 then true else check 0
+
+let assert_utf8_error label = function
+  | Ok _ -> assert_failure (label ^ ": expected UTF-8 error, got Ok")
+  | Error err ->
+      assert_bool
+        (Printf.sprintf "%s: expected UTF-8 error, got %S" label err)
+        (contains_substring err "UTF-8")
+
 (** Basic operator creation tests *)
 let test_new_block_operator _ = ignore new_test_block_operator
 
@@ -403,16 +420,6 @@ let test_complex_workflow test_ctxt =
   let readme_str =
     readme_data |> Array.to_seq |> Bytes.of_seq |> Bytes.to_string
   in
-  let contains_substring s sub =
-    let len_s = String.length s in
-    let len_sub = String.length sub in
-    let rec check i =
-      if i > len_s - len_sub then false
-      else if String.sub s i len_sub = sub then true
-      else check (i + 1)
-    in
-    if len_sub = 0 then true else check 0
-  in
   assert_bool "README should contain project info"
     (contains_substring readme_str "My Project");
 
@@ -430,6 +437,98 @@ let test_complex_workflow test_ctxt =
   (* Clean up *)
   ignore (test_check_result (Operator.remove_all bo "project/"))
 
+(** Test that non-UTF-8 strings return Result.Error instead of aborting across
+    FFI *)
+let test_invalid_utf8_rejected _ =
+  let bad = "\xff" in
+  assert_utf8_error "new_operator scheme" (Operator.new_operator bad []);
+  assert_utf8_error "new_operator config key"
+    (Operator.new_operator "memory" [ (bad, "value") ]);
+  assert_utf8_error "new_operator config value"
+    (Operator.new_operator "memory" [ ("key", bad) ]);
+  assert_utf8_error "new_operator shadowed invalid config value"
+    (Operator.new_operator "memory" [ ("root", bad); ("root", "/valid") ]);
+
+  let bo = new_test_memory_operator () in
+  ignore
+    (test_check_result
+       (Operator.write bo "keep.txt" (Bytes.of_string "keep me")));
+
+  assert_utf8_error "list" (Operator.list bo bad);
+  assert_utf8_error "lister" (Operator.lister bo bad);
+  assert_utf8_error "stat" (Operator.stat bo bad);
+  assert_utf8_error "is_exist" (Operator.is_exist bo bad);
+  assert_utf8_error "create_dir" (Operator.create_dir bo bad);
+  assert_utf8_error "read" (Operator.read bo bad);
+  assert_utf8_error "reader" (Operator.reader bo bad);
+  assert_utf8_error "write" (Operator.write bo bad (Bytes.of_string "data"));
+  assert_utf8_error "writer" (Operator.writer bo bad);
+  assert_utf8_error "copy from" (Operator.copy bo bad "dst");
+  assert_utf8_error "copy to" (Operator.copy bo "keep.txt" bad);
+  assert_utf8_error "rename from" (Operator.rename bo bad "dst");
+  assert_utf8_error "rename to" (Operator.rename bo "keep.txt" bad);
+  assert_utf8_error "delete" (Operator.delete bo bad);
+  assert_utf8_error "remove" (Operator.remove bo [| "keep.txt"; bad |]);
+  assert_equal true (Operator.is_exist bo "keep.txt" |> test_check_result);
+  assert_utf8_error "remove_all" (Operator.remove_all bo bad)
+
+(** Test that duplicate config keys keep last-wins behavior *)
+let test_config_duplicate_key_last_wins _ =
+  let bo =
+    Operator.new_operator "memory" [ ("root", "/first"); ("root", "/second") ]
+    |> test_check_result
+  in
+  let info = Operator.info bo in
+  assert_equal "/second/" (Operator.OperatorInfo.root info)
+
+(** Test interleaved operations across shared Operator/Writer/Reader/Lister
+    handles *)
+let test_shared_handles_interleaved _ =
+  let bo = new_test_memory_operator () in
+  ignore (test_check_result (Operator.create_dir bo "dir/"));
+  let writer = Operator.writer bo "dir/stream.txt" |> test_check_result in
+  ignore
+    (test_check_result
+       (Operator.Writer.write writer (Bytes.of_string "alpha-")));
+  ignore
+    (test_check_result
+       (Operator.write bo "dir/other.txt" (Bytes.of_string "x")));
+  ignore
+    (test_check_result (Operator.Writer.write writer (Bytes.of_string 
"beta")));
+  let close_meta = Operator.Writer.close writer |> test_check_result in
+  assert_equal 10L (Operator.Metadata.content_length close_meta);
+
+  let reader = Operator.reader bo "dir/stream.txt" |> test_check_result in
+  let buf_head = Bytes.create 5 in
+  let buf_tail = Bytes.create 4 in
+  assert_equal 5 (Operator.Reader.pread reader buf_head 0L |> 
test_check_result);
+  assert_equal 4 (Operator.Reader.pread reader buf_tail 6L |> 
test_check_result);
+  assert_equal "alpha" (Bytes.to_string buf_head);
+  assert_equal "beta" (Bytes.to_string buf_tail);
+
+  let lister = Operator.lister bo "dir/" |> test_check_result in
+  let rec collect acc =
+    match Operator.Lister.next lister with
+    | Ok (Some entry) ->
+        let meta = Operator.Entry.metadata entry in
+        let item =
+          ( Operator.Entry.path entry,
+            Operator.Entry.name entry,
+            Operator.Metadata.is_file meta )
+        in
+        collect (item :: acc)
+    | Ok None -> acc
+    | Error err -> assert_failure err
+  in
+  let entries = collect [] |> List.sort compare in
+  assert_equal
+    [
+      ("dir/", "dir/", false);
+      ("dir/other.txt", "other.txt", true);
+      ("dir/stream.txt", "stream.txt", true);
+    ]
+    entries
+
 let suite =
   "OCaml OpenDAL Test Suite"
   >::: [
@@ -455,6 +554,10 @@ let suite =
          "test_remove" >:: test_remove;
          "test_check" >:: test_check;
          "test_complex_workflow" >:: test_complex_workflow;
+         "test_invalid_utf8_rejected" >:: test_invalid_utf8_rejected;
+         "test_config_duplicate_key_last_wins"
+         >:: test_config_duplicate_key_last_wins;
+         "test_shared_handles_interleaved" >:: test_shared_handles_interleaved;
        ]
 
 let () = run_test_tt_main suite

Reply via email to