kosiew commented on code in PR #27172:
URL: https://github.com/apache/datafusion/pull/27172#discussion_r4753828241


##########
benchmarks/benches/list_files_cache.rs:
##########
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+//! Benchmarks listing-cache misses through the public `ListingTableUrl` API.
+//!
+//! A lazy object store generates fresh metadata without retaining the listing.
+//! There is no network or file-data I/O. Consumers count results without 
collecting
+//! them, so large allocations come from listing/cache behavior, not the 
harness.
+//! Cases vary whether a complete listing fits the 1 MiB cache, whether the 
consumer
+//! stops after ten matches, and whether only one percent of extensions match.
+//!
+//! Run with `cargo bench -p datafusion-benchmarks --bench list_files_cache`.
+
+use std::fmt::{Display, Formatter};
+
+use async_trait::async_trait;
+use criterion::{Criterion, criterion_group, criterion_main};
+use datafusion::datasource::listing::ListingTableUrl;
+use datafusion::execution::runtime_env::RuntimeEnvBuilder;
+use datafusion::prelude::{SessionConfig, SessionContext};
+use futures::stream::BoxStream;
+use futures::{StreamExt, TryStreamExt, future, stream};
+use object_store::path::Path;
+use object_store::{
+    CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, 
ObjectMeta,
+    ObjectStore, PutMultipartOptions, PutOptions, PutPayload, PutResult,
+};
+
+const CACHE_LIMIT: usize = 1024 * 1024;
+
+/// Generates metadata on demand; even a million-file listing has constant 
store
+/// memory. Every `list` call generates its own paths rather than cloning a 
fixture.
+#[derive(Debug)]
+struct GeneratedObjectStore {
+    files: usize,
+    parquet_every: usize,
+}
+
+impl Display for GeneratedObjectStore {
+    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+        write!(f, "GeneratedObjectStore")
+    }
+}
+
+fn unsupported(operation: &str) -> object_store::Error {
+    object_store::Error::NotImplemented {
+        operation: operation.to_owned(),
+        implementer: "GeneratedObjectStore".to_owned(),
+    }
+}
+
+#[async_trait]
+impl ObjectStore for GeneratedObjectStore {
+    async fn put_opts(
+        &self,
+        _location: &Path,
+        _payload: PutPayload,
+        _opts: PutOptions,
+    ) -> object_store::Result<PutResult> {
+        Err(unsupported("put_opts"))
+    }
+
+    async fn put_multipart_opts(
+        &self,
+        _location: &Path,
+        _opts: PutMultipartOptions,
+    ) -> object_store::Result<Box<dyn MultipartUpload>> {
+        Err(unsupported("put_multipart_opts"))
+    }
+
+    async fn get_opts(
+        &self,
+        _location: &Path,
+        _opts: GetOptions,
+    ) -> object_store::Result<GetResult> {
+        Err(unsupported("get_opts"))
+    }
+
+    fn delete_stream(
+        &self,
+        _locations: BoxStream<'static, object_store::Result<Path>>,
+    ) -> BoxStream<'static, object_store::Result<Path>> {
+        stream::once(future::ready(Err(unsupported("delete_stream")))).boxed()
+    }
+
+    fn list(
+        &self,
+        prefix: Option<&Path>,
+    ) -> BoxStream<'static, object_store::Result<ObjectMeta>> {
+        assert_eq!(prefix.map(Path::as_ref), Some("table"));
+        let parquet_every = self.parquet_every;
+        stream::iter(0..self.files)
+            .map(move |index| {
+                let extension = if index % parquet_every == 0 {
+                    "parquet"
+                } else {
+                    "csv"
+                };
+                ObjectMeta {
+                    location: 
Path::from(format!("table/part-{index:08}.{extension}")),
+                    last_modified: Default::default(),
+                    size: 1024,
+                    e_tag: None,
+                    version: None,
+                }
+            })
+            .map(Ok)
+            .boxed()
+    }
+
+    async fn list_with_delimiter(
+        &self,
+        _prefix: Option<&Path>,
+    ) -> object_store::Result<ListResult> {
+        Err(unsupported("list_with_delimiter"))
+    }
+
+    async fn copy_opts(
+        &self,
+        _from: &Path,
+        _to: &Path,
+        _options: CopyOptions,
+    ) -> object_store::Result<()> {
+        Err(unsupported("copy_opts"))
+    }
+}
+
+fn criterion_benchmark(criterion: &mut Criterion) {
+    let runtime = tokio::runtime::Runtime::new().unwrap();
+    let runtime_env = RuntimeEnvBuilder::new()
+        .with_object_list_cache_limit(CACHE_LIMIT)
+        .build_arc()
+        .unwrap();
+    let cache = runtime_env.cache_manager.get_list_files_cache().unwrap();
+    let context = SessionContext::new_with_config_rt(SessionConfig::new(), 
runtime_env);
+    let state = context.state();
+    let url = ListingTableUrl::parse("test:///table/").unwrap();
+
+    let mut group = criterion.benchmark_group("list_files_cache_miss");
+    for (name, files, take, parquet_every) in [
+        ("cacheable/full", 1_000, usize::MAX, 1),

Review Comment:
   Please provide a matched cacheable-miss benchmark against the parent 
revision. These misses now perform incremental metadata accounting in addition 
to final cache admission accounting, and the supplied results do not isolate 
this overhead.



##########
datafusion/datasource/src/url.rs:
##########
@@ -398,10 +401,32 @@ async fn list_with_cache<'b>(
                 debug!("Hit list files cache for requested path");
                 cached.files_matching_prefix(&None)
             } else {
-                let mut vec = store
+                let mut list = store
                     .list(Some(&full_prefix))
-                    .try_collect::<Vec<ObjectMeta>>()
-                    .await?;
+                    .map_err(|e| DataFusionError::ObjectStore(Box::new(e)))
+                    .boxed();
+                let limit = cache.cache_limit();
+                let mut size = table_scoped_list_path.size();
+                if size > limit {
+                    return Ok(list);
+                }
+                let mut vec = Vec::new();
+                while let Some(meta) = list.try_next().await? {
+                    // Admission uses the final, right-sized vector, not spare 
capacity
+                    // from growth. Count only bytes that shrink_to_fit cannot 
remove.
+                    let next_size = size
+                        .checked_add(size_of::<ObjectMeta>())
+                        .and_then(|size| 
size.checked_add(meta_heap_bytes(&meta)));
+                    vec.push(meta);

Review Comment:
   Pushing the rejected object can double the prefix capacity, increasing peak 
allocations when callers collect results. Please push only fitting objects, 
stream the crossing object separately, and verify allocation behavior with a 
near-budget collecting case.



##########
datafusion/datasource/src/url.rs:
##########
@@ -1130,6 +1157,189 @@ mod tests {
         Ok(())
     }
 
+    fn listing_cache_key(url: &ListingTableUrl) -> TableScopedPath {
+        TableScopedPath {
+            table: url.get_table_ref().clone(),
+            path: url.prefix().clone(),
+        }
+    }
+
+    fn generated_listing_weight(
+        url: &ListingTableUrl,
+        listing: &GeneratedListing,
+        count: usize,
+    ) -> usize {
+        let mut files = (0..count).map(|index| 
listing.object(index)).collect_vec();
+        files.shrink_to_fit();
+        listing_cache_key(url).size() + CachedFileList::new(files).size()
+    }
+
+    fn session_with_listing_cache(limit: usize) -> Result<MockSession> {
+        use datafusion_execution::runtime_env::RuntimeEnvBuilder;
+
+        Ok(MockSession::with_runtime_env(
+            RuntimeEnvBuilder::new()
+                .with_object_list_cache_limit(limit)
+                .build_arc()?,
+        ))
+    }
+
+    #[tokio::test]
+    async fn test_oversized_listing_only_prefetches_a_bounded_prefix() -> 
Result<()> {
+        let store = MockObjectStore::with_generated_listing(100, 128, None);
+        let listing = store.generated_listing.as_ref().unwrap();
+        let url = ListingTableUrl::parse("/table/")?;
+        let session =
+            session_with_listing_cache(generated_listing_weight(&url, listing, 
2))?;
+        let stream = url.list_all_files(&session, &store, "parquet").await?;
+
+        // Two objects fit; the third proves this listing cannot be cached.
+        assert_eq!(listing.polled.load(Ordering::Relaxed), 3);
+        let files = stream.try_collect::<Vec<_>>().await?;
+        assert_eq!(
+            files,
+            (0..100).map(|index| listing.object(index)).collect_vec()
+        );
+        assert_eq!(listing.polled.load(Ordering::Relaxed), 100);
+        let cache = session
+            .runtime_env
+            .cache_manager
+            .get_list_files_cache()
+            .unwrap();
+        assert!(cache.get(&listing_cache_key(&url)).is_none());
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn test_dropping_oversized_listing_does_not_read_or_cache_its_tail()
+    -> Result<()> {
+        let store = MockObjectStore::with_generated_listing(100, 128, None);
+        let listing = store.generated_listing.as_ref().unwrap();
+        let url = ListingTableUrl::parse("/table/")?;
+        let session =
+            session_with_listing_cache(generated_listing_weight(&url, listing, 
1))?;
+        let mut stream = url.list_all_files(&session, &store, 
"parquet").await?;
+        assert_eq!(stream.try_next().await?, Some(listing.object(0)));
+        drop(stream);
+
+        assert_eq!(listing.polled.load(Ordering::Relaxed), 2);
+        let cache = session
+            .runtime_env
+            .cache_manager
+            .get_list_files_cache()
+            .unwrap();
+        assert!(cache.get(&listing_cache_key(&url)).is_none());
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn test_listing_cache_admission_boundary_includes_key_and_metadata()
+    -> Result<()> {
+        let url = ListingTableUrl::parse("/table/")?
+            .with_table_ref(TableReference::bare("a_table_reference"));
+        for below_limit in [0, 1] {
+            let store = MockObjectStore::with_generated_listing(2, 128, None);
+            let listing = store.generated_listing.as_ref().unwrap();
+            let limit = generated_listing_weight(&url, listing, 2) - 
below_limit;
+            let session = session_with_listing_cache(limit)?;
+            let cache = session
+                .runtime_env
+                .cache_manager
+                .get_list_files_cache()
+                .unwrap();
+            let expected = (0..2).map(|index| 
listing.object(index)).collect_vec();
+
+            for _ in 0..2 {
+                let files = url
+                    .list_all_files(&session, &store, "parquet")
+                    .await?
+                    .try_collect::<Vec<_>>()
+                    .await?;
+                assert_eq!(files, expected);
+            }
+
+            assert_eq!(
+                cache.get(&listing_cache_key(&url)).is_some(),
+                below_limit == 0
+            );
+            assert_eq!(
+                listing.polled.load(Ordering::Relaxed),
+                if below_limit == 0 { 2 } else { 4 }
+            );
+        }
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn 
test_single_oversized_listing_object_is_returned_without_reading_tail()
+    -> Result<()> {
+        let store = MockObjectStore::with_generated_listing(100, 1024 * 1024, 
None);
+        let listing = store.generated_listing.as_ref().unwrap();
+        let url = ListingTableUrl::parse("/table/")?;
+        let session = session_with_listing_cache(1024)?;
+        let mut stream = url.list_all_files(&session, &store, 
"parquet").await?;
+
+        assert_eq!(listing.polled.load(Ordering::Relaxed), 1);
+        assert_eq!(stream.try_next().await?, Some(listing.object(0)));
+        drop(stream);
+        assert_eq!(listing.polled.load(Ordering::Relaxed), 1);
+        let cache = session
+            .runtime_env
+            .cache_manager
+            .get_list_files_cache()
+            .unwrap();
+        assert!(cache.get(&listing_cache_key(&url)).is_none());
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn test_listing_key_over_budget_skips_prefetch() -> Result<()> {
+        let store = MockObjectStore::with_generated_listing(3, 128, None);
+        let listing = store.generated_listing.as_ref().unwrap();
+        let url = ListingTableUrl::parse("/table/")?;
+        let session = 
session_with_listing_cache(listing_cache_key(&url).size() - 1)?;
+        let stream = url.list_all_files(&session, &store, "parquet").await?;
+
+        assert_eq!(listing.polled.load(Ordering::Relaxed), 0);
+        assert_eq!(stream.try_collect::<Vec<_>>().await?.len(), 3);
+        let cache = session
+            .runtime_env
+            .cache_manager
+            .get_list_files_cache()
+            .unwrap();
+        assert!(cache.get(&listing_cache_key(&url)).is_none());
+        Ok(())
+    }
+
+    #[tokio::test]
+    async fn test_listing_errors_never_cache_a_partial_listing() -> Result<()> 
{
+        let url = ListingTableUrl::parse("/table/")?;
+        for fitting_objects in [1, 10] {
+            let store = MockObjectStore::with_generated_listing(10, 128, 
Some(2));
+            let listing = store.generated_listing.as_ref().unwrap();
+            let session = session_with_listing_cache(generated_listing_weight(
+                &url,
+                listing,
+                fitting_objects,
+            ))?;
+            let result = match url.list_all_files(&session, &store, 
"parquet").await {

Review Comment:
   Could we assert the error delivery phase explicitly? The smaller budget 
should produce two objects followed by a stream error, while the larger budget 
should fail during prefetch. Retain both no-cache assertions.



##########
datafusion/datasource/src/url.rs:
##########
@@ -357,6 +358,8 @@ impl ListingTableUrl {
 /// # Cache Behavior:
 /// A full table listing can satisfy a prefix-filtered request by filtering the
 /// cached files. On cache miss, only the requested path is listed and cached.
+/// Once the listing exceeds the cache budget, the buffered prefix and 
remaining

Review Comment:
   Could we clarify that the cutoff uses estimated cache-entry weight rather 
than actual memory consumption? Spare vector capacity, the crossing object, and 
downstream allocations are not bounded by this threshold.



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to