chitralverma opened a new issue, #9419:
URL: https://github.com/apache/opendal/issues/9419

   ### OpenDAL version or commit
   
   `c5a3e41666e3e486fbdef68798a4b02456930477` (`main`)
   
   ### Affected service or component
   
   `SimulateLayer` glob listing (`core/core/src/layers/simulate/glob.rs`) with 
`TimeoutLayer`. It applies to services without native `list_with_glob`.
   
   ### Describe the bug
   
   `TimeoutLayer` wraps the glob lister, so `io_timeout` bounds each glob 
`next()` call. One glob `next()` sends LIST requests until it finds the next 
match. In a large tree with few matches, one `next()` can send many LIST 
requests. The glob then fails with `io operation timeout reached`. Each LIST 
request finishes well within `io_timeout`.
   
   Both glob strategies have this behaviour:
   
   - The guided walk, for example `*/match.parquet`, lists each directory that 
can match.
   - The filtered recursive listing, for example `**/match.parquet`, reads 
pages until a key matches.
   
   A recursive listing without glob does not fail. Each of its `next()` calls 
waits for at most one page.
   
   ### Steps to Reproduce
   
   The fixture is like `core/tests/guided_glob_http.rs`. A paged service sends 
each page through the context HTTP transport. Each request takes 50 ms. The 
tree has 200 directories. Only the last directory holds a match. `io_timeout` 
is 500 ms.
   
   `Cargo.toml`:
   
   ```toml
   [package]
   name = "glob-timeout-repro"
   version = "0.0.0"
   edition = "2024"
   publish = false
   
   [workspace]
   
   [dependencies]
   futures = "0.3"
   http = "1"
   opendal = { git = "https://github.com/apache/opendal";, rev = 
"c5a3e41666e3e486fbdef68798a4b02456930477", default-features = false, features 
= ["executors-tokio", "layers-timeout"] }
   tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
   ```
   
   <details><summary><code>src/main.rs</code></summary>
   
   ```rust
   use std::collections::BTreeSet;
   use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::SeqCst};
   use std::sync::{Arc, LazyLock};
   use std::time::{Duration, Instant};
   
   use opendal::executors::TokioExecutor;
   use opendal::layers::{SimulateLayer, TimeoutLayer};
   use opendal::raw::{oio, *};
   use opendal::*;
   
   const DIRS: usize = 200;
   const PAGE_SIZE: usize = 10;
   const LATENCY: Duration = Duration::from_millis(50);
   const IO_TIMEOUT: Duration = Duration::from_millis(500);
   
   /// `d0000/x.txt` .. `d0199/x.txt` and one match, `d0199/match.parquet`.
   static KEYS: LazyLock<Vec<String>> = LazyLock::new(|| {
       let mut keys = Vec::new();
       for i in 0..DIRS {
           if i == DIRS - 1 {
               keys.push(format!("d{i:04}/match.parquet"));
           }
           keys.push(format!("d{i:04}/x.txt"));
       }
       keys
   });
   
   /// A paged store. Each page is one request through the context HTTP 
transport.
   #[derive(Debug)]
   struct Store;
   
   impl Service for Store {
       type Reader = ();
       type Writer = ();
       type Lister = oio::PageLister<Pages>;
       type Deleter = ();
       type Copier = ();
       type Composer = ();
   
       fn info(&self) -> ServiceInfo {
           ServiceInfo::with_scheme("fixture")
       }
       fn capability(&self) -> Capability {
           Capability {
               list: true,
               list_with_recursive: true,
               ..Default::default()
           }
       }
       fn list(&self, ctx: &OperationContext, path: &str, args: OpList) -> 
Result<Self::Lister> {
           Ok(oio::PageLister::new(Pages {
               path: path.to_owned(),
               recursive: args.recursive(),
               transport: ctx.http_transport().clone(),
           }))
       }
       async fn create_dir(
           &self,
           _: &OperationContext,
           _: &str,
           _: OpCreateDir,
       ) -> Result<RpCreateDir> {
           unreachable!()
       }
       async fn stat(&self, _: &OperationContext, _: &str, _: OpStat) -> 
Result<RpStat> {
           unreachable!()
       }
       fn read(&self, _: &OperationContext, _: &str, _: OpRead) -> Result<()> {
           unreachable!()
       }
       fn write(&self, _: &OperationContext, _: &str, _: OpWrite) -> Result<()> 
{
           unreachable!()
       }
       fn delete(&self, _: &OperationContext) -> Result<()> {
           unreachable!()
       }
       fn copy(&self, _: &OperationContext, _: &str, _: &str, _: OpCopy) -> 
Result<()> {
           unreachable!()
       }
       async fn rename(
           &self,
           _: &OperationContext,
           _: &str,
           _: &str,
           _: OpRename,
       ) -> Result<RpRename> {
           unreachable!()
       }
       async fn presign(&self, _: &OperationContext, _: &str, _: OpPresign) -> 
Result<RpPresign> {
           unreachable!()
       }
   }
   
   struct Pages {
       path: String,
       recursive: bool,
       transport: HttpTransporter,
   }
   
   impl oio::PageList for Pages {
       async fn next_page(&self, ctx: &mut oio::PageContext) -> Result<()> {
           let request = http::Request::get("http://fixture.invalid/";)
               .body(Buffer::new())
               .unwrap();
           self.transport.fetch(request).await?;
   
           let prefix = if self.path == "/" {
               ""
           } else {
               self.path.as_str()
           };
           let below: Vec<&String> = KEYS.iter().filter(|k| 
k.starts_with(prefix)).collect();
           if self.recursive {
               let start: usize = ctx.token.parse().unwrap_or(0);
               let end = (start + PAGE_SIZE).min(below.len());
               for key in below[start..end].iter().copied() {
                   ctx.entries
                       .push_back(oio::Entry::new(key, 
MetadataBuilder::file(0).build()));
               }
               ctx.done = end == below.len();
               ctx.token = end.to_string();
               return Ok(());
           }
           let mut dirs = BTreeSet::new();
           for key in below.iter().copied() {
               let rest = &key[prefix.len()..];
               match rest.find('/') {
                   Some(i) => {
                       let dir = format!("{prefix}{}", &rest[..=i]);
                       if dirs.insert(dir.clone()) {
                           ctx.entries
                               .push_back(oio::Entry::new(&dir, 
MetadataBuilder::dir().build()));
                       }
                   }
                   None => ctx
                       .entries
                       .push_back(oio::Entry::new(key, 
MetadataBuilder::file(0).build())),
               }
           }
           ctx.done = true;
           Ok(())
       }
   }
   
   #[derive(Default)]
   struct Stats {
       requests: AtomicUsize,
       slowest_us: AtomicU64,
   }
   
   /// Each request takes `LATENCY`.
   struct Transport(Arc<Stats>);
   
   impl HttpTransport for Transport {
       async fn fetch(&self, _: http::Request<Buffer>) -> 
Result<http::Response<HttpBody>> {
           self.0.requests.fetch_add(1, SeqCst);
           let start = Instant::now();
           tokio::time::sleep(LATENCY).await;
           self.0
               .slowest_us
               .fetch_max(start.elapsed().as_micros() as u64, SeqCst);
           Ok(http::Response::new(HttpBody::new(
               futures::stream::empty(),
               Some(0),
           )))
       }
   }
   
   async fn run(case: &str, timeout: bool, glob: Option<&str>) {
       let stats = Arc::new(Stats::default());
       let ctx = OperationContext::default()
           .with_http_transport(HttpTransporter::new(Transport(stats.clone())))
           .with_executor(Executor::with(TokioExecutor::default()));
       let mut op = Operator::from_parts(ctx, 
Arc::new(Store)).layer(SimulateLayer::default());
       if timeout {
           op = op.layer(TimeoutLayer::new().with_io_timeout(IO_TIMEOUT));
       }
       let start = Instant::now();
       let result = match glob {
           Some(glob) => op.list_with("/").glob(glob).await,
           None => op.list_with("/").recursive(true).await,
       };
       let outcome = match result {
           Ok(entries) => format!("{} entries", entries.len()),
           Err(err) => format!("error: {err}"),
       };
       println!(
           "{case}: {outcome}\n  elapsed {:.2?}, {} requests, slowest request 
{:.2?}",
           start.elapsed(),
           stats.requests.load(SeqCst),
           Duration::from_micros(stats.slowest_us.load(SeqCst)),
       );
   }
   
   #[tokio::main]
   async fn main() {
       run(
           "1. glob `*/match.parquet`, no TimeoutLayer",
           false,
           Some("*/match.parquet"),
       )
       .await;
       run("2. glob `*/match.parquet`", true, Some("*/match.parquet")).await;
       run("3. glob `**/match.parquet`", true, Some("**/match.parquet")).await;
       run("4. recursive list, no glob", true, None).await;
   }
   ```
   
   </details>
   
   Run `cargo run --release`.
   
   ### Actual Behavior
   
   ```text
   1. glob `*/match.parquet`, no TimeoutLayer: 1 entries
     elapsed 1.42s, 201 requests, slowest request 62.80ms
   2. glob `*/match.parquet`: error: Unexpected (temporary) at list, context: { 
timeout: 0.5 } => io operation timeout reached
     elapsed 502.90ms, 66 requests, slowest request 61.59ms
   3. glob `**/match.parquet`: error: Unexpected (temporary) at list, context: 
{ timeout: 0.5 } => io operation timeout reached
     elapsed 501.10ms, 9 requests, slowest request 74.64ms
   4. recursive list, no glob: 201 entries
     elapsed 1.14s, 21 requests, slowest request 57.10ms
   ```
   
   Cases 2 and 3 fail after 500 ms. No request takes more than 75 ms. Case 4 
reads the same keys with the same `TimeoutLayer` and passes.
   
   The default `io_timeout` (10 s) has the same result on a larger tree. With 
`DIRS = 250_000`, `PAGE_SIZE = 1_000` and `IO_TIMEOUT = 
Duration::from_secs(10)`, cases 3 and 4 give:
   
   ```text
   3. glob `**/match.parquet`: error: Unexpected (temporary) at list, context: 
{ timeout: 10 } => io operation timeout reached
     elapsed 10.00s, 182 requests, slowest request 63.00ms
   4. recursive list, no glob: 250001 entries
     elapsed 13.90s, 251 requests, slowest request 89.00ms
   ```
   
   ### Expected Behavior
   
   A glob does not fail with a timeout while each LIST request finishes within 
`io_timeout`. `io_timeout` bounds each LIST request that the glob sends, as it 
does for a listing without glob.
   
   ### Additional Context
   
   - `RetryLayer` after `TimeoutLayer` does not fix this in general. 
`RetryLayer` calls `next()` again on the same lister, and the walk continues. 
In a variant of this fixture with default `RetryLayer::new()`, case 2 passes on 
200 directories. On 2,000 directories it fails after the retries end with 
`Unexpected (persistent) at list, context: { timeout: 0.5 } => io operation 
timeout reached`.
   - The background prefetch of the guided walk already bounds each request 
with the executor timeout (`Directory::prefetch` in `glob.rs`). The foreground 
walk gets only the timeout of the outer `next()`.
   - The `TimeoutLayer` docs say that `io_timeout` bounds "fetching a list 
entry". For a glob, one entry can take many requests.
   - Related: #9103 states that the outer `TimeoutLayer` wraps the foreground 
walk. #9034 is about the walk strategy and does not cover timeouts.
   
   AI assisted: an AI agent wrote the reproduction, ran it, and drafted this 
report for a human contributor.
   
   ### Reproduction confirmation
   
   - [x] I reproduced this issue against the affected component. For a 
service-specific report, I used the actual service rather than only a mock, 
emulator, or source-code analysis.
   
   ### Are you willing to submit a PR to fix this bug?
   
   - [ ] Yes, I would like to submit a PR.
   
   *This comment is AI assisted.*
   


-- 
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]

Reply via email to