LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-3295 [FIX] Fix fsspec directory listing cache issue on connectors (#1826)
Chandrasekharan M5ebb6fbe7c89
diff --git a/backend/workflow_manager/endpoint_v2/source.py b/backend/workflow_manager/endpoint_v2/source.pyindex 0f4bccae1..23b0d04f2 100644--- a/backend/workflow_manager/endpoint_v2/source.py+++ b/backend/workflow_manager/endpoint_v2/source.py@@ -3,6 +3,7 @@ import loggingimport osimport shutilimport uuid+from collections.abc import Collectionfrom hashlib import sha256from io import BytesIOfrom itertools import islice@@ -486,14 +487,14 @@ class SourceConnector(BaseConnector):max_depth = int(SourceConstant.MAX_RECURSIVE_DEPTH) if recursive else 1fs_fsspec = source_fs.get_fsspec_fs()- for root, dirs, _ in fs_fsspec.walk(input_directory, maxdepth=max_depth):- try:- fs_metadata_list: list[dict[str, Any]] = fs_fsspec.listdir(- root- ) # Single call for file system metadata- except Exception as e:- logger.warning(f"Failed to list directory from path: {root}, error: {e}")- continue++ def _on_walk_error(error: Exception) -> None:+ logger.warning(f"Failed to list directory: {error}")++ for _root, dirs, files in fs_fsspec.walk(+ input_directory, maxdepth=max_depth, detail=True, on_error=_on_walk_error+ ):+ fs_metadata_list: list[dict[str, Any]] = list(files.values())count = self._process_file_fs_directory(fs_metadata_list=fs_metadata_list,@@ -517,7 +518,7 @@ class SourceConnector(BaseConnector):matched_files: dict[str, FileHash],patterns: list[str],source_fs: UnstractFileSystem,- dirs: list[str],+ dirs: Collection[str],) -> int:for fs_metadata in fs_metadata_list:if count >= limit:@@ -708,7 +709,7 @@ class SourceConnector(BaseConnector):source_fs: UnstractFileSystem,file_path: str,metadata: dict[str, Any],- dirs: list[str],+ dirs: Collection[str],) -> bool:"""Check if the given path is a directory.@@ -717,7 +718,7 @@ class SourceConnector(BaseConnector):reading the file.file_path (str): The path of the file.metadata (dict[str, Any]): The metadata of the file.- dirs (list[str]): The list of directories.+ dirs (Collection[str]): The collection of directory names.Returns:bool: True if the file is a directory, False otherwise.diff --git a/frontend/src/hooks/useClearFileHistory.js b/frontend/src/hooks/useClearFileHistory.jsindex ba17aad38..360ed4e39 100644--- a/frontend/src/hooks/useClearFileHistory.js+++ b/frontend/src/hooks/useClearFileHistory.js@@ -35,6 +35,10 @@ const useClearFileHistory = () => {try {await workflowServiceInstance.clearFileMarkers(workflowId);+ setAlertDetails({+ type: "success",+ content: "File history cleared successfully",+ });return true;} catch (err) {setAlertDetails(handleException(err, "Failed to clear file history"));diff --git a/unstract/connectors/src/unstract/connectors/filesystems/azure_cloud_storage/azure_cloud_storage.py b/unstract/connectors/src/unstract/connectors/filesystems/azure_cloud_storage/azure_cloud_storage.pyindex 1034cdcdf..ecc92da48 100644--- a/unstract/connectors/src/unstract/connectors/filesystems/azure_cloud_storage/azure_cloud_storage.py+++ b/unstract/connectors/src/unstract/connectors/filesystems/azure_cloud_storage/azure_cloud_storage.py@@ -39,8 +39,15 @@ class AzureCloudStorageFS(UnstractFileSystem):account_name = settings.get("account_name", "")access_key = settings.get("access_key", "")self.bucket = settings.get("bucket", "")+ # adlfs._ls_containers() unconditionally reads from DirCache after+ # populating it — use_listings_cache=False makes the write a no-op,+ # causing a KeyError. Setting listings_expiry_time=0 allows writes+ # but expires entries immediately on subsequent reads.+ # Check https://github.com/fsspec/adlfs/issues/230 for more context.self.azure_fs = AzureBlobFileSystem(- account_name=account_name, credential=access_key+ account_name=account_name,+ credential=access_key,+ listings_expiry_time=0,)@staticmethoddiff --git a/unstract/connectors/src/unstract/connectors/filesystems/box/box.py b/unstract/connectors/src/unstract/connectors/filesystems/box/box.pyindex 570bdf18b..bbf658518 100644--- a/unstract/connectors/src/unstract/connectors/filesystems/box/box.py+++ b/unstract/connectors/src/unstract/connectors/filesystems/box/box.py@@ -36,7 +36,9 @@ class BoxFS(UnstractFileSystem):try:oauth = JWTAuth.from_settings_dictionary(settings_dict)root_id = 0- self.box_fs = BoxFileSystem(oauth=oauth, root_id=root_id)+ self.box_fs = BoxFileSystem(+ oauth=oauth, root_id=root_id, use_listings_cache=False+ )except ValueError as e:raise ConnectorError(f"Error initialising from Box app settings: {e}",diff --git a/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.py b/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.pyindex 7ecb3ba76..bf99e5f74 100644--- a/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.py+++ b/unstract/connectors/src/unstract/connectors/filesystems/minio/minio.py@@ -26,6 +26,7 @@ class MinioFS(UnstractFileSystem):anon=False,key=key,secret=secret,+ use_listings_cache=False,default_fill_cache=False,default_cache_type="none",skip_instance_cache=True,diff --git a/unstract/connectors/src/unstract/connectors/filesystems/sharepoint/sharepoint.py b/unstract/connectors/src/unstract/connectors/filesystems/sharepoint/sharepoint.pyindex 415192b44..9b39c67c8 100644--- a/unstract/connectors/src/unstract/connectors/filesystems/sharepoint/sharepoint.py+++ b/unstract/connectors/src/unstract/connectors/filesystems/sharepoint/sharepoint.py@@ -11,6 +11,7 @@ Uses Microsoft Graph API via Office365-REST-Python-Client library.import loggingimport osimport threading+from collections.abc import Callablefrom datetime import UTC, datetimefrom typing import Any, NoReturn@@ -415,6 +416,7 @@ class SharePointFileSystem(AbstractFileSystem):self,path: str = "",maxdepth: int | None = None,+ on_error: str | Callable[[Exception], Any] = "omit",**kwargs: Any,):"""Walk directory tree."""@@ -424,7 +426,11 @@ class SharePointFileSystem(AbstractFileSystem):path = self._normalize_path(path)try:items = self.ls(path, detail=True)- except Exception:+ except Exception as e:+ if callable(on_error):+ on_error(e)+ elif on_error == "raise":+ raisereturndirs = []@@ -441,7 +447,7 @@ class SharePointFileSystem(AbstractFileSystem):for d in dirs:subpath = f"{path}/{d}" if path != "root" else dnew_depth = maxdepth - 1 if maxdepth is not None else None- yield from self.walk(subpath, maxdepth=new_depth, **kwargs)+ yield from self.walk(subpath, maxdepth=new_depth, on_error=on_error, **kwargs)class SharePointFS(UnstractFileSystem):diff --git a/unstract/connectors/src/unstract/connectors/filesystems/unstract_file_system.py b/unstract/connectors/src/unstract/connectors/filesystems/unstract_file_system.pyindex c8b75b20e..88ba60a78 100644--- a/unstract/connectors/src/unstract/connectors/filesystems/unstract_file_system.py+++ b/unstract/connectors/src/unstract/connectors/filesystems/unstract_file_system.py@@ -187,23 +187,31 @@ class UnstractFileSystem(UnstractConnector, ABC):Returns:List of file metadata dictionaries"""- all_files = []+ all_files: list[dict[str, Any]] = []fs_fsspec = self.get_fsspec_fs()- for root, dirs, _ in fs_fsspec.walk(directory, maxdepth=max_depth):- try:- fs_metadata_list = fs_fsspec.listdir(root, detail=True)- for metadata in fs_metadata_list:- if not include_dirs and self.is_dir_by_metadata(metadata):- continue- all_files.append(metadata)-- if limit is not None and len(all_files) >= limit:- return all_files- except Exception as e:- logger.warning(f"Failed to list directory {root}: {e}")- self._store_user_error(f"Could not access directory: {root}")- continue+ def _on_walk_error(error: Exception) -> None:+ """Callback for walk errors — preserves user error reporting."""+ logger.warning(f"Failed to list directory: {error}")+ self._store_user_error(f"Could not access directory: {error}")++ for _root, dirs, files in fs_fsspec.walk(+ directory, maxdepth=max_depth, detail=True, on_error=_on_walk_error+ ):+ if include_dirs:+ items = list(dirs.values()) + list(files.values())+ else:+ items = list(files.values())++ for metadata in items:+ # Safety check: some providers (GCS zero-size objects, Azure+ # is_directory tag) mis-classify directories as files.+ if not include_dirs and self.is_dir_by_metadata(metadata):+ continue+ all_files.append(metadata)++ if limit is not None and len(all_files) >= limit:+ return all_filesreturn all_filesdef report_errors_to_user(self) -> list[str]:diff --git a/unstract/connectors/src/unstract/connectors/filesystems/zs_dropbox/zs_dropbox.py b/unstract/connectors/src/unstract/connectors/filesystems/zs_dropbox/zs_dropbox.pyindex 990728a48..cdbdfde58 100644--- a/unstract/connectors/src/unstract/connectors/filesystems/zs_dropbox/zs_dropbox.py+++ b/unstract/connectors/src/unstract/connectors/filesystems/zs_dropbox/zs_dropbox.py@@ -16,7 +16,9 @@ class DropboxFS(UnstractFileSystem):from dropboxdrivefs import DropboxDriveFileSystemsuper().__init__("Dropbox")- self.dropbox_fs = DropboxDriveFileSystem(token=settings["token"])+ self.dropbox_fs = DropboxDriveFileSystem(+ token=settings["token"], use_listings_cache=False+ )self.path = "///"@staticmethoddiff --git a/workers/shared/processing/file_discovery.py b/workers/shared/processing/file_discovery.pyindex 942926df0..6bc8d9b32 100644--- a/workers/shared/processing/file_discovery.py+++ b/workers/shared/processing/file_discovery.py@@ -5,6 +5,7 @@ to avoid circular imports and provide clean separation of concerns."""import time+from collections.abc import Collectionfrom typing import Anyfrom unstract.connectors.filesystems.unstract_file_system import UnstractFileSystem@@ -115,22 +116,22 @@ class StreamingFileDiscovery:logger.info(f"[StreamingDiscovery] Processing directory: {directory}")+ def _on_walk_error(error: Exception) -> None:+ logger.warning(+ f"[StreamingDiscovery] Failed to list directory: {error}"+ )+# Walk directory with max depth control- for root, dirs, _ in self.fs_fsspec.walk(directory, maxdepth=max_depth):+ for _root, dirs, files in self.fs_fsspec.walk(+ directory, maxdepth=max_depth, detail=True, on_error=_on_walk_error+ ):metrics["directories_walked"] += 1# Check limit before processing directoryif len(matched_files) >= file_hard_limit:break- try:- # Get all items in directory with metadata- fs_metadata_list: list[dict[str, Any]] = self.fs_fsspec.listdir(- root- )- except Exception as e:- logger.warning(f"Failed to list directory {root}: {e}")- continue+ fs_metadata_list: list[dict[str, Any]] = list(files.values())# Process files in this directoryfor fs_metadata in fs_metadata_list:@@ -395,14 +396,14 @@ class StreamingFileDiscovery:)def _is_directory(- self, file_path: str, metadata: dict[str, Any], dirs: list[str]+ self, file_path: str, metadata: dict[str, Any], dirs: Collection[str]) -> bool:"""Check if path is a directory using multiple detection methods.Args:file_path: Path to checkmetadata: File metadata from fsspec- dirs: List of directories from walk+ dirs: Collection of directory names from walkReturns:True if path is a directory