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

Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git


The following commit(s) were added to refs/heads/main by this push:
     new 2f35a5aec3 fix(services/fs): honor start_after for list (#8588)
2f35a5aec3 is described below

commit 2f35a5aec3f03a1eb1c2d7896dd6a118d77cb6c9
Author: Xuanwo <[email protected]>
AuthorDate: Sun Nov 22 05:27:25 2026 +0800

    fix(services/fs): honor start_after for list (#8588)
    
    * fix(services/fs): honor start_after for list
    
    Return entries strictly after the marker for both flat and recursive 
listings. Sort each visited directory so callers can resume using the last 
returned path.
    
    Preserve encoded path comparisons for FS offsets in the object_store 
adapter.
    
    Co-Authored-By: Mola-maker <[email protected]>
    
    * fix(services/fs): skip unreadable directories during recursive listing
    
    ---------
    
    Co-authored-by: Mola-maker <[email protected]>
---
 bindings/ruby/test/lister_test.rb          |   6 +-
 core/services/fs/src/backend.rs            |   9 +-
 core/services/fs/src/docs.md               |  13 ++
 core/services/fs/src/lister.rs             | 357 +++++++++++++++++++++--------
 core/services/fs/src/reader.rs             |  33 ---
 core/services/fs/tests/list_start_after.rs |  97 ++++++++
 integrations/object_store/src/store.rs     |  38 ++-
 7 files changed, 420 insertions(+), 133 deletions(-)

diff --git a/bindings/ruby/test/lister_test.rb 
b/bindings/ruby/test/lister_test.rb
index bfeb043f50..895886d8b1 100644
--- a/bindings/ruby/test/lister_test.rb
+++ b/bindings/ruby/test/lister_test.rb
@@ -68,10 +68,10 @@ class ListerTest < ActiveSupport::TestCase
   end
 
   test "lists the directory with start_after" do
-    lister = @op.list("", start_after: "sub/")
+    lister = @op.list("", start_after: "sample")
 
-    lists = lister.map(&:to_h).map { |e| e[:path] }.sort
+    lists = lister.map(&:to_h).map { |e| e[:path] }
 
-    assert_equal ["/", "sample", "sub/"], lists # fs backend doesn't support 
start_after
+    assert_equal ["sub/"], lists
   end
 end
diff --git a/core/services/fs/src/backend.rs b/core/services/fs/src/backend.rs
index 5689803ff7..94901e9d80 100644
--- a/core/services/fs/src/backend.rs
+++ b/core/services/fs/src/backend.rs
@@ -25,6 +25,7 @@ use super::FS_SCHEME;
 use super::config::FsConfig;
 use super::core::*;
 use super::deleter::FsDeleter;
+use super::lister::FsLister;
 use super::reader::*;
 use opendal_core::raw::*;
 use opendal_core::*;
@@ -152,6 +153,8 @@ impl Builder for FsBuilder {
                     delete_with_recursive: true,
 
                     list: true,
+                    list_with_recursive: true,
+                    list_with_start_after: true,
 
                     copy: true,
                     rename: true,
@@ -177,7 +180,7 @@ pub struct FsBackend {
 impl Service for FsBackend {
     type Reader = oio::PositionReader<FsReader>;
     type Writer = FsLazyWriter;
-    type Lister = FsLazyLister;
+    type Lister = FsLister;
     type Deleter = oio::OneShotDeleter<FsDeleter>;
     type Copier = oio::OneShotCopier;
     type Composer = ();
@@ -225,8 +228,8 @@ impl Service for FsBackend {
         Ok(oio::OneShotDeleter::new(FsDeleter::new(self.core.clone())))
     }
 
-    fn list(&self, _ctx: &OperationContext, path: &str, _: OpList) -> 
Result<Self::Lister> {
-        Ok(FsLazyLister::new(self.core.clone(), path))
+    fn list(&self, _ctx: &OperationContext, path: &str, args: OpList) -> 
Result<Self::Lister> {
+        Ok(FsLister::new(self.core.clone(), path, args))
     }
 
     fn copy(
diff --git a/core/services/fs/src/docs.md b/core/services/fs/src/docs.md
index 98f8efc67e..c66a330a1a 100644
--- a/core/services/fs/src/docs.md
+++ b/core/services/fs/src/docs.md
@@ -15,6 +15,19 @@ Depending on its configuration and the backing system, this 
service can expose:
 Inspect the effective capability set with [`opendal_core::Operator::info`] and
 [`opendal_core::OperatorInfo::capability`] after building an operator.
 
+## List
+
+When set, `start_after` returns entries in lexicographic order and excludes
+paths at or before the marker in both non-recursive and recursive listings.
+Pass a path relative to the operator root, including the trailing `/` for a
+directory entry. Pass an empty marker to start a sorted listing from the
+beginning.
+
+With `start_after`, the service reads and sorts each visited directory before
+yielding its entries. This can increase latency and memory usage for large
+directories. With `start_after` unset, the traversal follows the order of
+entries from the filesystem.
+
 ## Delete
 
 Deleting a symbolic link removes the link and preserves its target, even with
diff --git a/core/services/fs/src/lister.rs b/core/services/fs/src/lister.rs
index 1240f359b2..261e6fee64 100644
--- a/core/services/fs/src/lister.rs
+++ b/core/services/fs/src/lister.rs
@@ -16,135 +16,312 @@
 // under the License.
 
 use std::path::Path;
-use std::path::PathBuf;
+use std::sync::Arc;
+use std::vec::IntoIter;
 
 use opendal_core::EntryMode;
+use opendal_core::ErrorKind;
 use opendal_core::MetadataBuilder;
 use opendal_core::Result;
 use opendal_core::raw::*;
+use tokio::fs::ReadDir;
 
-pub struct FsLister<P> {
-    root: PathBuf,
+use super::core::FsCore;
 
-    current_path: Option<String>,
+pub struct FsLister {
+    core: Arc<FsCore>,
+    prefix: String,
+    recursive: bool,
+    start_after: Option<String>,
+    next_dir: Option<oio::Entry>,
+    active: Vec<DirectoryEntries>,
+}
 
-    rd: P,
+enum DirectoryEntries {
+    Streaming {
+        reader: ReadDir,
+        after_children: Option<oio::Entry>,
+    },
+    Sorted(IntoIter<oio::Entry>),
 }
 
-impl<P> FsLister<P> {
-    pub fn new(root: &Path, path: &str, rd: P) -> Self {
+impl FsLister {
+    pub(super) fn new(core: Arc<FsCore>, path: &str, args: OpList) -> Self {
+        let directory = if path.ends_with('/') {
+            path
+        } else {
+            get_parent(path)
+        };
+        let prefix = if path == "/" { "" } else { path };
         Self {
-            root: root.to_owned(),
-            current_path: Some(path.to_string()),
-            rd,
+            core,
+            prefix: prefix.to_string(),
+            recursive: args.recursive(),
+            start_after: args.start_after().map(str::to_owned),
+            next_dir: Some(oio::Entry::new(directory, 
MetadataBuilder::dir().build())),
+            active: Vec::new(),
         }
     }
 }
 
-/// # Safety
-///
-/// We will only take `&mut Self` reference for FsLister.
-unsafe impl<P> Sync for FsLister<P> {}
-
-impl oio::List for FsLister<tokio::fs::ReadDir> {
+impl oio::List for FsLister {
     async fn next(&mut self) -> Result<Option<oio::Entry>> {
         loop {
-            // since list should return path itself, we return it first
-            if let Some(path) = self.current_path.take() {
-                let e = oio::Entry::new(path.as_str(), 
MetadataBuilder::dir().build());
-                return Ok(Some(e));
-            }
+            if let Some(dir) = &self.next_dir {
+                // A discovered child always has an active parent directory.
+                let discovered_child = !self.active.is_empty();
+                let mut reader = match self.core.fs_list(dir.path()).await {
+                    Ok(Some(reader)) => reader,
+                    Ok(None) => {
+                        if discovered_child {
+                            log::warn!(
+                                "FS recursive listing skipped missing 
directory: {}",
+                                dir.path()
+                            );
+                        }
+                        self.next_dir = None;
+                        continue;
+                    }
+                    Err(err)
+                        if discovered_child
+                            && matches!(
+                                err.kind(),
+                                ErrorKind::PermissionDenied | 
ErrorKind::NotFound
+                            ) =>
+                    {
+                        log::warn!(
+                            "FS recursive listing skipped directory {}: {err}",
+                            dir.path()
+                        );
+                        self.next_dir = None;
+                        continue;
+                    }
+                    Err(err) => return Err(err),
+                };
+                let include_dir = dir.path().starts_with(&self.prefix)
+                    && self
+                        .start_after
+                        .as_deref()
+                        .is_none_or(|marker| dir.path() > marker);
 
-            let de = match self.rd.next_entry().await {
-                Ok(Some(de)) => de,
-                Ok(None) => return Ok(None),
-                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
-                    // Directory can be removed during listing; stop 
gracefully.
-                    return Ok(None);
+                if let Some(marker) = &self.start_after {
+                    // Keep next_dir until the buffer is complete, so an error 
or
+                    // cancelled read leaves the entire directory available to 
retry.
+                    let mut entries = Vec::new();
+                    while let Some(entry) = next_entry(
+                        &mut reader,
+                        &self.core.root,
+                        &self.prefix,
+                        Some(marker),
+                        self.recursive,
+                    )
+                    .await?
+                    {
+                        entries.push(entry);
+                    }
+                    let mut dir = self.next_dir.take().filter(|_| include_dir);
+                    // Unlike other directory paths, "/" is not a prefix of its
+                    // children. It can sort between entries in the root.
+                    if dir.as_ref().is_some_and(|entry| entry.path() == "/") {
+                        entries.extend(dir.take());
+                    }
+                    entries.sort_unstable_by(|a, b| a.path().cmp(b.path()));
+                    self.active
+                        .push(DirectoryEntries::Sorted(entries.into_iter()));
+                    // A non-root directory sorts before all its descendants.
+                    if dir.is_some() {
+                        return Ok(dir);
+                    }
+                } else {
+                    let mut dir = self.next_dir.take().filter(|_| include_dir);
+                    // Keep bottom-up ordering for ordinary recursive listings.
+                    let after_children = if self.recursive { dir.take() } else 
{ None };
+                    self.active.push(DirectoryEntries::Streaming {
+                        reader,
+                        after_children,
+                    });
+                    if dir.is_some() {
+                        return Ok(dir);
+                    }
                 }
-                Err(e) => return Err(new_std_io_error(e)),
-            };
+            }
 
-            let entry_path = de.path();
-            let raw = entry_path
-                .strip_prefix(&self.root)
-                .expect("cannot fail because the prefix is iterated")
-                .to_string_lossy();
-            #[cfg(windows)]
-            let raw = raw.replace('\\', "/");
-            let rel_path = normalize_path(&raw);
-
-            let ft = match de.file_type().await {
-                Ok(ft) => ft,
-                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
-                    // Entry can be deleted between readdir and stat calls.
-                    continue;
-                }
-                Err(e) => return Err(new_std_io_error(e)),
-            };
-            let (path, mode) = if ft.is_dir() {
-                // Make sure we are returning the correct path.
-                (&format!("{rel_path}/"), EntryMode::DIR)
-            } else if ft.is_file() {
-                (&rel_path, EntryMode::FILE)
-            } else {
-                (&rel_path, EntryMode::Unknown)
+            let Some(directory) = self.active.last_mut() else {
+                return Ok(None);
             };
-
-            let de_metadata = match de.metadata().await {
-                Ok(de_metadata) => de_metadata,
-                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
-                    // Entry can be deleted between readdir and metadata calls.
-                    continue;
+            let entry = match directory {
+                DirectoryEntries::Streaming { reader, .. } => {
+                    next_entry(reader, &self.core.root, &self.prefix, None, 
self.recursive).await?
                 }
-                Err(e) => return Err(new_std_io_error(e)),
+                DirectoryEntries::Sorted(entries) => entries.next(),
             };
-            let last_modified = match de_metadata.modified() {
-                Ok(v) => v,
-                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
-                    continue;
+            let Some(entry) = entry else {
+                if let Some(DirectoryEntries::Streaming {
+                    after_children: Some(dir),
+                    ..
+                }) = self.active.pop()
+                {
+                    return Ok(Some(dir));
                 }
-                Err(e) => return Err(new_std_io_error(e)),
-            };
-            let mut metadata = match mode {
-                EntryMode::FILE => MetadataBuilder::file(de_metadata.len()),
-                EntryMode::DIR => MetadataBuilder::dir(),
-                EntryMode::Unknown => MetadataBuilder::unknown(),
+                continue;
             };
-            metadata.last_modified(Timestamp::try_from(last_modified)?);
+            if self.recursive && entry.mode().is_dir() && entry.path() != "/" {
+                self.next_dir = Some(entry);
+            } else {
+                return Ok(Some(entry));
+            }
+        }
+    }
+}
+
+async fn next_entry(
+    reader: &mut ReadDir,
+    root: &Path,
+    prefix: &str,
+    start_after: Option<&str>,
+    recursive: bool,
+) -> Result<Option<oio::Entry>> {
+    loop {
+        let de = match reader.next_entry().await {
+            Ok(Some(de)) => de,
+            Ok(None) => return Ok(None),
+            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+                // Directory can be removed during listing; stop gracefully.
+                return Ok(None);
+            }
+            Err(e) => return Err(new_std_io_error(e)),
+        };
+
+        let entry_path = de.path();
+        let raw = entry_path
+            .strip_prefix(root)
+            .expect("cannot fail because the prefix is iterated")
+            .to_string_lossy();
+        #[cfg(windows)]
+        let raw = raw.replace('\\', "/");
+        let rel_path = normalize_path(&raw);
+
+        let ft = match de.file_type().await {
+            Ok(ft) => ft,
+            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+                // Entry can be deleted between readdir and stat calls.
+                continue;
+            }
+            Err(e) => return Err(new_std_io_error(e)),
+        };
+        let (path, mode) = if ft.is_dir() {
+            // Make sure we are returning the correct path.
+            (&format!("{rel_path}/"), EntryMode::DIR)
+        } else if ft.is_file() {
+            (&rel_path, EntryMode::FILE)
+        } else {
+            (&rel_path, EntryMode::Unknown)
+        };
 
-            return Ok(Some(oio::Entry::new(path, metadata.build())));
+        if !path.starts_with(prefix) {
+            continue;
+        }
+        // A directory containing the marker can still have later children.
+        if let Some(marker) = start_after
+            && path.as_str() <= marker
+            && !(recursive && mode.is_dir() && marker.starts_with(path))
+        {
+            continue;
         }
+
+        let de_metadata = match de.metadata().await {
+            Ok(de_metadata) => de_metadata,
+            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+                // Entry can be deleted between readdir and metadata calls.
+                continue;
+            }
+            Err(e) => return Err(new_std_io_error(e)),
+        };
+        let last_modified = match de_metadata.modified() {
+            Ok(v) => v,
+            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+                continue;
+            }
+            Err(e) => return Err(new_std_io_error(e)),
+        };
+        let mut metadata = match mode {
+            EntryMode::FILE => MetadataBuilder::file(de_metadata.len()),
+            EntryMode::DIR => MetadataBuilder::dir(),
+            EntryMode::Unknown => MetadataBuilder::unknown(),
+        };
+        metadata.last_modified(Timestamp::try_from(last_modified)?);
+
+        return Ok(Some(oio::Entry::new(path, metadata.build())));
     }
 }
 
 #[cfg(all(test, unix))]
 mod tests {
-    use super::*;
-    use opendal_core::raw::oio::List;
+    use std::fs;
+    use std::os::unix::fs::PermissionsExt;
 
-    #[tokio::test]
-    async fn list_file_with_backslash_in_name() {
-        let root = 
std::env::temp_dir().join("opendal-test-fs-lister-backslash");
-        let _ = std::fs::remove_dir_all(&root);
-        std::fs::create_dir_all(&root).unwrap();
+    use opendal_core::EntryMode;
+    use opendal_core::ErrorKind;
+    use opendal_core::Operator;
 
-        std::fs::write(root.join("has\\slash"), b"data").unwrap();
+    use crate::Fs;
 
-        let rd = tokio::fs::read_dir(&root).await.unwrap();
-        let mut lister = FsLister::new(&root, "/", rd);
-
-        let first = lister.next().await.unwrap().unwrap();
-        assert_eq!(first.mode(), EntryMode::DIR);
+    #[tokio::test]
+    async fn list_file_with_backslash_in_name() {
+        let root = tempfile::tempdir().unwrap();
+        std::fs::write(root.path().join("has\\slash"), b"data").unwrap();
+        let op = 
Operator::new(Fs::default().root(root.path().to_str().unwrap())).unwrap();
 
-        let file_entry = lister.next().await.unwrap().unwrap();
-        assert_eq!(file_entry.mode(), EntryMode::FILE);
+        let entries = op.list("/").await.unwrap();
+        assert_eq!(entries.len(), 2);
+        assert_eq!(entries[0].metadata().mode(), EntryMode::DIR);
+        assert_eq!(entries[1].metadata().mode(), EntryMode::FILE);
         assert!(
-            !file_entry.path().ends_with('/'),
+            !entries[1].path().ends_with('/'),
             "file path must not end with /: {}",
-            file_entry.path()
+            entries[1].path()
         );
+    }
 
-        std::fs::remove_dir_all(&root).unwrap();
+    #[tokio::test]
+    async fn list_recursively_skips_unreadable_child() {
+        let root = tempfile::tempdir().unwrap();
+        let locked = root.path().join("locked");
+        fs::create_dir(&locked).unwrap();
+        fs::write(root.path().join("z.txt"), b"data").unwrap();
+        let op = 
Operator::new(Fs::default().root(root.path().to_str().unwrap())).unwrap();
+        let permissions = fs::metadata(&locked).unwrap().permissions();
+        fs::set_permissions(&locked, 
fs::Permissions::from_mode(0o000)).unwrap();
+
+        // Privileged processes can read the directory even with mode 000.
+        match fs::read_dir(&locked) {
+            Ok(_) => {
+                fs::set_permissions(&locked, permissions).unwrap();
+                return;
+            }
+            Err(err) => assert_eq!(err.kind(), 
std::io::ErrorKind::PermissionDenied),
+        }
+
+        let recursive = op.list_with("/").recursive(true).await;
+        let resumed = op.list_with("/").recursive(true).start_after("a").await;
+        let direct = op.list_with("locked/").recursive(true).await;
+        let direct_resumed = op
+            .list_with("locked/")
+            .recursive(true)
+            .start_after("a")
+            .await;
+        fs::set_permissions(&locked, permissions).unwrap();
+
+        let recursive = recursive.unwrap();
+        let paths: Vec<_> = recursive.iter().map(|entry| 
entry.path()).collect();
+        assert_eq!(paths, ["z.txt", "/"]);
+        let resumed = resumed.unwrap();
+        let paths: Vec<_> = resumed.iter().map(|entry| entry.path()).collect();
+        assert_eq!(paths, ["z.txt"]);
+        assert_eq!(direct.unwrap_err().kind(), ErrorKind::PermissionDenied);
+        assert_eq!(
+            direct_resumed.unwrap_err().kind(),
+            ErrorKind::PermissionDenied
+        );
     }
 }
diff --git a/core/services/fs/src/reader.rs b/core/services/fs/src/reader.rs
index 72b432b5bb..d8f47ff237 100644
--- a/core/services/fs/src/reader.rs
+++ b/core/services/fs/src/reader.rs
@@ -16,7 +16,6 @@
 // under the License.
 
 use super::core::*;
-use super::lister::FsLister;
 use super::writer::FsWriter;
 use super::writer::FsWriters;
 use opendal_core::raw::*;
@@ -141,35 +140,3 @@ impl oio::Write for FsLazyWriter {
         }
     }
 }
-
-pub struct FsLazyLister {
-    core: Arc<FsCore>,
-    path: String,
-    inner: Option<Option<FsLister<tokio::fs::ReadDir>>>,
-}
-
-impl FsLazyLister {
-    pub(super) fn new(core: Arc<FsCore>, path: &str) -> Self {
-        Self {
-            core,
-            path: path.to_string(),
-            inner: None,
-        }
-    }
-}
-
-impl oio::List for FsLazyLister {
-    async fn next(&mut self) -> Result<Option<oio::Entry>> {
-        if self.inner.is_none() {
-            self.inner = Some(match self.core.fs_list(&self.path).await? {
-                Some(rd) => Some(FsLister::new(&self.core.root, &self.path, 
rd)),
-                None => None,
-            });
-        }
-
-        match self.inner.as_mut().expect("lister must be initialized") {
-            Some(lister) => lister.next().await,
-            None => Ok(None),
-        }
-    }
-}
diff --git a/core/services/fs/tests/list_start_after.rs 
b/core/services/fs/tests/list_start_after.rs
new file mode 100644
index 0000000000..2198c80d8e
--- /dev/null
+++ b/core/services/fs/tests/list_start_after.rs
@@ -0,0 +1,97 @@
+// 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 opendal_core::Operator;
+use opendal_service_fs::Fs;
+
+#[tokio::test]
+async fn test_list_with_start_after() {
+    let root = tempfile::tempdir().unwrap();
+    let op = 
Operator::new(Fs::default().root(root.path().to_str().unwrap())).unwrap();
+    for path in [
+        "z.txt",
+        "d/y",
+        "d/x",
+        "d/a/child",
+        "d-early.txt",
+        "a.txt",
+        "-first.txt",
+    ] {
+        op.write(path, "data").await.unwrap();
+    }
+
+    for (prefix, recursive, marker, expected) in [
+        ("", false, "d/x", &["z.txt"][..]),
+        ("", true, "d/x", &["d/y", "z.txt"]),
+        ("", false, "d", &["d-early.txt", "d/", "z.txt"]),
+        (
+            "",
+            true,
+            "d/",
+            &["d/a/", "d/a/child", "d/x", "d/y", "z.txt"],
+        ),
+        ("d/", false, "d/", &["d/a/", "d/x", "d/y"]),
+        (
+            "d",
+            true,
+            "d-early.txt",
+            &["d/", "d/a/", "d/a/child", "d/x", "d/y"],
+        ),
+        ("d/", true, "d/w", &["d/x", "d/y"]),
+        ("d", false, "d-early.txt", &["d/"]),
+        (
+            "",
+            false,
+            "",
+            &["-first.txt", "/", "a.txt", "d-early.txt", "d/", "z.txt"],
+        ),
+        (
+            "",
+            true,
+            "",
+            &[
+                "-first.txt",
+                "/",
+                "a.txt",
+                "d-early.txt",
+                "d/",
+                "d/a/",
+                "d/a/child",
+                "d/x",
+                "d/y",
+                "z.txt",
+            ],
+        ),
+        ("", true, "z.txt", &[]),
+    ] {
+        let entries = op
+            .list_with(prefix)
+            .recursive(recursive)
+            .start_after(marker)
+            .await
+            .unwrap();
+        let paths: Vec<_> = entries.iter().map(|entry| entry.path()).collect();
+        assert_eq!(
+            paths, expected,
+            "{prefix:?}, recursive={recursive}, marker={marker:?}"
+        );
+    }
+
+    let capability = op.info().capability();
+    assert!(capability.list_with_start_after);
+    assert!(capability.list_with_recursive);
+}
diff --git a/integrations/object_store/src/store.rs 
b/integrations/object_store/src/store.rs
index 33b404a0ba..c037e82e2b 100644
--- a/integrations/object_store/src/store.rs
+++ b/integrations/object_store/src/store.rs
@@ -715,11 +715,15 @@ impl ObjectStore for OpendalStore {
         let this = self.clone();
 
         let fut = async move {
-            let list_with_start_after = 
this.inner.info().capability().list_with_start_after;
+            let info = this.inner.info();
+            // object_store::path::Path compares percent-encoded strings, so
+            // a%7Eb sorts before a-b. FS compares filenames as stored, where
+            // a~b sorts after a-b. Keep FS offsets in object_store path order.
+            let use_native_offset =
+                info.capability().list_with_start_after && info.scheme() != 
"fs";
             let mut fut = this.inner.lister_with(&path).recursive(true);
 
-            // Use native start_after support if possible.
-            if list_with_start_after {
+            if use_native_offset {
                 fut = fut.start_after(offset.as_ref());
             }
 
@@ -753,7 +757,7 @@ impl ObjectStore for OpendalStore {
                 .into_send()
                 .boxed();
 
-            let stream = if list_with_start_after {
+            let stream = if use_native_offset {
                 lister
             } else {
                 lister
@@ -1209,6 +1213,32 @@ mod tests {
         );
     }
 
+    #[tokio::test]
+    async fn test_list_with_offset_fs_uses_encoded_path_order() {
+        let root =
+            std::env::temp_dir().join(format!("opendal-object-store-{}", 
uuid::Uuid::new_v4()));
+        let op = 
Operator::new(services::Fs::default().root(root.to_str().unwrap())).unwrap();
+        let store = OpendalStore::new(op);
+        for path in ["a~b", "a-b", "z"] {
+            store
+                .put(&Path::from(path), Bytes::from_static(b"data").into())
+                .await
+                .unwrap();
+        }
+
+        let offset = Path::from("a~b");
+        let result = store
+            .list_with_offset(None, &offset)
+            .map_ok(|meta| meta.location)
+            .try_collect::<Vec<_>>()
+            .await;
+        tokio::fs::remove_dir_all(root).await.unwrap();
+
+        let mut locations = result.unwrap();
+        locations.sort();
+        assert_eq!(locations, vec![Path::from("a-b"), Path::from("z")]);
+    }
+
     /// Custom layer that counts stat operations and optionally records read 
ranges.
     mod stat_counter {
         use super::*;

Reply via email to