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

mchades pushed a commit to branch branch-2.0
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/branch-2.0 by this push:
     new 6a649ba424 [Cherry-pick to branch-2.0] [#13890] fix(gvfs): Use fileset 
metadata cache when resolving properties and secrets (#13891) (#15085)
6a649ba424 is described below

commit 6a649ba4245eccd90fb7a5039e74ae124e8f9935
Author: mchades <[email protected]>
AuthorDate: Wed Nov 18 22:44:18 2026 +0800

    [Cherry-pick to branch-2.0] [#13890] fix(gvfs): Use fileset metadata cache 
when resolving properties and secrets (#13891) (#15085)
    
    **Cherry-pick Information:**
    - Original commit: de847eec1d279406173a85952aefd11665931139
    - Target branch: `branch-2.0`
    - Status: ✅ Clean cherry-pick (no conflicts)
    - Fork CI: runs in `mchades/gravitino`; re-run it there or push to this
    PR branch
    
    Signed-off-by: Bruce Arctor <[email protected]>
    Co-authored-by: brucearctor <[email protected]>
---
 .../gravitino/filesystem/gvfs_base_operations.py   | 154 +++++---
 .../filesystem/gvfs_default_operations.py          | 417 +++++++++++----------
 .../tests/integration/test_gvfs_with_s3.py         |   1 +
 .../tests/unittests/test_gvfs_merge_secrets.py     | 268 +++++++++++++
 .../filesystem/hadoop/BaseGVFSOperations.java      |  15 +-
 .../filesystem/hadoop/FilesetMetadataCache.java    |  27 +-
 .../hadoop/TestBaseGVFSOperationsSecrets.java      | 152 +++++++-
 .../hadoop/TestFilesetMetadataCache.java           |  45 +++
 docs/how-to-use-gvfs.md                            |   2 +-
 9 files changed, 812 insertions(+), 269 deletions(-)

diff --git a/clients/client-python/gravitino/filesystem/gvfs_base_operations.py 
b/clients/client-python/gravitino/filesystem/gvfs_base_operations.py
index 7cb66627da..f3e8901a28 100644
--- a/clients/client-python/gravitino/filesystem/gvfs_base_operations.py
+++ b/clients/client-python/gravitino/filesystem/gvfs_base_operations.py
@@ -14,6 +14,7 @@
 # KIND, either express or implied.  See the License for the
 # specific language governing permissions and limitations
 # under the License.
+# pylint: disable=too-many-lines
 import logging
 import os
 import sys
@@ -21,7 +22,7 @@ import threading
 import time
 from abc import ABC, abstractmethod
 from pathlib import PurePosixPath
-from typing import Dict, Tuple, Optional, List
+from typing import Any, Dict, Tuple, Optional, List
 from urllib.error import URLError
 from urllib.parse import urlparse
 
@@ -76,6 +77,27 @@ _CREDENTIAL_INFO_TO_GVFS_KEYS = {
 }
 
 
+class _OperationScope:  # pylint: disable=too-few-public-methods
+    """Shares catalogs and filesets loaded during a single GVFS operation."""
+
+    def __init__(self, scope_local: threading.local):
+        self._scope_local = scope_local
+        self._outermost = getattr(scope_local, "scope", None) is None
+        self.catalogs: Dict[NameIdentifier, Any] = {}
+        # Keyed by fileset_catalog identity so a fileset loaded through an
+        # overriding _get_fileset_catalog is not reused for another catalog.
+        self.filesets: Dict[int, Tuple[object, Dict[NameIdentifier, Fileset]]] 
= {}
+
+    def __enter__(self):
+        if self._outermost:
+            self._scope_local.scope = self
+        return self
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        if self._outermost:
+            delattr(self._scope_local, "scope")
+
+
 class FileSystemCacheKey:
     """
     A cache key for filesystem instances following fsspec's native caching 
behavior.
@@ -263,6 +285,7 @@ class BaseGVFSOperations(ABC):
             )
         )
         self._current_location_name = self._init_current_location_name()
+        self._scope_local = threading.local()
         self._kwargs = kwargs
 
     def _get_gravitino_client(self):
@@ -543,11 +566,9 @@ class BaseGVFSOperations(ABC):
             )
             fileset = self._get_fileset(fileset_ident)
         else:
-            catalog = self._get_gravitino_client().load_catalog(catalog_name)
+            catalog = self._load_catalog(NameIdentifier.of(metalake_name, 
catalog_name))
             schema = catalog.as_schemas().load_schema(schema_name)
-            fileset = catalog.as_fileset_catalog().load_fileset(
-                NameIdentifier.of(schema_name, fileset_ident.name())
-            )
+            fileset = self._load_fileset(fileset_ident, 
catalog.as_fileset_catalog())
         # Masked placeholders are skipped, as the Java client does: a cached 
entry can still
         # hold one for a secret removed since, which would overwrite a value 
merged before it.
         fileset_props = self._omit_masked_properties(catalog.properties())
@@ -648,53 +669,56 @@ class BaseGVFSOperations(ABC):
         :param location_name: The location name, None means the default 
location
         :return: The actual filesystem
         """
-        fileset = self._get_fileset(fileset_ident)
-
-        # Determine target location name
-        target_location_name = (
-            location_name
-            or fileset.properties().get(fileset.PROPERTY_DEFAULT_LOCATION_NAME)
-            or fileset.LOCATION_NAME_UNKNOWN
-        )
+        with self._open_operation_scope():
+            fileset = self._get_fileset(fileset_ident)
 
-        # Get the actual storage location
-        actual_location = fileset.storage_locations().get(target_location_name)
-        if actual_location is None:
-            raise NoSuchLocationNameException(
-                f"Cannot find the location: {target_location_name} in fileset: 
{fileset_ident}"
+            # Determine target location name
+            target_location_name = (
+                location_name
+                or 
fileset.properties().get(fileset.PROPERTY_DEFAULT_LOCATION_NAME)
+                or fileset.LOCATION_NAME_UNKNOWN
             )
 
-        fileset_props = self._merge_fileset_properties(fileset_ident, 
actual_location)
-
-        # Set caller context for credential vending
-        if location_name:
-            context = {
-                Credential.HTTP_HEADER_CURRENT_LOCATION_NAME: location_name,
-            }
-            caller_context: CallerContext = CallerContext(context)
-            CallerContextHolder.set(caller_context)
+            # Get the actual storage location
+            actual_location = 
fileset.storage_locations().get(target_location_name)
+            if actual_location is None:
+                raise NoSuchLocationNameException(
+                    f"Cannot find the location: {target_location_name} in 
fileset: {fileset_ident}"
+                )
 
-        try:
-            # Get credentials with client-side caching to avoid redundant REST 
calls
-            credentials = self._get_credentials_with_cache(
-                fileset_ident, fileset, target_location_name
+            fileset_props = self._merge_fileset_properties(
+                fileset_ident, actual_location
             )
 
-            # Get the filesystem using the new path-based caching approach
-            # This matches how Java GVFS caches by (scheme, authority, config)
-            actual_fs = self._get_filesystem(
-                credentials,
-                fileset_props,
-                actual_location,
-                **self._kwargs,
-            )
+            # Set caller context for credential vending
+            if location_name:
+                context = {
+                    Credential.HTTP_HEADER_CURRENT_LOCATION_NAME: 
location_name,
+                }
+                caller_context: CallerContext = CallerContext(context)
+                CallerContextHolder.set(caller_context)
+
+            try:
+                # Get credentials with client-side caching to avoid redundant 
REST calls
+                credentials = self._get_credentials_with_cache(
+                    fileset_ident, fileset, target_location_name
+                )
 
-            self._create_fileset_location_if_needed(
-                fileset_props, actual_fs, actual_location
-            )
-            return actual_fs
-        finally:
-            CallerContextHolder.remove()
+                # Get the filesystem using the new path-based caching approach
+                # This matches how Java GVFS caches by (scheme, authority, 
config)
+                actual_fs = self._get_filesystem(
+                    credentials,
+                    fileset_props,
+                    actual_location,
+                    **self._kwargs,
+                )
+
+                self._create_fileset_location_if_needed(
+                    fileset_props, actual_fs, actual_location
+                )
+                return actual_fs
+            finally:
+                CallerContextHolder.remove()
 
     def _create_fileset_location_if_needed(
         self,
@@ -918,9 +942,41 @@ class BaseGVFSOperations(ABC):
         finally:
             write_lock.release()
 
+    def _open_operation_scope(self):
+        return _OperationScope(self._scope_local)
+
+    def _load_catalog(self, catalog_ident: NameIdentifier):
+        scope = getattr(self._scope_local, "scope", None)
+        if scope is None:
+            return 
self._get_gravitino_client().load_catalog(catalog_ident.name())
+        catalog = scope.catalogs.get(catalog_ident)
+        if catalog is None:
+            catalog = 
self._get_gravitino_client().load_catalog(catalog_ident.name())
+            scope.catalogs[catalog_ident] = catalog
+        return catalog
+
+    def _load_fileset(self, fileset_ident: NameIdentifier, fileset_catalog):
+        ident = NameIdentifier.of(
+            fileset_ident.namespace().level(2), fileset_ident.name()
+        )
+        scope = getattr(self._scope_local, "scope", None)
+        if scope is None:
+            return fileset_catalog.load_fileset(ident)
+        entry = scope.filesets.get(id(fileset_catalog))
+        if entry is None:
+            catalog_filesets: Dict[NameIdentifier, Fileset] = {}
+            scope.filesets[id(fileset_catalog)] = (fileset_catalog, 
catalog_filesets)
+        else:
+            catalog_filesets = entry[1]
+        fileset = catalog_filesets.get(fileset_ident)
+        if fileset is None:
+            fileset = fileset_catalog.load_fileset(ident)
+            catalog_filesets[fileset_ident] = fileset
+        return fileset
+
     def _get_fileset_catalog(self, catalog_ident: NameIdentifier):
         if not self._enable_fileset_metadata_cache:
-            return 
self._get_gravitino_client().load_catalog(catalog_ident.name())
+            return self._load_catalog(catalog_ident)
 
         read_lock = self._catalog_cache_lock.gen_rlock()
         try:
@@ -949,11 +1005,7 @@ class BaseGVFSOperations(ABC):
                 fileset_ident.namespace().level(0), 
fileset_ident.namespace().level(1)
             )
             catalog: FilesetCatalog = self._get_fileset_catalog(catalog_ident)
-            return catalog.as_fileset_catalog().load_fileset(
-                NameIdentifier.of(
-                    fileset_ident.namespace().level(2), fileset_ident.name()
-                )
-            )
+            return self._load_fileset(fileset_ident, 
catalog.as_fileset_catalog())
 
         read_lock = self._fileset_cache_lock.gen_rlock()
         try:
diff --git 
a/clients/client-python/gravitino/filesystem/gvfs_default_operations.py 
b/clients/client-python/gravitino/filesystem/gvfs_default_operations.py
index e6687b10c7..109cb2dfbb 100644
--- a/clients/client-python/gravitino/filesystem/gvfs_default_operations.py
+++ b/clients/client-python/gravitino/filesystem/gvfs_default_operations.py
@@ -42,43 +42,44 @@ class DefaultGVFSOperations(BaseGVFSOperations):
         :param kwargs: Extra args
         :return If details is true, returns a list of file info dicts, else 
returns a list of file paths
         """
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, FilesetDataOperation.LIST_STATUS
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
-
-        pre_process_path: str = self._pre_process_path(path)
-        identifier: NameIdentifier = extract_identifier(
-            self._metalake, pre_process_path
-        )
-        sub_path: str = get_sub_path_from_virtual_path(identifier, 
pre_process_path)
-        fileset_location: str = actual_file_path[
-            : len(actual_file_path) - len(sub_path)
-        ]
-
-        paths_or_entries = actual_fs.ls(
-            storage_handler.strip_storage_protocol(actual_file_path),
-            detail=detail,
-        )
-        # return entries with details
-        if detail:
-            virtual_entries = [
-                storage_handler.actual_info_to_gvfs_info(
-                    entry, fileset_location, to_gvfs_path_prefix(identifier)
-                )
-                for entry in paths_or_entries
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, 
FilesetDataOperation.LIST_STATUS
+            )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
+
+            pre_process_path: str = self._pre_process_path(path)
+            identifier: NameIdentifier = extract_identifier(
+                self._metalake, pre_process_path
+            )
+            sub_path: str = get_sub_path_from_virtual_path(identifier, 
pre_process_path)
+            fileset_location: str = actual_file_path[
+                : len(actual_file_path) - len(sub_path)
             ]
-            return virtual_entries
 
-        # only returns paths
-        virtual_entry_paths = [
-            storage_handler.actual_path_to_gvfs_path(
-                entry_path, fileset_location, to_gvfs_path_prefix(identifier)
+            paths_or_entries = actual_fs.ls(
+                storage_handler.strip_storage_protocol(actual_file_path),
+                detail=detail,
             )
-            for entry_path in paths_or_entries
-        ]
-        return virtual_entry_paths
+            # return entries with details
+            if detail:
+                virtual_entries = [
+                    storage_handler.actual_info_to_gvfs_info(
+                        entry, fileset_location, 
to_gvfs_path_prefix(identifier)
+                    )
+                    for entry in paths_or_entries
+                ]
+                return virtual_entries
+
+            # only returns paths
+            virtual_entry_paths = [
+                storage_handler.actual_path_to_gvfs_path(
+                    entry_path, fileset_location, 
to_gvfs_path_prefix(identifier)
+                )
+                for entry_path in paths_or_entries
+            ]
+            return virtual_entry_paths
 
     def info(self, path, **kwargs):
         """Get file info.
@@ -86,27 +87,28 @@ class DefaultGVFSOperations(BaseGVFSOperations):
         :param kwargs: Extra args
         :return A file info dict
         """
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, 
FilesetDataOperation.GET_FILE_STATUS
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
-
-        pre_process_path: str = self._pre_process_path(path)
-        identifier: NameIdentifier = extract_identifier(
-            self._metalake, pre_process_path
-        )
-        sub_path: str = get_sub_path_from_virtual_path(identifier, 
pre_process_path)
-        fileset_location: str = actual_file_path[
-            : len(actual_file_path) - len(sub_path)
-        ]
-
-        entry_info = actual_fs.info(
-            storage_handler.strip_storage_protocol(actual_file_path)
-        )
-        return storage_handler.actual_info_to_gvfs_info(
-            entry_info, fileset_location, to_gvfs_path_prefix(identifier)
-        )
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, 
FilesetDataOperation.GET_FILE_STATUS
+            )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
+
+            pre_process_path: str = self._pre_process_path(path)
+            identifier: NameIdentifier = extract_identifier(
+                self._metalake, pre_process_path
+            )
+            sub_path: str = get_sub_path_from_virtual_path(identifier, 
pre_process_path)
+            fileset_location: str = actual_file_path[
+                : len(actual_file_path) - len(sub_path)
+            ]
+
+            entry_info = actual_fs.info(
+                storage_handler.strip_storage_protocol(actual_file_path)
+            )
+            return storage_handler.actual_info_to_gvfs_info(
+                entry_info, fileset_location, to_gvfs_path_prefix(identifier)
+            )
 
     def exists(self, path, **kwargs):
         """Check if a file or a directory exists.
@@ -114,15 +116,16 @@ class DefaultGVFSOperations(BaseGVFSOperations):
         :param kwargs: Extra args
         :return If a file or directory exists, it returns True, otherwise False
         """
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, FilesetDataOperation.EXISTS
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, FilesetDataOperation.EXISTS
+            )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
 
-        return actual_fs.exists(
-            storage_handler.strip_storage_protocol(actual_file_path)
-        )
+            return actual_fs.exists(
+                storage_handler.strip_storage_protocol(actual_file_path)
+            )
 
     def cp_file(self, path1, path2, **kwargs):
         """Copy a file.
@@ -134,19 +137,22 @@ class DefaultGVFSOperations(BaseGVFSOperations):
         src_path = self._pre_process_path(path1)
         dst_path = self._pre_process_path(path2)
 
-        actual_fs = self._get_actual_filesystem(src_path, 
self.current_location_name)
-        actual_src_file_path = self._get_actual_file_path(
-            src_path, self.current_location_name, 
FilesetDataOperation.COPY_FILE
-        )
-        actual_dst_file_path = self._get_actual_file_path(
-            dst_path, self.current_location_name, 
FilesetDataOperation.COPY_FILE
-        )
-        storage_handler = get_storage_handler_by_path(actual_src_file_path)
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(
+                src_path, self.current_location_name
+            )
+            actual_src_file_path = self._get_actual_file_path(
+                src_path, self.current_location_name, 
FilesetDataOperation.COPY_FILE
+            )
+            actual_dst_file_path = self._get_actual_file_path(
+                dst_path, self.current_location_name, 
FilesetDataOperation.COPY_FILE
+            )
+            storage_handler = get_storage_handler_by_path(actual_src_file_path)
 
-        actual_fs.cp_file(
-            storage_handler.strip_storage_protocol(actual_src_file_path),
-            storage_handler.strip_storage_protocol(actual_dst_file_path),
-        )
+            actual_fs.cp_file(
+                storage_handler.strip_storage_protocol(actual_src_file_path),
+                storage_handler.strip_storage_protocol(actual_dst_file_path),
+            )
 
     def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs):
         """Move a file to another directory.
@@ -162,27 +168,30 @@ class DefaultGVFSOperations(BaseGVFSOperations):
         src_path = self._pre_process_path(path1)
         dst_path = self._pre_process_path(path2)
 
-        actual_fs = self._get_actual_filesystem(src_path, 
self.current_location_name)
-        src_actual_path = self._get_actual_file_path(
-            src_path, self.current_location_name, FilesetDataOperation.RENAME
-        )
-        dst_actual_path = self._get_actual_file_path(
-            dst_path, self.current_location_name, FilesetDataOperation.RENAME
-        )
-        storage_handler = get_storage_handler_by_path(src_actual_path)
-
-        if storage_handler.storage_type() == StorageType.LOCAL:
-            actual_fs.mv(
-                path1=storage_handler.strip_storage_protocol(src_actual_path),
-                path2=storage_handler.strip_storage_protocol(dst_actual_path),
-                recursive=recursive,
-                maxdepth=maxdepth,
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(
+                src_path, self.current_location_name
             )
-        else:
-            actual_fs.mv(
-                storage_handler.strip_storage_protocol(src_actual_path),
-                storage_handler.strip_storage_protocol(dst_actual_path),
+            src_actual_path = self._get_actual_file_path(
+                src_path, self.current_location_name, 
FilesetDataOperation.RENAME
             )
+            dst_actual_path = self._get_actual_file_path(
+                dst_path, self.current_location_name, 
FilesetDataOperation.RENAME
+            )
+            storage_handler = get_storage_handler_by_path(src_actual_path)
+
+            if storage_handler.storage_type() == StorageType.LOCAL:
+                actual_fs.mv(
+                    
path1=storage_handler.strip_storage_protocol(src_actual_path),
+                    
path2=storage_handler.strip_storage_protocol(dst_actual_path),
+                    recursive=recursive,
+                    maxdepth=maxdepth,
+                )
+            else:
+                actual_fs.mv(
+                    storage_handler.strip_storage_protocol(src_actual_path),
+                    storage_handler.strip_storage_protocol(dst_actual_path),
+                )
 
     def rm(self, path, recursive=False, maxdepth=None):
         """Remove a file or directory.
@@ -191,36 +200,38 @@ class DefaultGVFSOperations(BaseGVFSOperations):
                 When removing a directory, this parameter should be True.
         :param maxdepth: The maximum depth to remove the directory recursively.
         """
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, FilesetDataOperation.DELETE
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
-
-        # S3FileSystem and ocifs don't support maxdepth
-        if storage_handler.storage_type() in [StorageType.S3A]:
-            actual_fs.rm(
-                storage_handler.strip_storage_protocol(actual_file_path),
-                recursive,
-            )
-        else:
-            actual_fs.rm(
-                storage_handler.strip_storage_protocol(actual_file_path),
-                recursive,
-                maxdepth,
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, FilesetDataOperation.DELETE
             )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
+
+            # S3FileSystem and ocifs don't support maxdepth
+            if storage_handler.storage_type() in [StorageType.S3A]:
+                actual_fs.rm(
+                    storage_handler.strip_storage_protocol(actual_file_path),
+                    recursive,
+                )
+            else:
+                actual_fs.rm(
+                    storage_handler.strip_storage_protocol(actual_file_path),
+                    recursive,
+                    maxdepth,
+                )
 
     def rm_file(self, path):
         """Remove a file.
         :param path: Virtual fileset path
         """
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, FilesetDataOperation.DELETE
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, FilesetDataOperation.DELETE
+            )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
 
-        
actual_fs.rm_file(storage_handler.strip_storage_protocol(actual_file_path))
+            
actual_fs.rm_file(storage_handler.strip_storage_protocol(actual_file_path))
 
     def rmdir(self, path):
         """Remove a directory.
@@ -228,13 +239,14 @@ class DefaultGVFSOperations(BaseGVFSOperations):
         And it will throw an exception if delete a directory which is 
non-empty for LocalFileSystem.
         :param path: Virtual fileset path
         """
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, FilesetDataOperation.DELETE
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, FilesetDataOperation.DELETE
+            )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
 
-        
actual_fs.rmdir(storage_handler.strip_storage_protocol(actual_file_path))
+            
actual_fs.rmdir(storage_handler.strip_storage_protocol(actual_file_path))
 
     def open(
         self,
@@ -261,20 +273,21 @@ class DefaultGVFSOperations(BaseGVFSOperations):
         else:
             data_operation = FilesetDataOperation.OPEN
 
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, data_operation
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
-
-        return actual_fs.open(
-            storage_handler.strip_storage_protocol(actual_file_path),
-            mode,
-            block_size,
-            cache_options,
-            compression,
-            **kwargs,
-        )
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, data_operation
+            )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
+
+            return actual_fs.open(
+                storage_handler.strip_storage_protocol(actual_file_path),
+                mode,
+                block_size,
+                cache_options,
+                compression,
+                **kwargs,
+            )
 
     def mkdir(self, path, create_parents=True, **kwargs):
         """Make a directory.
@@ -284,33 +297,35 @@ class DefaultGVFSOperations(BaseGVFSOperations):
         :param create_parents: Create parent directories if missing when set 
to True
         :param kwargs: Extra args
         """
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, FilesetDataOperation.MKDIRS
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
-
-        actual_fs.mkdir(
-            storage_handler.strip_storage_protocol(actual_file_path),
-            create_parents,
-            **kwargs,
-        )
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, FilesetDataOperation.MKDIRS
+            )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
+
+            actual_fs.mkdir(
+                storage_handler.strip_storage_protocol(actual_file_path),
+                create_parents,
+                **kwargs,
+            )
 
     def makedirs(self, path, exist_ok=True):
         """Make a directory recursively.
         :param path: Virtual fileset path
         :param exist_ok: Continue if a directory already exists
         """
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, FilesetDataOperation.MKDIRS
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, FilesetDataOperation.MKDIRS
+            )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
 
-        actual_fs.makedirs(
-            storage_handler.strip_storage_protocol(actual_file_path),
-            exist_ok,
-        )
+            actual_fs.makedirs(
+                storage_handler.strip_storage_protocol(actual_file_path),
+                exist_ok,
+            )
 
     def created(self, path):
         """Return the created timestamp of a file as a datetime.datetime
@@ -318,35 +333,37 @@ class DefaultGVFSOperations(BaseGVFSOperations):
         :param path: Virtual fileset path
         :return Created time(datetime.datetime)
         """
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, FilesetDataOperation.CREATED_TIME
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
-        if storage_handler.storage_type() != StorageType.LOCAL:
-            raise GravitinoRuntimeException(
-                f"Storage type:{storage_handler.storage_type()} doesn't 
support now."
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, 
FilesetDataOperation.CREATED_TIME
             )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
+            if storage_handler.storage_type() != StorageType.LOCAL:
+                raise GravitinoRuntimeException(
+                    f"Storage type:{storage_handler.storage_type()} doesn't 
support now."
+                )
 
-        created_time = actual_fs.created(
-            storage_handler.strip_storage_protocol(actual_file_path)
-        )
-        return created_time
+            created_time = actual_fs.created(
+                storage_handler.strip_storage_protocol(actual_file_path)
+            )
+            return created_time
 
     def modified(self, path):
         """Returns the modified time of the path file if it exists.
         :param path: Virtual fileset path
         :return Modified time(datetime.datetime)
         """
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, 
FilesetDataOperation.MODIFIED_TIME
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, 
FilesetDataOperation.MODIFIED_TIME
+            )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
 
-        return actual_fs.modified(
-            storage_handler.strip_storage_protocol(actual_file_path)
-        )
+            return actual_fs.modified(
+                storage_handler.strip_storage_protocol(actual_file_path)
+            )
 
     def cat_file(self, path, start=None, end=None, **kwargs):
         """Get the content of a file.
@@ -356,18 +373,19 @@ class DefaultGVFSOperations(BaseGVFSOperations):
         :param kwargs: Extra args
         :return File content
         """
-        actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            path, self.current_location_name, 
FilesetDataOperation.GET_FILE_STATUS
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
-
-        return actual_fs.cat_file(
-            storage_handler.strip_storage_protocol(actual_file_path),
-            start,
-            end,
-            **kwargs,
-        )
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(path, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                path, self.current_location_name, 
FilesetDataOperation.GET_FILE_STATUS
+            )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
+
+            return actual_fs.cat_file(
+                storage_handler.strip_storage_protocol(actual_file_path),
+                start,
+                end,
+                **kwargs,
+            )
 
     def get_file(self, rpath, lpath, callback=None, outfile=None, **kwargs):
         """Copy single remote file to local.
@@ -384,14 +402,15 @@ class DefaultGVFSOperations(BaseGVFSOperations):
                 "Doesn't support copy a remote gvfs file to an another remote 
file."
             )
 
-        actual_fs = self._get_actual_filesystem(rpath, 
self.current_location_name)
-        actual_file_path = self._get_actual_file_path(
-            rpath, self.current_location_name, FilesetDataOperation.GET_FILE
-        )
-        storage_handler = get_storage_handler_by_path(actual_file_path)
+        with self._open_operation_scope():
+            actual_fs = self._get_actual_filesystem(rpath, 
self.current_location_name)
+            actual_file_path = self._get_actual_file_path(
+                rpath, self.current_location_name, 
FilesetDataOperation.GET_FILE
+            )
+            storage_handler = get_storage_handler_by_path(actual_file_path)
 
-        actual_fs.get_file(
-            storage_handler.strip_storage_protocol(actual_file_path),
-            lpath,
-            **kwargs,
-        )
+            actual_fs.get_file(
+                storage_handler.strip_storage_protocol(actual_file_path),
+                lpath,
+                **kwargs,
+            )
diff --git a/clients/client-python/tests/integration/test_gvfs_with_s3.py 
b/clients/client-python/tests/integration/test_gvfs_with_s3.py
index 91bce125c7..ed1fdb6bc8 100644
--- a/clients/client-python/tests/integration/test_gvfs_with_s3.py
+++ b/clients/client-python/tests/integration/test_gvfs_with_s3.py
@@ -282,6 +282,7 @@ class TestGvfsWithS3(TestGvfsWithHDFS):
         if fs.operations._enable_fileset_metadata_cache:
             fs.operations._fileset_cache.clear()
             fs.operations._catalog_cache.clear()
+            fs.operations._schema_cache.clear()
 
         s3_fs = fs.operations._get_actual_filesystem(mkdir_dir, None)
         config_kwargs = s3_fs.config_kwargs
diff --git a/clients/client-python/tests/unittests/test_gvfs_merge_secrets.py 
b/clients/client-python/tests/unittests/test_gvfs_merge_secrets.py
index 5d5d3fcb07..4af2eaff7e 100644
--- a/clients/client-python/tests/unittests/test_gvfs_merge_secrets.py
+++ b/clients/client-python/tests/unittests/test_gvfs_merge_secrets.py
@@ -14,21 +14,62 @@
 # KIND, either express or implied.  See the License for the
 # specific language governing permissions and limitations
 # under the License.
+import os
+import tempfile
 import unittest
 from unittest.mock import MagicMock, patch
 from urllib.error import URLError
 
+from gravitino.api.file.fileset import Fileset
+from gravitino.dto.audit_dto import AuditDTO
+from gravitino.dto.fileset_dto import FilesetDTO
 from gravitino.exceptions.base import (
     ForbiddenException,
     NotFoundException,
     RESTException,
 )
+from gravitino.filesystem.gvfs import GravitinoVirtualFileSystem
 from gravitino.filesystem.gvfs_config import GVFSConfig
 from gravitino.filesystem.gvfs_default_operations import DefaultGVFSOperations
 from gravitino.filesystem.gvfs_storage_handler import S3StorageHandler
 from gravitino.name_identifier import NameIdentifier
 
 
+class _CustomGetFilesetOperations(DefaultGVFSOperations):
+    """Test operations subclass overriding _get_fileset with the legacy 1-arg 
signature."""
+
+    custom_fileset = None
+
+    def _get_fileset(self, fileset_ident: NameIdentifier):
+        if self.custom_fileset is not None:
+            return self.custom_fileset
+        return super()._get_fileset(fileset_ident)
+
+
+class _CustomGetFilesetCatalogOperations(DefaultGVFSOperations):
+    """Test operations subclass overriding _get_fileset_catalog with the 
legacy 1-arg signature."""
+
+    custom_catalog = None
+
+    def _get_fileset_catalog(self, catalog_ident: NameIdentifier):
+        if self.custom_catalog is not None:
+            return self.custom_catalog
+        return super()._get_fileset_catalog(catalog_ident)
+
+
+class _CustomMergePropertiesOperations(DefaultGVFSOperations):
+    """Test operations subclass overriding _merge_fileset_properties with 2 
args."""
+
+    def _merge_fileset_properties(
+        self,
+        fileset_ident: NameIdentifier,
+        actual_location: str,
+    ):
+        props = super()._merge_fileset_properties(fileset_ident, 
actual_location)
+        props["custom-location"] = actual_location
+        return props
+
+
 # pylint: disable=protected-access
 class TestGVFSMergeSecrets(unittest.TestCase):
     """Unit tests for _merge_fileset_properties including get_secrets()."""
@@ -432,6 +473,233 @@ class TestGVFSMergeSecrets(unittest.TestCase):
         self.assertEqual(merged["s3-secret-access-key"], "static-secret")
         self.assertNotIn("s3-session-token", merged)
 
+    def test_get_actual_filesystem_loads_once_with_credential_vending(self):
+        operations = DefaultGVFSOperations(
+            server_uri="http://localhost:8090";,
+            metalake_name="ml",
+            options={GVFSConfig.GVFS_FILESYSTEM_ENABLE_CREDENTIAL_VENDING: 
True},
+        )
+        client, catalog, fileset = self._build_client_chain(
+            prefix="client",
+            location="s3://bucket/data",
+            target_file_uri="s3://bucket/data/a",
+        )
+        scoped_cred = MagicMock()
+        scoped_cred.expire_time_in_ms.return_value = 0
+        fileset.support_credentials.return_value.get_credentials.return_value 
= [
+            scoped_cred
+        ]
+        filesystem = MagicMock()
+        ident = NameIdentifier.of("ml", "catalog", "schema", "fs")
+
+        with (
+            patch.object(operations, "_get_gravitino_client", 
return_value=client),
+            patch.object(operations, "_get_user_defined_configs", 
return_value={}),
+            patch.object(
+                operations, "_get_filesystem", return_value=filesystem
+            ) as create_fs,
+        ):
+            self.assertIs(
+                filesystem,
+                operations._get_actual_filesystem_by_location_name(ident, 
"default"),
+            )
+
+        create_fs.assert_called_once()
+        client.load_catalog.assert_called_once_with("catalog")
+        
catalog.as_schemas.return_value.load_schema.assert_called_once_with("schema")
+        
catalog.as_fileset_catalog.return_value.load_fileset.assert_called_once_with(
+            NameIdentifier.of("schema", "fs")
+        )
+        
fileset.support_credentials.return_value.get_credentials.assert_called_once_with()
+
+    def test_exists_loads_catalog_and_fileset_once_when_cache_disabled(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            loc_dir = os.path.join(tmp_dir, "loc")
+            os.makedirs(loc_dir)
+            target_file = os.path.join(loc_dir, "data.txt")
+            with open(target_file, "w", encoding="utf-8") as fp:
+                fp.write("hello")
+
+            client, catalog, _ = self._build_client_chain(
+                prefix="client",
+                location=f"file://{loc_dir}",
+                target_file_uri=f"file://{target_file}",
+            )
+            gvfs = GravitinoVirtualFileSystem(
+                server_uri="http://localhost:8090";,
+                metalake_name="ml",
+                options={
+                    GVFSConfig.GVFS_FILESYSTEM_ENABLE_FILESET_METADATA_CACHE: 
False
+                },
+                skip_instance_cache=True,
+            )
+            with patch.object(
+                gvfs.operations, "_get_gravitino_client", return_value=client
+            ):
+                self.assertTrue(
+                    gvfs.exists("gvfs://fileset/catalog/schema/fs/data.txt")
+                )
+                self.assertEqual(client.load_catalog.call_count, 1)
+                self.assertEqual(
+                    catalog.as_schemas.return_value.load_schema.call_count, 1
+                )
+                self.assertEqual(
+                    
catalog.as_fileset_catalog.return_value.load_fileset.call_count, 1
+                )
+
+                # A subsequent operation opens a new scope and performs a 
fresh load.
+                self.assertTrue(
+                    gvfs.exists("gvfs://fileset/catalog/schema/fs/data.txt")
+                )
+                self.assertEqual(client.load_catalog.call_count, 2)
+                self.assertEqual(
+                    
catalog.as_fileset_catalog.return_value.load_fileset.call_count, 2
+                )
+
+    @staticmethod
+    def _build_client_chain(prefix: str, location: str, target_file_uri: str):
+        catalog = MagicMock()
+        catalog.as_fileset_catalog.return_value = catalog
+        schema = MagicMock()
+        fileset = MagicMock()
+
+        catalog.properties.return_value = {"c-prop": f"from-{prefix}"}
+        catalog.get_secrets.return_value = {"c-secret": f"{prefix}-cat-secret"}
+        catalog.as_schemas.return_value.load_schema.return_value = schema
+        schema.properties.return_value = {"s-prop": f"from-{prefix}"}
+        schema.get_secrets.return_value = {"s-secret": f"{prefix}-sch-secret"}
+        catalog.load_fileset.return_value = fileset
+        catalog.get_file_location.return_value = target_file_uri
+        fileset.PROPERTY_DEFAULT_LOCATION_NAME = 
Fileset.PROPERTY_DEFAULT_LOCATION_NAME
+        fileset.LOCATION_NAME_UNKNOWN = Fileset.LOCATION_NAME_UNKNOWN
+        fileset.properties.return_value = {
+            Fileset.PROPERTY_DEFAULT_LOCATION_NAME: "default",
+            "f-prop": f"from-{prefix}",
+            f"{prefix}-only": "1",
+        }
+        fileset.get_secrets.return_value = {
+            "f-secret": f"{prefix}-secret",
+            f"{prefix}-sec-only": "1",
+        }
+        fileset.storage_locations.return_value = {"default": location}
+
+        client = MagicMock()
+        client.load_catalog.return_value = catalog
+        return client, catalog, fileset
+
+    def _run_hook_exists_check(
+        self,
+        ops_cls,
+        enable_cache: bool,
+        client_location: str,
+        hook_location: str,
+        target_file: str,
+    ):
+        target_uri = f"file://{target_file}"
+        client, _, _ = self._build_client_chain(
+            prefix="client", location=client_location, 
target_file_uri=target_uri
+        )
+        gvfs = GravitinoVirtualFileSystem(
+            server_uri="http://localhost:8090";,
+            metalake_name="ml",
+            options={
+                GVFSConfig.GVFS_FILESYSTEM_ENABLE_FILESET_METADATA_CACHE: 
enable_cache,
+                GVFSConfig.GVFS_FILESYSTEM_OPERATIONS: (
+                    f"{ops_cls.__module__}.{ops_cls.__name__}"
+                ),
+            },
+            skip_instance_cache=True,
+        )
+        with (
+            patch.object(gvfs.operations, "_get_gravitino_client", 
return_value=client),
+            patch.object(
+                gvfs.operations,
+                "_get_filesystem",
+                wraps=gvfs.operations._get_filesystem,
+            ) as get_fs_spy,
+        ):
+            
self.assertTrue(gvfs.exists("gvfs://fileset/catalog/schema/fs/data.txt"))
+            merged_props, actual_path = get_fs_spy.call_args.args[1:3]
+            if ops_cls in (
+                _CustomGetFilesetOperations,
+                _CustomGetFilesetCatalogOperations,
+            ):
+                self.assertEqual(actual_path, hook_location)
+                self.assertEqual(merged_props.get("c-prop"), "from-client")
+                self.assertEqual(merged_props.get("c-secret"), 
"client-cat-secret")
+                self.assertEqual(merged_props.get("s-prop"), "from-client")
+                self.assertEqual(merged_props.get("s-secret"), 
"client-sch-secret")
+                self.assertEqual(merged_props.get("f-prop"), "from-client")
+                self.assertEqual(merged_props.get("f-secret"), "client-secret")
+                self.assertNotIn("hook-only", merged_props)
+                self.assertNotIn("hook-sec-only", merged_props)
+                self.assertNotIn("dto-prop", merged_props)
+            else:
+                self.assertEqual(actual_path, client_location)
+                self.assertEqual(merged_props.get("custom-location"), 
client_location)
+
+    def test_custom_hooks_keep_client_properties_when_cache_disabled(self):
+        with tempfile.TemporaryDirectory() as tmp_dir:
+            client_dir = os.path.join(tmp_dir, "client-loc")
+            hook_dir = os.path.join(tmp_dir, "hook-loc")
+            os.makedirs(client_dir)
+            os.makedirs(hook_dir)
+            target_file = os.path.join(hook_dir, "data.txt")
+            with open(target_file, "w", encoding="utf-8") as fp:
+                fp.write("hello")
+
+            client_location = f"file://{client_dir}"
+            hook_location = f"file://{hook_dir}"
+
+            _, hook_catalog, hook_fileset = self._build_client_chain(
+                prefix="hook",
+                location=hook_location,
+                target_file_uri=f"file://{target_file}",
+            )
+            dto_fileset = FilesetDTO(
+                _name="fs",
+                _comment="dto",
+                _type=Fileset.Type.MANAGED,
+                _properties={
+                    Fileset.PROPERTY_DEFAULT_LOCATION_NAME: "default",
+                    "dto-prop": "1",
+                },
+                _storage_locations={"default": hook_location},
+                _audit=AuditDTO(_creator="test"),
+            )
+
+            try:
+                for hook_fs in (hook_fileset, dto_fileset):
+                    _CustomGetFilesetOperations.custom_fileset = hook_fs
+                    self._run_hook_exists_check(
+                        _CustomGetFilesetOperations,
+                        False,
+                        client_location,
+                        hook_location,
+                        target_file,
+                    )
+
+                _CustomGetFilesetCatalogOperations.custom_catalog = 
hook_catalog
+                self._run_hook_exists_check(
+                    _CustomGetFilesetCatalogOperations,
+                    False,
+                    client_location,
+                    hook_location,
+                    target_file,
+                )
+
+                for enable_cache in (False, True):
+                    self._run_hook_exists_check(
+                        _CustomMergePropertiesOperations,
+                        enable_cache,
+                        client_location,
+                        hook_location,
+                        target_file,
+                    )
+            finally:
+                _CustomGetFilesetOperations.custom_fileset = None
+                _CustomGetFilesetCatalogOperations.custom_catalog = None
+
 
 if __name__ == "__main__":
     unittest.main()
diff --git 
a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
 
b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
index a14583a5a2..4b8e6e9b3d 100644
--- 
a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
+++ 
b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
@@ -676,11 +676,14 @@ public abstract class BaseGVFSOperations implements 
Closeable {
     // If the server-side filesystem ops are disabled, the fileset directory 
may not exist. In such
     // case the operations like create, open, list files under this directory 
will fail. So we
     // need to check the existence of the fileset directory beforehand.
+    Catalog filesetCatalog = (Catalog) getFilesetCatalog(catalogIdent);
+    Map<String, String> catalogProperties =
+        filesetCatalog != null ? filesetCatalog.properties() : null;
     boolean fsOpsDisabled =
-        ((Catalog) getFilesetCatalog(catalogIdent))
-            .properties()
-            .getOrDefault("disable-filesystem-ops", "false")
-            .equalsIgnoreCase("true");
+        catalogProperties != null
+            && catalogProperties
+                .getOrDefault("disable-filesystem-ops", "false")
+                .equalsIgnoreCase("true");
     if (fsOpsDisabled) {
       try {
         if (!fs.exists(filesetPath)) {
@@ -797,14 +800,14 @@ public abstract class BaseGVFSOperations implements 
Closeable {
    * @return the schema.
    */
   protected Schema getSchema(NameIdentifier schemaIdent) {
-    return filesetMetadataCache
+    return getFilesetMetadataCache()
         .map(cache -> cache.getSchema(schemaIdent))
         .orElseGet(
             () -> {
               NameIdentifier catalogIdent =
                   NameIdentifier.of(
                       schemaIdent.namespace().level(0), 
schemaIdent.namespace().level(1));
-              Catalog c = gravitinoClient.loadCatalog(catalogIdent.name());
+              Catalog c = loadCatalog(catalogIdent);
               return c.asSchemas().loadSchema(schemaIdent.name());
             });
   }
diff --git 
a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/FilesetMetadataCache.java
 
b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/FilesetMetadataCache.java
index 048b622bdd..f310271168 100644
--- 
a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/FilesetMetadataCache.java
+++ 
b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/FilesetMetadataCache.java
@@ -84,7 +84,10 @@ public class FilesetMetadataCache implements Closeable {
    * @return the fileset catalog.
    */
   public FilesetCatalog getFilesetCatalog(NameIdentifier catalogIdent) {
-    return getCatalog(catalogIdent).asFilesetCatalog();
+    FilesetCatalog filesetCatalog = 
getCatalog(catalogIdent).asFilesetCatalog();
+    Preconditions.checkArgument(
+        filesetCatalog != null, String.format("Loaded fileset catalog: %s is 
null.", catalogIdent));
+    return filesetCatalog;
   }
 
   /**
@@ -94,14 +97,15 @@ public class FilesetMetadataCache implements Closeable {
    * @return the fileset.
    */
   public Fileset getFileset(NameIdentifier filesetIdent) {
-    NameIdentifier catalogIdent =
-        NameIdentifier.of(filesetIdent.namespace().level(0), 
filesetIdent.namespace().level(1));
-    FilesetCatalog filesetCatalog = getFilesetCatalog(catalogIdent);
     return filesetCache.get(
         filesetIdent,
-        ident ->
-            filesetCatalog.loadFileset(
-                NameIdentifier.of(filesetIdent.namespace().level(2), 
filesetIdent.name())));
+        ident -> {
+          NameIdentifier catalogIdent =
+              NameIdentifier.of(ident.namespace().level(0), 
ident.namespace().level(1));
+          FilesetCatalog filesetCatalog = getFilesetCatalog(catalogIdent);
+          return filesetCatalog.loadFileset(
+              NameIdentifier.of(ident.namespace().level(2), ident.name()));
+        });
   }
 
   /**
@@ -111,10 +115,13 @@ public class FilesetMetadataCache implements Closeable {
    * @return the schema.
    */
   public Schema getSchema(NameIdentifier schemaIdent) {
-    NameIdentifier catalogIdent =
-        NameIdentifier.of(schemaIdent.namespace().level(0), 
schemaIdent.namespace().level(1));
     return schemaCache.get(
-        schemaIdent, ident -> 
getCatalog(catalogIdent).asSchemas().loadSchema(schemaIdent.name()));
+        schemaIdent,
+        ident -> {
+          NameIdentifier catalogIdent =
+              NameIdentifier.of(ident.namespace().level(0), 
ident.namespace().level(1));
+          return getCatalog(catalogIdent).asSchemas().loadSchema(ident.name());
+        });
   }
 
   private Cache<NameIdentifier, Catalog> newCatalogCache() {
diff --git 
a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java
 
b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java
index db10e219d2..3d633e58f5 100644
--- 
a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java
+++ 
b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java
@@ -22,6 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyMap;
 import static org.mockito.Mockito.clearInvocations;
@@ -31,9 +32,11 @@ import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.withSettings;
 
 import java.io.IOException;
 import java.io.UncheckedIOException;
+import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
@@ -524,6 +527,136 @@ public class TestBaseGVFSOperationsSecrets {
     }
   }
 
+  @Test
+  public void testGetSchemaLazyInitializesMetadataCache() throws Exception {
+    Catalog catalog = mock(Catalog.class);
+    Schema schema = mock(Schema.class);
+    SupportsSchemas schemas = mock(SupportsSchemas.class);
+    when(catalog.asSchemas()).thenReturn(schemas);
+    when(schemas.loadSchema("schema")).thenReturn(schema);
+
+    GravitinoClient client = mock(GravitinoClient.class);
+    when(client.loadCatalog("catalog")).thenReturn(catalog);
+
+    Configuration cachedConf = new Configuration();
+    
cachedConf.set(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_METALAKE_KEY,
 "ml");
+    cachedConf.set(
+        GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_SERVER_URI_KEY,
+        "http://localhost:8090";);
+    cachedConf.setBoolean(
+        
GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_FILESET_METADATA_CACHE_ENABLE,
 true);
+
+    NameIdentifier schemaIdent = NameIdentifier.of("ml", "catalog", "schema");
+    try (TestOps cachedOps = new TestOps(cachedConf, client)) {
+      assertSame(schema, cachedOps.getSchema(schemaIdent));
+      assertSame(schema, cachedOps.getSchema(schemaIdent));
+      verify(client, times(1)).loadCatalog("catalog");
+      verify(schemas, times(1)).loadSchema("schema");
+    }
+
+    Configuration uncachedConf = new Configuration();
+    uncachedConf.set(
+        
GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_METALAKE_KEY, "ml");
+    uncachedConf.set(
+        GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_SERVER_URI_KEY,
+        "http://localhost:8090";);
+    try (TestOps uncachedOps = new TestOps(uncachedConf, client)) {
+      assertSame(schema, uncachedOps.getSchema(schemaIdent));
+      verify(client, times(2)).loadCatalog("catalog");
+      verify(schemas, times(2)).loadSchema("schema");
+    }
+  }
+
+  @Test
+  void testCustomGetFilesetWithSecretsDoesNotChangeBackendProperties() throws 
Exception {
+    for (boolean enableCache : new boolean[] {false, true}) {
+      Catalog clientCatalog = mockCatalogWithCredentials(Map.of("c-prop", 
"client"), null);
+      Fileset clientFileset =
+          
clientCatalog.asFilesetCatalog().loadFileset(NameIdentifier.of("schema", "fs"));
+      SupportsSecrets clientSecrets = mock(SupportsSecrets.class);
+      when(clientSecrets.getSecrets()).thenReturn(Map.of("fs-secret", 
"client-secret"));
+      when(clientFileset.properties()).thenReturn(Map.of("fs-prop", 
"client-val"));
+      when(clientFileset.supportsSecrets()).thenReturn(clientSecrets);
+      when(clientFileset.storageLocations()).thenReturn(Map.of("default", 
"s3a://client/data"));
+
+      Fileset hookFileset = mock(Fileset.class);
+      SupportsSecrets hookSecrets = mock(SupportsSecrets.class);
+      when(hookSecrets.getSecrets())
+          .thenReturn(Map.of("fs-secret", "hook-secret", "hook-only", "x"));
+      when(hookFileset.properties()).thenReturn(Map.of("fs-prop", "hook-val"));
+      when(hookFileset.supportsSecrets()).thenReturn(hookSecrets);
+      when(hookFileset.storageLocations()).thenReturn(Map.of("default", 
"s3a://hook/data"));
+
+      try (ScopeProbeOps ops = new ScopeProbeOps(clientCatalog, enableCache)) {
+        ops.hookFileset = hookFileset;
+        ops.getActualFileSystemByLocationName(PROBE_IDENT, "default");
+
+        assertEquals(List.of(new Path("s3a://hook/data")), ops.paths);
+        assertEquals("client-val", ops.props.get(0).get("fs-prop"));
+        assertEquals("client-secret", ops.props.get(0).get("fs-secret"));
+        assertFalse(ops.props.get(0).containsKey("hook-only"));
+      }
+    }
+  }
+
+  @Test
+  void testCreateFilesetLocationUsesHookCatalogDisableFilesystemOpsFlag() 
throws Exception {
+    java.nio.file.Path tempRoot = 
Files.createTempDirectory("gvfs-hook-autocreate");
+    java.nio.file.Path missingDir = tempRoot.resolve("missing-hook-dir");
+    String missingUri = missingDir.toUri().toString();
+
+    Catalog clientCatalog =
+        mockCatalogWithCredentials(Map.of("disable-filesystem-ops", "false"), 
null);
+    Fileset clientFileset =
+        
clientCatalog.asFilesetCatalog().loadFileset(NameIdentifier.of("schema", "fs"));
+    when(clientFileset.storageLocations())
+        .thenReturn(Map.of("default", 
tempRoot.resolve("client-dir").toUri().toString()));
+
+    Catalog hookCatalog = mock(Catalog.class, 
withSettings().extraInterfaces(FilesetCatalog.class));
+    FilesetCatalog hookFilesetCatalog = (FilesetCatalog) hookCatalog;
+    Fileset hookFileset = mock(Fileset.class);
+    when(hookCatalog.properties()).thenReturn(Map.of("disable-filesystem-ops", 
"true"));
+    when(hookFilesetCatalog.loadFileset(NameIdentifier.of("schema", 
"fs"))).thenReturn(hookFileset);
+    when(hookFileset.properties())
+        .thenReturn(Map.of(Fileset.PROPERTY_DEFAULT_LOCATION_NAME, "default"));
+    when(hookFileset.storageLocations()).thenReturn(Map.of("default", 
missingUri));
+    when(hookFilesetCatalog.getFileLocation(NameIdentifier.of("schema", "fs"), 
"", null))
+        .thenReturn(missingUri);
+
+    GravitinoClient client = mock(GravitinoClient.class);
+    when(client.loadCatalog("catalog")).thenReturn(clientCatalog);
+
+    Configuration conf = new Configuration();
+    conf.setBoolean("fs.gvfs.impl.disable.cache", true);
+    conf.setBoolean(
+        
GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_AUTO_CREATE_LOCATION, 
true);
+    
conf.set(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_METALAKE_KEY,
 "ml");
+    conf.set(
+        GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_SERVER_URI_KEY,
+        "http://localhost:8090";);
+
+    try (DefaultGVFSOperations ops =
+        new DefaultGVFSOperations(conf) {
+          @Override
+          GravitinoClient getGravitinoClient() {
+            return client;
+          }
+
+          @Override
+          protected FilesetCatalog getFilesetCatalog(NameIdentifier 
catalogIdent) {
+            return hookFilesetCatalog;
+          }
+        }) {
+      FileStatus[] statuses = ops.listStatus(new 
Path("gvfs://fileset/catalog/schema/fs"));
+      assertEquals(0, statuses.length);
+      assertTrue(Files.isDirectory(missingDir));
+
+      // Verify a null catalog properties map on the hook catalog is safely 
ignored.
+      when(hookCatalog.properties()).thenReturn(null);
+      assertEquals(0, ops.listStatus(new 
Path("gvfs://fileset/catalog/schema/fs")).length);
+    }
+  }
+
   private static class TestOps extends BaseGVFSOperations {
     private final GravitinoClient client;
 
@@ -611,14 +744,28 @@ public class TestBaseGVFSOperationsSecrets {
   private static class ScopeProbeOps extends DefaultGVFSOperations {
     private final GravitinoClient client = mock(GravitinoClient.class);
     private final List<Map<String, String>> props = new ArrayList<>();
+    private final List<Path> paths = new ArrayList<>();
     private FilesetCatalog hookCatalog;
+    private Fileset hookFileset;
     private ScopeProbeOps inner;
 
     private ScopeProbeOps(Catalog catalog) {
-      super(opsConf());
+      this(catalog, false);
+    }
+
+    private ScopeProbeOps(Catalog catalog, boolean enableCache) {
+      super(opsConf(enableCache));
       when(client.loadCatalog("catalog")).thenReturn(catalog);
     }
 
+    private static Configuration opsConf(boolean enableCache) {
+      Configuration conf = TestBaseGVFSOperationsSecrets.opsConf();
+      conf.setBoolean(
+          
GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_FILESET_METADATA_CACHE_ENABLE,
+          enableCache);
+      return conf;
+    }
+
     @Override
     GravitinoClient getGravitinoClient() {
       return client;
@@ -639,11 +786,12 @@ public class TestBaseGVFSOperationsSecrets {
           throw new UncheckedIOException(e);
         }
       }
-      return super.getFileset(filesetIdent);
+      return hookFileset != null ? hookFileset : 
super.getFileset(filesetIdent);
     }
 
     @Override
     protected FileSystem getActualFileSystemByPath(Path path, Map<String, 
String> allProperties) {
+      paths.add(path);
       props.add(allProperties);
       return mock(FileSystem.class);
     }
diff --git 
a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestFilesetMetadataCache.java
 
b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestFilesetMetadataCache.java
index c60ea31168..828e8d88f0 100644
--- 
a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestFilesetMetadataCache.java
+++ 
b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestFilesetMetadataCache.java
@@ -18,8 +18,10 @@
  */
 package org.apache.gravitino.filesystem.hadoop;
 
+import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.clearInvocations;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.times;
@@ -29,7 +31,11 @@ import static org.mockito.Mockito.when;
 import java.io.IOException;
 import org.apache.gravitino.Catalog;
 import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.Schema;
+import org.apache.gravitino.SupportsSchemas;
 import org.apache.gravitino.client.GravitinoClient;
+import org.apache.gravitino.file.Fileset;
+import org.apache.gravitino.file.FilesetCatalog;
 import org.junit.jupiter.api.Test;
 
 /**
@@ -118,4 +124,43 @@ public class TestFilesetMetadataCache {
     // The failed load is not cached, so the second call loads the catalog 
again.
     verify(client, times(2)).loadCatalog("catalog");
   }
+
+  @Test
+  public void testCacheReusesCatalogSchemaAndFileset() throws IOException {
+    GravitinoClient client = mock(GravitinoClient.class);
+    Catalog catalog = mock(Catalog.class);
+    FilesetCatalog filesetCatalog = mock(FilesetCatalog.class);
+    SupportsSchemas schemas = mock(SupportsSchemas.class);
+    Schema schema = mock(Schema.class);
+    Fileset fileset = mock(Fileset.class);
+
+    when(client.loadCatalog("catalog")).thenReturn(catalog);
+    when(catalog.asFilesetCatalog()).thenReturn(filesetCatalog);
+    when(catalog.asSchemas()).thenReturn(schemas);
+    when(schemas.loadSchema("schema")).thenReturn(schema);
+    when(filesetCatalog.loadFileset(NameIdentifier.of("schema", 
"fs"))).thenReturn(fileset);
+
+    NameIdentifier catalogIdent = NameIdentifier.of("ml", "catalog");
+    NameIdentifier schemaIdent = NameIdentifier.of("ml", "catalog", "schema");
+    NameIdentifier filesetIdent = NameIdentifier.of("ml", "catalog", "schema", 
"fs");
+
+    try (FilesetMetadataCache cache = new FilesetMetadataCache(client)) {
+      assertSame(catalog, cache.getCatalog(catalogIdent));
+      assertSame(filesetCatalog, cache.getFilesetCatalog(catalogIdent));
+      assertSame(schema, cache.getSchema(schemaIdent));
+      assertSame(fileset, cache.getFileset(filesetIdent));
+
+      // Second round should all hit caches.
+      assertSame(catalog, cache.getCatalog(catalogIdent));
+      assertSame(filesetCatalog, cache.getFilesetCatalog(catalogIdent));
+      assertSame(schema, cache.getSchema(schemaIdent));
+      clearInvocations(catalog);
+      assertSame(fileset, cache.getFileset(filesetIdent));
+      verify(catalog, never()).asFilesetCatalog();
+    }
+
+    verify(client, times(1)).loadCatalog("catalog");
+    verify(schemas, times(1)).loadSchema("schema");
+    verify(filesetCatalog, times(1)).loadFileset(NameIdentifier.of("schema", 
"fs"));
+  }
 }
diff --git a/docs/how-to-use-gvfs.md b/docs/how-to-use-gvfs.md
index b5a279b489..f09a87b918 100644
--- a/docs/how-to-use-gvfs.md
+++ b/docs/how-to-use-gvfs.md
@@ -72,7 +72,7 @@ the path mapping and convert automatically.
 | `fs.gravitino.client.request.header.`                 | The configuration 
key prefix for the Gravitino client request header. You can set the request 
header for the Gravitino client.                                                
                                                                                
                                                                                
                         | (none)                                               
          | No       [...]
 | `fs.gravitino.enableCredentialVending`                | Whether to enable 
credential vending for the Gravitino Virtual File System.                       
                                                                                
                                                                                
                                                                                
                     | `false`                                                  
      | No       [...]
 | `fs.gravitino.client.`                                | The configuration 
key prefix for the Gravitino client config.                                     
                                                                                
                                                                                
                                                                                
                     | (none)                                                   
      | No       [...]
-| `fs.gravitino.filesetMetadataCache.enable`            | Whether to cache the 
fileset, fileset schema or fileset catalog metadata in the Gravitino Virtual 
File System. Note that this cache causes a side effect: while an entry is 
cached, the client does not see changes to the fileset, its schema or its 
catalog, including their properties. Secrets are still fetched for every 
operation.                                                                      
                                    [...]
+| `fs.gravitino.filesetMetadataCache.cache.enable`      | Whether to cache the 
fileset, fileset schema or fileset catalog metadata in the Gravitino Virtual 
File System. Note that this cache causes a side effect: while an entry is 
cached, the client does not see changes to the fileset, its schema or its 
catalog, including their properties. Secrets are still fetched for every 
operation.                                                                      
                                    [...]
 | `fs.gravitino.autoCreateLocation`                     | The configuration 
key for whether to enable auto-creation of fileset location when the 
server-side filesystem ops are disabled and the location does not exist.        
                                                                                
                                                                                
                                | `true`                                        
                 | No       [...]
 | `fs.gravitino.kerberos.access.filesets`               | Comma-separated 
fileset paths, such as `gvfs://fileset/catalog/schema/fileset`, to collect 
Hadoop delegation tokens for. Needed on Kerberized HDFS when a job reads 
filesets stored outside `fs.defaultFS`. See [Via Apache 
Spark](#via-apache-spark).                                                      
                                                           | (none)             
                                            | No       [...]
 | `fs.path.config.<name>`                               | Defines a logical 
location entry. Set `fs.path.config.<name>` to the real base URI (for example, 
`hdfs://cluster1/`). Any key that starts with the same prefix (such as 
`fs.path.config.<name>.config.resource`) is treated as a location-scoped 
property and will be forwarded to the underlying filesystem client. Note: 
location names must not contain (`.`, `_`). | (none)                            
                             | No       [...]

Reply via email to