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

   ### OpenDAL version or commit
   
   `main` at 37b4cf956 (also reproduced at d3a9351 and d21fd39). GlobLayer 
landed in #7629.
   
   ### Affected service or component
   
   core: `GlobLayer` (`list_with(..).glob(..)`). Affects s3, gcs, azblob, oss, 
cos, obs, tos, b2, swift and memory, i.e. every service whose recursive listing 
is a flat key listing.
   
   ### Describe the bug
   
   For a pattern that spans directories (`**`, or a wildcard in a non-final 
component), `GlobLayer` walks the tree one directory at a time and sends one 
non-recursive list request per visited directory. That is the right strategy 
for a directory walker such as `fs`, but on object stores a recursive listing 
is already one flat, paged key listing of the whole subtree. The guided walk 
turns one request into one request per prefix.
   
   On real AWS S3 (us-east-1), with 1000 keys laid out as 
`t/part=0..199/f0..4.parquet`:
   
   | pattern | matches | `glob()` ListObjectsV2 | `glob()` time | 
`list_with("t/").recursive(true)` |
   |---|---|---|---|---|
   | `t/**/*.parquet` | 1000 | 201 | 55.0 s | 1 request, 1.37 s |
   | `t/*/*.parquet` | 1000 | 201 | 59.7 s | 1 request, 0.96 s |
   | `t/part=1*/*.parquet` | 555 | 112 | 29.0 s | 1 request, 0.91 s |
   | `t/part=7/*.parquet` | 5 | 1 | 0.23 s | 1 request, 0.40 s |
   
   Listing the subtree once and filtering it client-side returns the same 
entries with 1 request. Cost scales with the number of directories rather than 
the number of keys, so hive-style layouts (`year=/month=/day=/`) degrade 
fastest. #6535 proposed the guided traversal assuming per-directory listing is 
always cheaper than a full scan, which holds for walkers but not for flat key 
listings.
   
   A second, larger layout (1,722 keys) showed the same thing: `logs/**/*.json` 
267 requests / 67 s vs 1 / 0.85 s, and `logs/y=2024/m=03/*/*.json` 11 / 2.97 s 
vs 1 / 0.28 s.
   
   ### Steps to Reproduce
   
   A standalone program (the `CountingTransport` counts `list-type=2` GETs, 
i.e. ListObjectsV2):
   
   ```toml
   [dependencies]
   futures = "0.3"
   http = "1"
   tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
   opendal = { git = "https://github.com/apache/opendal";, default-features = 
false, features = ["executors-tokio", "http-transport-reqwest-rustls", 
"services-s3"] }
   opendal-http-transport-reqwest = { git = "https://github.com/apache/opendal"; 
}
   ```
   
   ```rust
   use std::sync::Arc;
   use std::sync::atomic::{AtomicUsize, Ordering};
   
   use futures::{StreamExt, TryStreamExt};
   use opendal::*;
   
   #[derive(Clone)]
   struct CountingTransport {
       inner: opendal_http_transport_reqwest::ReqwestTransport,
       lists: Arc<AtomicUsize>,
   }
   
   impl HttpTransport for CountingTransport {
       async fn fetch(&self, req: http::Request<Buffer>) -> 
Result<http::Response<HttpBody>> {
           if req.uri().query().unwrap_or("").contains("list-type=2") {
               self.lists.fetch_add(1, Ordering::SeqCst);
           }
           self.inner.fetch(req).await
       }
   }
   
   #[tokio::main]
   async fn main() -> Result<()> {
       opendal::init_default_registry();
       let env = |k: &str| std::env::var(k).unwrap();
       let lists = Arc::new(AtomicUsize::new(0));
       let transport = CountingTransport {
           inner: Default::default(),
           lists: lists.clone(),
       };
       let op = Operator::via_iter(
           "s3",
           [
               ("bucket", env("S3_BUCKET")),
               ("root", env("S3_ROOT")),
               ("region", env("S3_REGION")),
               ("access_key_id", env("AWS_ACCESS_KEY_ID")),
               ("secret_access_key", env("AWS_SECRET_ACCESS_KEY")),
               ("session_token", env("AWS_SESSION_TOKEN")),
           ]
           .map(|(k, v)| (k.to_string(), v)),
       )?
       
.with_context(OperationContext::new().with_http_transport(HttpTransporter::new(transport)));
   
       let paths = (0..200).flat_map(|p| (0..5).map(move |f| 
format!("t/part={p}/f{f}.parquet")));
       futures::stream::iter(paths)
           .map(|p| { let op = op.clone(); async move { op.write(&p, 
"x").await.map(|_| ()) } })
           .buffer_unordered(32)
           .try_collect::<Vec<_>>()
           .await?;
   
       for pattern in ["t/**/*.parquet", "t/*/*.parquet", 
"t/part=1*/*.parquet"] {
           lists.store(0, Ordering::SeqCst);
           let matches = op.list_with("").glob(pattern).await?.len();
           println!("{pattern}: {matches} matches, {} ListObjectsV2", 
lists.load(Ordering::SeqCst));
       }
       lists.store(0, Ordering::SeqCst);
       let all = op.list_with("t/").recursive(true).await?.len();
       println!("recursive t/: {all} entries, {} ListObjectsV2", 
lists.load(Ordering::SeqCst));
       Ok(())
   }
   ```
   
   ### Actual Behavior
   
   ```text
   t/**/*.parquet: 1000 matches, 201 ListObjectsV2
   t/*/*.parquet: 1000 matches, 201 ListObjectsV2
   t/part=1*/*.parquet: 555 matches, 112 ListObjectsV2
   recursive t/: 1000 entries, 1 ListObjectsV2
   ```
   
   ### Expected Behavior
   
   On services whose recursive listing is a flat key listing, `glob()` should 
cost about what one recursive listing of the pattern's literal prefix costs 
(here 1 request) and return the same entries it returns today. Services that 
recurse by walking directories (fs, and anything simulated by `SimulateLayer`) 
should keep the guided walk, since there it skips directories the pattern 
cannot match.
   
   ### Additional Context
   
   A recursive flat listing does not return directory entries for parents that 
exist only as key prefixes, so a filter has to synthesize those parents (once 
each) to keep results identical for patterns like `t/*/` or `t/**`.
   
   Nothing in `Capability` currently tells `GlobLayer` whether recursion is 
flat or a walk: `list_with_recursive` is true for both s3 and fs. I have a 
patch that adds `Capability::list_with_recursive_flat`, sets it on the 
flat-listing services, and filters one recursive listing when it is set. With 
it the numbers above are 1 request for every pattern, with identical results on 
real S3, and fs is unchanged. PR to follow.
   
   ### 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?
   
   - [x] Yes, I would like to submit a PR.
   


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