Skip to main content

lance_io/object_store/
providers.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The Lance Authors
3
4use std::{
5    collections::HashMap,
6    sync::{
7        Arc, RwLock, Weak,
8        atomic::{AtomicU64, Ordering},
9    },
10};
11
12use object_store::path::Path;
13use url::Url;
14
15use crate::object_store::WrappingObjectStore;
16use crate::object_store::uri_to_url;
17
18use super::{ObjectStore, ObjectStoreParams, tracing::ObjectStoreTracingExt};
19use lance_core::error::{Error, LanceOptionExt, Result};
20
21#[cfg(feature = "aws")]
22pub mod aws;
23#[cfg(feature = "azure")]
24pub mod azure;
25#[cfg(feature = "gcp")]
26pub mod gcp;
27#[cfg(feature = "goosefs")]
28pub mod goosefs;
29#[cfg(feature = "huggingface")]
30pub mod huggingface;
31pub mod local;
32pub mod memory;
33#[cfg(feature = "oss")]
34pub mod oss;
35pub mod shared_memory;
36#[cfg(feature = "tencent")]
37pub mod tencent;
38#[cfg(feature = "tos")]
39pub mod tos;
40
41#[async_trait::async_trait]
42pub trait ObjectStoreProvider: std::fmt::Debug + Sync + Send {
43    async fn new_store(&self, base_path: Url, params: &ObjectStoreParams) -> Result<ObjectStore>;
44
45    /// Extract the path relative to the base of the store.
46    ///
47    /// For example, in S3 the path is relative to the bucket. So a URL of
48    /// `s3://bucket/path/to/file` would return `path/to/file`.
49    ///
50    /// Meanwhile, for a file store, the path is relative to the filesystem root.
51    /// So a URL of `file:///path/to/file` would return `/path/to/file`.
52    fn extract_path(&self, url: &Url) -> Result<Path> {
53        // url.path() returns a percent-encoded string (per the WHATWG URL spec).
54        // Path::from_url_path decodes it first so the Path internal representation
55        // holds the raw UTF-8 string. This prevents double-encoding when the
56        // object store client later percent-encodes the path for HTTP requests.
57        Path::from_url_path(url.path()).map_err(|e| {
58            Error::invalid_input(format!("Invalid path in URL '{}': {}", url.path(), e))
59        })
60    }
61
62    /// Calculate the unique prefix that should be used for this object store.
63    ///
64    /// For object stores that don't have the concept of buckets, this will just be something like
65    /// 'file' or 'memory'.
66    ///
67    /// In object stores where all bucket names are unique, like s3, this will be
68    /// simply 's3$my_bucket_name' or similar.
69    ///
70    /// In Azure, only the combination of (account name, container name) is unique, so
71    /// this will be something like 'az$account_name@container'
72    ///
73    /// Providers should override this if they have special requirements like Azure's.
74    fn calculate_object_store_prefix(
75        &self,
76        url: &Url,
77        _storage_options: Option<&HashMap<String, String>>,
78    ) -> Result<String> {
79        Ok(format!("{}${}", url.scheme(), url.authority()))
80    }
81}
82
83/// Statistics for the object store registry cache.
84#[derive(Debug, Clone, Default)]
85pub struct ObjectStoreRegistryStats {
86    /// Number of cache hits (store was already cached and reused).
87    pub hits: u64,
88    /// Number of cache misses (new store had to be created).
89    pub misses: u64,
90    /// Number of currently active object stores in the cache.
91    pub active_stores: usize,
92}
93
94/// A registry of object store providers.
95///
96/// Use [`Self::default()`] to create one with the available default providers.
97/// This includes (depending on features enabled):
98/// - `memory`: An in-memory object store.
99/// - `file`: A local file object store, with optimized code paths.
100/// - `file-object-store`: A local file object store that uses the ObjectStore API,
101///   for all operations. Used for testing with ObjectStore wrappers.
102/// - `file+uring`: A local file object store using io_uring (Linux only).
103/// - `s3`: An S3 object store.
104/// - `s3+ddb`: An S3 object store with DynamoDB for metadata.
105/// - `az`: An Azure Blob Storage object store.
106/// - `gs`: A Google Cloud Storage object store.
107/// - `tos`: A Volcengine TOS object store.
108///
109/// Use [`Self::empty()`] to create an empty registry, with no providers registered.
110///
111/// The registry also caches object stores that are currently in use. It holds
112/// weak references to the object stores, so they are not held onto. If an object
113/// store is no longer in use, it will be removed from the cache on the next
114/// call to either [`Self::active_stores()`] or [`Self::get_store()`].
115#[derive(Debug)]
116pub struct ObjectStoreRegistry {
117    providers: RwLock<HashMap<String, Arc<dyn ObjectStoreProvider>>>,
118    // Cache of object stores currently in use. We use a weak reference so the
119    // cache itself doesn't keep them alive if no object store is actually using
120    // it.
121    active_stores: RwLock<HashMap<(String, ObjectStoreParams), Weak<ObjectStore>>>,
122    // Cache statistics
123    hits: AtomicU64,
124    misses: AtomicU64,
125}
126
127impl ObjectStoreRegistry {
128    /// Create a new registry with no providers registered.
129    ///
130    /// Typically, you want to use [`Self::default()`] instead, so you get the
131    /// default providers.
132    pub fn empty() -> Self {
133        Self {
134            providers: RwLock::new(HashMap::new()),
135            active_stores: RwLock::new(HashMap::new()),
136            hits: AtomicU64::new(0),
137            misses: AtomicU64::new(0),
138        }
139    }
140
141    /// Get the object store provider for a given scheme.
142    pub fn get_provider(&self, scheme: &str) -> Option<Arc<dyn ObjectStoreProvider>> {
143        self.providers
144            .read()
145            .expect("ObjectStoreRegistry lock poisoned")
146            .get(scheme)
147            .cloned()
148    }
149
150    /// Get a list of all active object stores.
151    ///
152    /// Calling this will also clean up any weak references to object stores that
153    /// are no longer valid.
154    pub fn active_stores(&self) -> Vec<Arc<ObjectStore>> {
155        let mut found_inactive = false;
156        let output = self
157            .active_stores
158            .read()
159            .expect("ObjectStoreRegistry lock poisoned")
160            .values()
161            .filter_map(|weak| match weak.upgrade() {
162                Some(store) => Some(store),
163                None => {
164                    found_inactive = true;
165                    None
166                }
167            })
168            .collect();
169
170        if found_inactive {
171            // Clean up the cache by removing any weak references that are no longer valid
172            let mut cache_lock = self
173                .active_stores
174                .write()
175                .expect("ObjectStoreRegistry lock poisoned");
176            cache_lock.retain(|_, weak| weak.upgrade().is_some());
177        }
178        output
179    }
180
181    /// Get cache statistics for monitoring and debugging.
182    ///
183    /// Returns the number of cache hits, misses, and currently active stores.
184    /// This is useful for detecting configuration issues that cause excessive
185    /// cache misses (e.g., storage options that vary per-request).
186    pub fn stats(&self) -> ObjectStoreRegistryStats {
187        let active_stores = self
188            .active_stores
189            .read()
190            .map(|s| s.values().filter(|w| w.strong_count() > 0).count())
191            .unwrap_or(0);
192        ObjectStoreRegistryStats {
193            hits: self.hits.load(Ordering::Relaxed),
194            misses: self.misses.load(Ordering::Relaxed),
195            active_stores,
196        }
197    }
198
199    fn scheme_not_found_error(&self, scheme: &str) -> Error {
200        let mut message = format!("No object store provider found for scheme: '{}'", scheme);
201        if let Ok(providers) = self.providers.read() {
202            let valid_schemes = providers.keys().cloned().collect::<Vec<_>>().join(", ");
203            message.push_str(&format!("\nValid schemes: {}", valid_schemes));
204        }
205        Error::invalid_input(message)
206    }
207
208    async fn build_store(
209        &self,
210        provider: Arc<dyn ObjectStoreProvider>,
211        base_path: Url,
212        params: &ObjectStoreParams,
213        store_prefix: &str,
214    ) -> Result<Arc<ObjectStore>> {
215        let mut store = provider.new_store(base_path, params).await?;
216
217        store.inner = store.inner.traced();
218
219        // Label metrics by the store's unique prefix (e.g. `s3$bucket`,
220        // `az$container@account`) so multiple stores on one cloud differ.
221        crate::object_store::meter_store(&mut store.inner, &mut store.io_tracker, store_prefix);
222
223        if let Some(wrapper) = &params.object_store_wrapper {
224            store.apply_wrapper(wrapper.as_ref());
225        }
226
227        // Always wrap with IO tracking
228        store.inner = store.io_tracker.wrap("", store.inner);
229
230        Ok(Arc::new(store))
231    }
232
233    /// Build a fresh object store without consulting or populating the cache.
234    ///
235    /// Callers should retain the returned [`Arc`] for as long as they want to
236    /// reuse provider-local state such as HTTP clients and rate limiters.
237    #[doc(hidden)]
238    pub async fn new_store(
239        &self,
240        base_path: Url,
241        params: &ObjectStoreParams,
242    ) -> Result<Arc<ObjectStore>> {
243        // Base-scoped storage options (`base_<id>.<key>`) are directives for
244        // other registered base paths; resolve them away before building a
245        // store for this location.
246        let params = params.scoped_to_base(None);
247        let params = params.as_ref();
248        let scheme = base_path.scheme();
249        let Some(provider) = self.get_provider(scheme) else {
250            return Err(self.scheme_not_found_error(scheme));
251        };
252        let store_prefix =
253            provider.calculate_object_store_prefix(&base_path, params.storage_options())?;
254
255        self.build_store(provider, base_path, params, &store_prefix)
256            .await
257    }
258
259    /// Get an object store for a given base path and parameters.
260    ///
261    /// If the object store is already in use, it will return a strong reference
262    /// to the object store. If the object store is not in use, it will create a
263    /// new object store and return a strong reference to it.
264    pub async fn get_store(
265        &self,
266        base_path: Url,
267        params: &ObjectStoreParams,
268    ) -> Result<Arc<ObjectStore>> {
269        // Base-scoped storage options (`base_<id>.<key>`) are directives for
270        // other registered base paths; resolve them away before building or
271        // caching a store for this location. Params already resolved for a
272        // base contain no scoped entries, so this is a no-op for them.
273        let params = params.scoped_to_base(None);
274        let params = params.as_ref();
275        let scheme = base_path.scheme();
276        let Some(provider) = self.get_provider(scheme) else {
277            return Err(self.scheme_not_found_error(scheme));
278        };
279
280        let cache_path =
281            provider.calculate_object_store_prefix(&base_path, params.storage_options())?;
282        let cache_key = (cache_path.clone(), params.clone());
283
284        // Check if we have a cached store for this base path and params
285        {
286            let maybe_store = self
287                .active_stores
288                .read()
289                .ok()
290                .expect_ok()?
291                .get(&cache_key)
292                .cloned();
293            if let Some(store) = maybe_store {
294                if let Some(store) = store.upgrade() {
295                    self.hits.fetch_add(1, Ordering::Relaxed);
296                    return Ok(store);
297                } else {
298                    // Remove the weak reference if it is no longer valid
299                    let mut cache_lock = self
300                        .active_stores
301                        .write()
302                        .expect("ObjectStoreRegistry lock poisoned");
303                    if let Some(store) = cache_lock.get(&cache_key)
304                        && store.upgrade().is_none()
305                    {
306                        // Remove the weak reference if it is no longer valid
307                        cache_lock.remove(&cache_key);
308                    }
309                }
310            }
311        }
312
313        self.misses.fetch_add(1, Ordering::Relaxed);
314
315        let store = self
316            .build_store(provider, base_path, params, &cache_path)
317            .await?;
318
319        {
320            // Insert the store into the cache
321            let mut cache_lock = self.active_stores.write().ok().expect_ok()?;
322            cache_lock.insert(cache_key, Arc::downgrade(&store));
323        }
324
325        Ok(store)
326    }
327
328    /// Calculate the datastore prefix based on the URI and the storage options.
329    /// The data store prefix should uniquely identify the datastore.
330    pub fn calculate_object_store_prefix(
331        &self,
332        uri: &str,
333        storage_options: Option<&HashMap<String, String>>,
334    ) -> Result<String> {
335        let url = uri_to_url(uri)?;
336        match self.get_provider(url.scheme()) {
337            None => {
338                if url.scheme() == "file" || url.scheme().len() == 1 {
339                    Ok("file".to_string())
340                } else {
341                    Err(self.scheme_not_found_error(url.scheme()))
342                }
343            }
344            Some(provider) => provider.calculate_object_store_prefix(&url, storage_options),
345        }
346    }
347}
348
349impl Default for ObjectStoreRegistry {
350    fn default() -> Self {
351        let mut providers: HashMap<String, Arc<dyn ObjectStoreProvider>> = HashMap::new();
352
353        providers.insert("memory".into(), Arc::new(memory::MemoryStoreProvider));
354        providers.insert(
355            "shared-memory".into(),
356            Arc::new(shared_memory::SharedMemoryStoreProvider::default()),
357        );
358        providers.insert("file".into(), Arc::new(local::FileStoreProvider));
359        // The "file" scheme has special optimized code paths that bypass
360        // the ObjectStore API for better performance. However, this can make it
361        // hard to test when using ObjectStore wrappers, such as IOTrackingStore.
362        // So we provide a "file-object-store" scheme that uses the ObjectStore API.
363        // The specialized code paths are differentiated by the scheme name.
364        providers.insert(
365            "file-object-store".into(),
366            Arc::new(local::FileStoreProvider),
367        );
368        #[cfg(target_os = "linux")]
369        providers.insert("file+uring".into(), Arc::new(local::FileStoreProvider));
370
371        #[cfg(feature = "aws")]
372        {
373            let aws = Arc::new(aws::AwsStoreProvider);
374            providers.insert("s3".into(), aws.clone());
375            providers.insert("s3+ddb".into(), aws);
376        }
377        #[cfg(feature = "azure")]
378        {
379            let azure = Arc::new(azure::AzureBlobStoreProvider);
380            providers.insert("az".into(), azure.clone());
381            providers.insert("abfss".into(), azure);
382        }
383        #[cfg(feature = "gcp")]
384        providers.insert("gs".into(), Arc::new(gcp::GcsStoreProvider));
385        #[cfg(feature = "goosefs")]
386        providers.insert("goosefs".into(), Arc::new(goosefs::GooseFsStoreProvider));
387        #[cfg(feature = "oss")]
388        providers.insert("oss".into(), Arc::new(oss::OssStoreProvider));
389        #[cfg(feature = "tencent")]
390        providers.insert("cos".into(), Arc::new(tencent::TencentStoreProvider));
391        #[cfg(feature = "huggingface")]
392        providers.insert("hf".into(), Arc::new(huggingface::HuggingfaceStoreProvider));
393        #[cfg(feature = "tos")]
394        providers.insert("tos".into(), Arc::new(tos::TosStoreProvider));
395        Self {
396            providers: RwLock::new(providers),
397            active_stores: RwLock::new(HashMap::new()),
398            hits: AtomicU64::new(0),
399            misses: AtomicU64::new(0),
400        }
401    }
402}
403
404impl ObjectStoreRegistry {
405    /// Add a new object store provider to the registry. The provider will be used
406    /// in [`Self::get_store()`] when a URL is passed with a matching scheme.
407    pub fn insert(&self, scheme: &str, provider: Arc<dyn ObjectStoreProvider>) {
408        self.providers
409            .write()
410            .expect("ObjectStoreRegistry lock poisoned")
411            .insert(scheme.into(), provider);
412    }
413}
414
415#[cfg(test)]
416mod tests {
417    use std::collections::HashMap;
418    use std::sync::Mutex;
419
420    use super::*;
421    use object_store::ObjectStore as OSObjectStore;
422
423    use crate::object_store::providers::memory::MemoryStoreProvider;
424    use object_store::list::{PaginatedListOptions, PaginatedListResult, PaginatedListStore};
425    use rstest::rstest;
426
427    #[derive(Debug)]
428    struct DummyProvider;
429
430    #[async_trait::async_trait]
431    impl ObjectStoreProvider for DummyProvider {
432        async fn new_store(
433            &self,
434            _base_path: Url,
435            _params: &ObjectStoreParams,
436        ) -> Result<ObjectStore> {
437            unreachable!("This test doesn't create stores")
438        }
439    }
440
441    /// A lister that exists only to be handed to a wrapper.
442    struct StubLister;
443
444    #[async_trait::async_trait]
445    impl PaginatedListStore for StubLister {
446        async fn list_paginated(
447            &self,
448            _prefix: Option<&str>,
449            _opts: PaginatedListOptions,
450        ) -> object_store::Result<PaginatedListResult> {
451            unimplemented!("this lister exists to be wrapped, not to list")
452        }
453    }
454
455    /// A provider whose stores come with a paginated lister, which the memory store does not.
456    #[derive(Debug)]
457    struct PaginatedProvider;
458
459    #[async_trait::async_trait]
460    impl ObjectStoreProvider for PaginatedProvider {
461        async fn new_store(
462            &self,
463            base_path: Url,
464            params: &ObjectStoreParams,
465        ) -> Result<ObjectStore> {
466            let mut store = MemoryStoreProvider.new_store(base_path, params).await?;
467            store.paginated_lister = Some(Arc::new(StubLister));
468            Ok(store)
469        }
470
471        fn calculate_object_store_prefix(
472            &self,
473            _url: &Url,
474            _storage_options: Option<&HashMap<String, String>>,
475        ) -> Result<String> {
476            Ok("memory".to_string())
477        }
478    }
479
480    /// Swaps the store out for an empty one, the way a wrapper enforcing visibility would, and
481    /// records the prefix each call was labelled with. `keep_pushdown` is what it answers when
482    /// asked about the lister.
483    #[derive(Debug)]
484    struct RecordingWrapper {
485        keep_pushdown: bool,
486        prefixes: Mutex<Vec<String>>,
487    }
488
489    impl WrappingObjectStore for RecordingWrapper {
490        fn wrap(
491            &self,
492            store_prefix: &str,
493            _original: Arc<dyn OSObjectStore>,
494        ) -> Arc<dyn OSObjectStore> {
495            self.prefixes
496                .lock()
497                .unwrap()
498                .push(format!("wrap@{store_prefix}"));
499            Arc::new(object_store::memory::InMemory::new())
500        }
501
502        fn wrap_paginated(
503            &self,
504            store_prefix: &str,
505            original: Arc<dyn PaginatedListStore>,
506        ) -> Option<Arc<dyn PaginatedListStore>> {
507            self.prefixes
508                .lock()
509                .unwrap()
510                .push(format!("wrap_paginated@{store_prefix}"));
511            self.keep_pushdown.then_some(original)
512        }
513    }
514
515    /// A decorator supplied through [`ObjectStoreParams`] has to reach the paginated lister
516    /// too, or `read_dir_page` would talk to the backend behind its back — and a decorator
517    /// that gives the pushdown up gets a store with no lister, so its listings go through the
518    /// wrapped `inner` and see what the wrapper allows rather than what the backend holds.
519    #[rstest]
520    #[case::keeps_the_pushdown(true)]
521    #[case::gives_up_the_pushdown(false)]
522    #[tokio::test]
523    async fn test_the_registry_hands_the_lister_to_the_wrapper(#[case] keep_pushdown: bool) {
524        let wrapper = Arc::new(RecordingWrapper {
525            keep_pushdown,
526            prefixes: Mutex::new(Vec::new()),
527        });
528        let registry = ObjectStoreRegistry::default();
529        registry.insert("pagmem", Arc::new(PaginatedProvider));
530
531        let store = registry
532            .get_store(
533                Url::parse("pagmem:///").unwrap(),
534                &ObjectStoreParams {
535                    object_store_wrapper: Some(wrapper.clone()),
536                    ..Default::default()
537                },
538            )
539            .await
540            .unwrap();
541
542        assert_eq!(store.paginated_lister.is_some(), keep_pushdown);
543        // Both halves of the store are labelled with the same prefix.
544        assert_eq!(
545            *wrapper.prefixes.lock().unwrap(),
546            vec!["wrap@memory", "wrap_paginated@memory"]
547        );
548        if !keep_pushdown {
549            // `StubLister` panics if it is ever asked to list, so reaching a page at all is
550            // the other half of the assertion.
551            let page = store
552                .read_dir_page(Path::from(""), Default::default())
553                .await
554                .unwrap();
555            assert!(page.result.common_prefixes.is_empty());
556            assert!(page.result.objects.is_empty());
557        }
558    }
559
560    #[test]
561    fn test_calculate_object_store_prefix() {
562        let provider = DummyProvider;
563        let url = Url::parse("dummy://blah/path").unwrap();
564        assert_eq!(
565            "dummy$blah",
566            provider.calculate_object_store_prefix(&url, None).unwrap()
567        );
568    }
569
570    #[tokio::test]
571    async fn test_get_store_resolves_base_scoped_options() {
572        use crate::object_store::StorageOptionsAccessor;
573
574        let registry = ObjectStoreRegistry::default();
575        let url = Url::parse("memory://test").unwrap();
576
577        let with_scoped = ObjectStoreParams {
578            storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
579                HashMap::from([
580                    ("shared".to_string(), "value".to_string()),
581                    ("base_1.account_key".to_string(), "base1-key".to_string()),
582                ]),
583            ))),
584            ..Default::default()
585        };
586        let without_scoped = ObjectStoreParams {
587            storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
588                HashMap::from([("shared".to_string(), "value".to_string())]),
589            ))),
590            ..Default::default()
591        };
592
593        // Base-scoped entries are resolved away before the store is built and
594        // cached, so params with and without them yield the same cached store.
595        let store_scoped = registry.get_store(url.clone(), &with_scoped).await.unwrap();
596        let store_plain = registry.get_store(url, &without_scoped).await.unwrap();
597        assert!(Arc::ptr_eq(&store_scoped, &store_plain));
598    }
599
600    #[test]
601    fn test_calculate_object_store_scheme_not_found() {
602        let registry = ObjectStoreRegistry::empty();
603        registry.insert("dummy", Arc::new(DummyProvider));
604        let s = "Invalid user input: No object store provider found for scheme: 'dummy2'\nValid schemes: dummy";
605        let result = registry
606            .calculate_object_store_prefix("dummy2://mybucket/my/long/path", None)
607            .expect_err("expected error")
608            .to_string();
609        assert_eq!(s, &result[..s.len()]);
610    }
611
612    // Test that paths without a scheme get treated as local paths.
613    #[test]
614    fn test_calculate_object_store_prefix_for_local() {
615        let registry = ObjectStoreRegistry::empty();
616        assert_eq!(
617            "file",
618            registry
619                .calculate_object_store_prefix("/tmp/foobar", None)
620                .unwrap()
621        );
622    }
623
624    // Test that paths with a single-letter scheme that is not registered for anything get treated as local paths.
625    #[test]
626    fn test_calculate_object_store_prefix_for_local_windows_path() {
627        let registry = ObjectStoreRegistry::empty();
628        assert_eq!(
629            "file",
630            registry
631                .calculate_object_store_prefix("c://dos/path", None)
632                .unwrap()
633        );
634    }
635
636    // Test that paths with a given scheme get mapped to that storage provider.
637    #[test]
638    fn test_calculate_object_store_prefix_for_dummy_path() {
639        let registry = ObjectStoreRegistry::empty();
640        registry.insert("dummy", Arc::new(DummyProvider));
641        assert_eq!(
642            "dummy$mybucket",
643            registry
644                .calculate_object_store_prefix("dummy://mybucket/my/long/path", None)
645                .unwrap()
646        );
647    }
648
649    #[tokio::test]
650    async fn test_stats_hit_miss_tracking() {
651        use crate::object_store::StorageOptionsAccessor;
652        let registry = ObjectStoreRegistry::default();
653        let url = Url::parse("memory://test").unwrap();
654
655        let params1 = ObjectStoreParams::default();
656        let params2 = ObjectStoreParams {
657            storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
658                HashMap::from([("k".into(), "v".into())]),
659            ))),
660            ..Default::default()
661        };
662
663        // (hits, misses, active)
664        let cases: &[(&ObjectStoreParams, (u64, u64, usize))] = &[
665            (&params1, (0, 1, 1)), // miss: new params
666            (&params1, (1, 1, 1)), // hit: same params
667            (&params2, (1, 2, 2)), // miss: different storage_options
668        ];
669
670        let mut stores = vec![]; // retain the stores
671        for (params, (hits, misses, active)) in cases {
672            stores.push(registry.get_store(url.clone(), params).await.unwrap());
673            let s = registry.stats();
674            assert_eq!(
675                (s.hits, s.misses, s.active_stores),
676                (*hits, *misses, *active)
677            );
678        }
679
680        // Same params returns same instance
681        assert!(Arc::ptr_eq(&stores[0], &stores[1]));
682    }
683
684    #[tokio::test]
685    async fn test_new_store_bypasses_cache() {
686        let registry = ObjectStoreRegistry::default();
687        let url = Url::parse("memory://test").unwrap();
688        let params = ObjectStoreParams::default();
689
690        let first = registry.new_store(url.clone(), &params).await.unwrap();
691        let second = registry.new_store(url, &params).await.unwrap();
692
693        assert!(!Arc::ptr_eq(&first, &second));
694        let stats = registry.stats();
695        assert_eq!((stats.hits, stats.misses, stats.active_stores), (0, 0, 0));
696    }
697}