From 76f7433ab595d53fa5e9df0af7facab1ea51a695 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 27 Nov 2026 16:37:48 -0800 Subject: [PATCH 01/17] Track Drive folders by parent ID and exact name --- docs/fsspec.rst | 5 +- pydrive2/fs/cache.py | 314 +++++++++++++++++++++++++ pydrive2/fs/spec.py | 380 +++++++++++++------------------ pydrive2/test/test_fs_listing.py | 109 +++++---- pydrive2/test/test_fs_unit.py | 209 ++++++++++++++++- 5 files changed, 743 insertions(+), 274 deletions(-) create mode 100644 pydrive2/fs/cache.py diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 9195391..9abc448 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -66,7 +66,10 @@ argument specifies traversal depth. Directory names returned by ``ls()`` and ``info()`` end in a slash. ``find(withdirs=True)`` returns directory paths without a trailing slash, like fsspec's other traversal methods. -Named directory lookups reuse cached Drive IDs. If another client moves, +Named directory lookups reuse cached Drive IDs. Listing a parent refreshes +the folders seen under that parent. If a listing discovers a folder under +a new name, its cached children follow the folder's Drive ID. +If another client moves, trashes, or deletes a folder, call ``fs.invalidate_cache("root/empty")`` before looking up its old path again. The next lookup checks Drive for all folders with that name, including any same-name folder that still exists. diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py new file mode 100644 index 0000000..0cfb1d0 --- /dev/null +++ b/pydrive2/fs/cache.py @@ -0,0 +1,314 @@ +"""Directory edges learned from Drive queries, scoped to one filesystem.""" + +from collections import defaultdict +from contextlib import contextmanager +from threading import RLock + +FOLDER_MIME_TYPE = "application/vnd.google-apps.folder" + + +class FolderListing: + """Accumulate one logical listing across all pages and parent batches.""" + + def __init__(self, parents, name, generation): + self.name = name + self.generation = generation + self.folders: dict[str, dict[str, list[str]]] = { + p: {} for p in parents + } + self.files: set[tuple[str, str]] = set() + self.complete = True + + def add(self, parent, item): + if parent is None: + self.complete = False + elif item["mimeType"] == FOLDER_MIME_TYPE: + self.folders[parent].setdefault(item["name"], []).append( + item["id"] + ) + else: + self.files.add((parent, item["name"])) + + +class DirectoryCache: + """Keep children attached to Drive IDs across moves. + + Invalidation advances the generation. Overlapping listings of the same + name can also supersede a pending response before it publishes its edges. + """ + + def __init__(self, root: str): + self.root = root + self.lock = RLock() + self.generation = 0 + self._pending: dict[FolderListing, None] = {} + self.children: dict[str, dict[str, tuple[str, ...]]] = {} + self.parents: dict[str, tuple[str, str]] = {} + # Names shared with files (or changed by a mutation) need a fresh lookup. + self.incomplete: set[tuple[str, str]] = set() + + def _folders(self, parents, name): + result: list[str] = [] + for parent in parents: + ids = self.children.get(parent, {}).get(name) + if ids is None or (parent, name) in self.incomplete: + return None + result.extend(ids) + return result or None + + def lookup(self, parents, name, generation): + with self.lock: + if generation == self.generation: + return self._folders(parents, name) + return None + + def prefix(self, path, generation): + parts = path.split("/") if path else [] + folders = [self.root] + with self.lock: + if generation != self.generation: + return "", folders, parts + for i, name in enumerate(parts): + found = self._folders(folders, name) + if not found: + return "/".join(parts[:i]), folders, parts[i:] + folders = found + return path, folders, [] + + def contains(self, path, generation): + return not self.prefix(path, generation)[2] + + def warm_parents(self, roots, maxdepth, generation): + """Include only parents whose contents can contribute to this walk.""" + with self.lock: + parents = dict.fromkeys(roots) + if generation != self.generation: + return parents + frontier = list(parents) + depth = 1 + while frontier and (maxdepth is None or depth < maxdepth): + following = [] + for parent in frontier: + for ids in self.children.get(parent, {}).values(): + for child in ids: + if child not in parents: + parents[child] = None + following.append(child) + frontier = following + depth += 1 + return parents + + def _remove_name(self, parent, name): + self.incomplete.discard((parent, name)) + names = self.children.get(parent) + if not names: + return () + ids = names.pop(name, ()) + if not names: + del self.children[parent] + return ids + + def _unlink(self, item_id): + parent, name = self.parents.pop(item_id) + ids = self.children[parent][name] + if len(ids) == 1: + self._remove_name(parent, name) + else: + self.children[parent][name] = tuple(i for i in ids if i != item_id) + + def _drop_subtrees(self, roots): + pending = list(roots) + while pending: + parent = pending.pop() + self.parents.pop(parent, None) + for name, ids in self.children.pop(parent, {}).items(): + self.incomplete.discard((parent, name)) + pending.extend(ids) + + def _known_folder_ids(self, path, *, verified=False): + ids: tuple[str, ...] | list[str] = (self.root,) + for part in path.split("/") if path else (): + if len(ids) == 1: + if verified and (ids[0], part) in self.incomplete: + return () + ids = self.children.get(ids[0], {}).get(part, ()) + else: + ids = [ + child + for parent in ids + if not verified or (parent, part) not in self.incomplete + for child in self.children.get(parent, {}).get(part, ()) + ] + if not ids: + break + return ids + + def has_directory(self, path, mount): + # One known folder suffices for exists and makedirs. Operations that + # select a specific Drive ID must resolve all same-name matches. + with self.lock: + if mount and not self._known_folder_ids(mount, verified=True): + return False + return bool(self._known_folder_ids(path, verified=True)) + + def _parents_of_path(self, path): + parent, _, name = path.rpartition("/") + return self._known_folder_ids(parent), name + + def invalidate(self, path): + with self.lock: + self.generation += 1 + if not path: + self.children.clear() + self.parents.clear() + self.incomplete.clear() + return + parents, name = self._parents_of_path(path) + for parent in parents: + self._drop_subtrees(self._remove_name(parent, name)) + + def removed(self, item_id, paths): + """Discard this ID. Recheck affected names without evicting siblings.""" + with self.lock: + self.generation += 1 + if item_id in self.parents: + self._unlink(item_id) + self._drop_subtrees([item_id]) + for path in paths: + parents, name = self._parents_of_path(path) + for parent in parents: + if name in self.children.get(parent, {}): + self.incomplete.add((parent, name)) + + def moved(self, generation, item_id, parent, name): + """Relink a known folder while retaining all edges below its ID.""" + with self.lock: + if generation != self.generation or item_id not in self.parents: + return False + old_parent, _ = self.parents[item_id] + # A rename leaves the physical parent unchanged. + if parent is None: + parent = old_parent + self._unlink(item_id) + edge = (parent, name) + names = self.children.setdefault(parent, {}) + names[name] = (*names.get(name, ()), item_id) + self.parents[item_id] = edge + # The destination can already contain same-name files or folders. + self.incomplete.add(edge) + self.generation += 1 + return True + + def created(self, generation, parents, parent, name, item_id): + with self.lock: + # A new child only changes this parent's listing. Independent + # creations can still publish and reuse their own folder IDs. + self._supersede((parent,), name) + if generation == self.generation: + for p in parents: + self.children.setdefault(p, {}).setdefault(name, ()) + ids = self.children[parent][name] + if item_id not in ids: + self.children[parent][name] = (*ids, item_id) + self.parents[item_id] = (parent, name) + elif name in self.children.get(parent, {}): + self.incomplete.add((parent, name)) + return generation + + def _supersede(self, parents, name, *, until=None): + # A newer completed listing can confirm an absence before an older + # request has even published its first edge for that name. + for pending in self._pending: + if pending is until: + break + same_name = name is None or pending.name in (None, name) + if same_name and not pending.folders.keys().isdisjoint(parents): + pending.generation = None + + def file_added(self, parent, name): + with self.lock: + self._supersede((parent,), name) + if name in self.children.get(parent, {}): + self.incomplete.add((parent, name)) + + @contextmanager + def listing(self, generation, parents, *, name=None): + listing = FolderListing(parents, name, generation) + with self.lock: + self._pending[listing] = None + try: + yield listing + with self.lock: + if listing.complete and listing.generation == self.generation: + self._supersede(listing.folders, name, until=listing) + self._observe(listing, name) + finally: + with self.lock: + del self._pending[listing] + + def _observe(self, listing, name): + groups = listing.folders + changed = self._relink(groups) + retired: list[str] = [] + has_folder = any(groups.values()) + for parent, names in groups.items(): + previous = self.children.get(parent, {}) + keys = ( + (name,) + if name is not None + else dict.fromkeys((*names, *previous)) + ) + for key in keys: + before = previous.get(key) + ids = tuple(names.get(key, ())) + edge = (parent, key) + if ( + before + and ids + and before != ids + and set(before) == set(ids) + ): + ids = before + if before is not None and ( + before != ids + or (edge in self.incomplete) != (edge in listing.files) + ): + changed = True + if before and before != ids: + retired.extend(set(before).difference(ids)) + # Remember an empty sibling only if this exact name matched + # a folder under another queried parent. Never cache misses alone. + if ids or (name is not None and has_folder): + self.children.setdefault(parent, {})[key] = ids + for item_id in ids: + self.parents[item_id] = edge + if edge in listing.files: + self.incomplete.add(edge) + else: + self.incomplete.discard(edge) + else: + self._remove_name(parent, key) + self._drop_subtrees(retired) + if changed: + self.generation += 1 + listing.generation = self.generation + + def _relink(self, groups): + # Unlink moved IDs before pruning absent names. Their children stay + # attached to the same ID even when an ancestor changes name or parent. + moved = defaultdict(set) + for parent, names in groups.items(): + for name, ids in names.items(): + for item_id in ids: + old = self.parents.get(item_id) + if old is not None and old != (parent, name): + moved[old].add(item_id) + for (parent, name), leaving in moved.items(): + remaining = tuple( + i for i in self.children[parent][name] if i not in leaving + ) + if remaining: + self.children[parent][name] = remaining + else: + self._remove_name(parent, name) + return bool(moved) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index be42598..68d366d 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -23,11 +23,11 @@ from pydrive2.auth import GoogleAuth, InvalidCredentialsError from pydrive2.drive import GoogleDrive +from pydrive2.fs.cache import FOLDER_MIME_TYPE, DirectoryCache from pydrive2.fs.utils import IterStream logger = logging.getLogger(__name__) -FOLDER_MIME_TYPE = "application/vnd.google-apps.folder" _INFO_FIELDS = "mimeType,size,md5Checksum" _LIST_FIELDS = ( f"nextPageToken,incompleteSearch,files(id,name,parents,{_INFO_FIELDS})" @@ -49,21 +49,6 @@ } -@dataclass -class _DirectoryCache: - by_path: dict[str, list[str]] = field(default_factory=dict) - by_id: dict[str, str] = field(default_factory=dict) - mount_checked: bool = False - - def without_subtrees(self, roots, *, keep_roots=False): - kept = _DirectoryCache(mount_checked=self.mount_checked) - for path, ids in self.by_path.items(): - if (keep_roots and path in roots) or not _in_subtrees(path, roots): - kept.by_path[path] = ids.copy() - kept.by_id.update(dict.fromkeys(ids, path)) - return kept - - @dataclass class _PathMatch: folders: list[str] @@ -298,14 +283,14 @@ def __init__( :raises: GDriveAuthError """ super().__init__(**kwargs) - self._cache_lock = threading.RLock() - self._directory_ids = _DirectoryCache() + self.path = path + self.root, self.base = self.split_path(path) + self._dirs = DirectoryCache(self.root) + self._cache_lock = self._dirs.lock self._mount_lock = threading.RLock() self._root_lock = threading.RLock() self._root_metadata: dict = {} self._creation_locks: WeakValueDictionary = WeakValueDictionary() - self.path = path - self.root, self.base = self.split_path(self.path) if not google_auth: if ( @@ -369,79 +354,39 @@ def _split_file_path(self, path): parent, name = posixpath.split(base) return posixpath.join(root, parent), name - def _directory_cache(self): - with self._cache_lock: - cache = self._directory_ids - if cache.mount_checked: - return cache, None + def _resolve_mount(self): + generation = self._dirs.generation + if not self.base or self._dirs.contains(self.base, generation): + return generation, None with self._mount_lock: - with self._cache_lock: - cache = self._directory_ids - if cache.mount_checked: - return cache, None - mount, cache = self._resolve_path(self.base, cache) + generation = self._dirs.generation + mount, generation = self._resolve_path(self.base, generation) if not mount.ids: raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), f"Confirm {self.path} exists and you can access it", ) - with self._cache_lock: - cache.mount_checked = True - return cache, mount - - def _cache_path_id(self, cache, path, *item_ids): - with self._cache_lock: - for item_id in item_ids: - old_path = cache.by_id.get(item_id) - if old_path == path: - continue - if old_path is not None: - # Either name can also belong to a different folder. - # Recheck their descendants against the remaining IDs. - kept = cache.without_subtrees( - (old_path, path), keep_roots=True - ) - if cache is self._directory_ids: - self._directory_ids = kept - if _in_subtrees(self.base, (old_path,)): - kept.mount_checked = False - cache = kept - cache.by_path[old_path].remove(item_id) - if not cache.by_path[old_path]: - del cache.by_path[old_path] - cache.by_id[item_id] = path - cache.by_path.setdefault(path, []).append(item_id) - return cache + return generation, mount def invalidate_cache(self, path=None): - self._invalidate_paths(path) - - def _invalidate_paths(self, *paths): - subtrees = tuple( - self._split_mounted_path(p)[1] if p else "" for p in paths - ) - for path in paths: - super().invalidate_cache(path) + base = self._split_mounted_path(path)[1] if path else "" + super().invalidate_cache(path) with self._cache_lock: - if "" in subtrees: + if not base: self._root_metadata = {} - if _in_subtrees(self.base, subtrees): - self._directory_ids = _DirectoryCache() - else: - self._directory_ids = self._directory_ids.without_subtrees( - subtrees - ) + self._dirs.invalidate(base) def _invalidate_folder(self, item_id, *paths, known_folder=False): with self._cache_lock: - # A lookup may have found this ID under a new name during the mutation. - cached_path = self._directory_ids.by_id.get(item_id) - if cached_path is not None: - paths = (*paths, posixpath.join(self.root, cached_path)) - elif not known_folder and item_id != self.root: - return - self._invalidate_paths(*dict.fromkeys(paths)) + if item_id == self.root: + self.invalidate_cache(self.root) + elif known_folder or item_id in self._dirs.parents: + for path in paths: + super().invalidate_cache(path) + self._dirs.removed( + item_id, [self._split_mounted_path(p)[1] for p in paths] + ) @property def _list_params(self): @@ -506,7 +451,7 @@ def _gdrive_list(self, query): raise OSError(errno.EIO, "Incomplete Drive listing") yield from page - def _gdrive_list_ids(self, query_ids, *, name=None): + def _list_children(self, query_ids, *, name=None, require_parent=False): filters = "trashed=false" if name is not None: filters += f" and name={_quote_query_value(name)}" @@ -516,83 +461,107 @@ def _gdrive_list_ids(self, query_ids, *, name=None): parents = " or ".join( f"{_quote_query_value(parent)} in parents" for parent in batch ) + batch_ids = set(batch) + unplaced = set() for item in self._gdrive_list(f"({parents}) and {filters}"): file_id = item["id"] if file_id in seen_ids: continue - # Only a full batch can be followed by another parent query. - if len(batch) == _PARENT_QUERY_BATCH_SIZE: + parent = next( + (p for p in item.get("parents", ()) if p in batch_ids), + None, + ) + if parent is None: + if len(batch) == 1: + parent = batch[0] + elif ( + self.root in {"root", "appDataFolder"} + and self.root in batch_ids + and item.get("parents") + ): + # Drive can return the canonical ID of the root alias. + parent = self.root + if parent is None and require_parent: + unplaced.add(file_id) + else: + unplaced.discard(file_id) seen_ids.add(file_id) - yield item - - def _match_child(self, cache, parent_ids, path, name, mount=None): + yield parent, item + # If a batched result omits its parents, find needs to establish + # the path. Probe only that batch, and only for the unplaced IDs. + if unplaced: + for parent_id in batch: + for _, item in self._list_children([parent_id], name=name): + if item["id"] in unplaced: + unplaced.remove(item["id"]) + seen_ids.add(item["id"]) + yield parent_id, item + if not unplaced: + break + + def _match_child(self, generation, parent_ids, path, name, mount=None): if path == self.base and mount is not None: - return mount, cache + return mount, generation + folders = self._dirs.lookup(parent_ids, name, generation) + if folders: + return _PathMatch(folders), generation match = _PathMatch([]) - for item in self._gdrive_list_ids(parent_ids, name=name): - if item["name"] != name: # Drive matches case-insensitively. - continue - if item["mimeType"] == FOLDER_MIME_TYPE: - match.folders.append(item["id"]) - else: - match.files.append(item) - return match, self._cache_path_id(cache, path, *match.folders) - - def _cached_prefix(self, path, cache): - parent = path - remaining = [] - with self._cache_lock: - while parent and parent not in cache.by_path: - parent, name = posixpath.split(parent) - remaining.append(name) - folders = cache.by_path[parent].copy() if parent else [self.root] - return parent, folders, reversed(remaining) - - def _resolve_prefix(self, path, cache, mount=None): - """Return the deepest existing component, its matches and lookup cache.""" - parent, folders, remaining = self._cached_prefix(path, cache) + with self._dirs.listing(generation, parent_ids, name=name) as listing: + for parent, item in self._list_children(parent_ids, name=name): + if item["name"] != name: # Drive matches case-insensitively. + continue + listing.add(parent, item) + if item["mimeType"] == FOLDER_MIME_TYPE: + match.folders.append(item["id"]) + else: + match.files.append(item) + return match, listing.generation + + def _resolve_prefix(self, path, generation, mount=None): + """Return the deepest existing component, its matches and lookup generation.""" + parent, folders, remaining = self._dirs.prefix(path, generation) match = _PathMatch(folders) for name in remaining: child = posixpath.join(parent, name) - found, cache = self._match_child( - cache, match.folders, child, name, mount + found, generation = self._match_child( + generation, match.folders, child, name, mount ) if not found.folders and not found.files: break parent, match = child, found if not match.folders: break - return parent, match, cache + return parent, match, generation - def _resolve_path( - self, path, cache, mount=None - ) -> tuple[_PathMatch, _DirectoryCache]: - prefix, match, cache = self._resolve_prefix(path, cache, mount) - return (match if prefix == path else _PathMatch([])), cache + def _resolve_path(self, path, generation, mount=None): + prefix, match, generation = self._resolve_prefix( + path, generation, mount + ) + return (match if prefix == path else _PathMatch([])), generation - def _ensure_dirs(self, path, cache, mount=None): - parent, folders, remaining = self._cached_prefix(path, cache) + def _ensure_dirs(self, path, generation, mount=None): + parent, folders, remaining = self._dirs.prefix(path, generation) for name in remaining: parent = posixpath.join(parent, name) - match, cache = self._get_or_create_child( - cache, folders, parent, name, mount + match, generation = self._get_or_create_child( + generation, folders, parent, name, mount ) if not match.folders: raise NotADirectoryError(posixpath.join(self.root, parent)) folders = match.folders - return folders, cache + return folders, generation def _lookup_path(self, path): if not path: with self._cache_lock: - return _PathMatch([self.root]), self._directory_ids - cache, mount = self._directory_cache() - return self._resolve_path(path, cache, mount) + return _PathMatch([self.root]), self._dirs.generation + generation, mount = self._resolve_mount() + return self._resolve_path(path, generation, mount) def _path_to_item_ids(self, path, create=False): if create and path: - cache, mount = self._directory_cache() - folders, _ = self._ensure_dirs(path, cache, mount) + generation, mount = self._resolve_mount() + folders, _ = self._ensure_dirs(path, generation, mount) return folders match, _ = self._lookup_path(path) return match.ids @@ -615,7 +584,7 @@ def _gdrive_create_dir(self, parent_id, name): return item def _get_or_create_child( - self, cache, parents, path, name, mount=None, *, exist_ok=True + self, generation, parents, path, name, mount=None, *, exist_ok=True ): parent_id = min(parents) key = (parent_id, name) @@ -624,24 +593,19 @@ def _get_or_create_child( if lock is None: lock = self._creation_locks[key] = threading.RLock() with lock: - with self._cache_lock: - folders = cache.by_path.get(path, []).copy() - if folders: - match = _PathMatch(folders) - else: - # An invalidation can give two writers different caches. Check - # Drive under the same name lock as the create. - match, cache = self._match_child( - cache, parents, path, name, mount - ) + # Check Drive under the same name lock as the create on a cache miss. + match, generation = self._match_child( + generation, parents, path, name, mount + ) if match.folders or match.files: if not exist_ok: raise FileExistsError(posixpath.join(self.root, path)) - return match, cache + return match, generation item = self._gdrive_create_dir(parent_id, name) - return _PathMatch([item["id"]]), self._cache_path_id( - cache, path, item["id"] + generation = self._dirs.created( + generation, parents, parent_id, name, item["id"] ) + return _PathMatch([item["id"]]), generation def mkdir(self, path, create_parents=True, **kwargs): self._mkdir(path, create_parents, exist_ok=False) @@ -651,9 +615,7 @@ def makedirs(self, path, exist_ok=False): def _mkdir(self, path, create_parents, exist_ok): root, base = self._split_mounted_path(path) - with self._cache_lock: - cache = self._directory_ids - cached = cache.mount_checked and base in cache.by_path + cached = base and self._dirs.has_directory(base, self.base) if not cached and root not in {"root", "appDataFolder"}: metadata = self._get_root_metadata(fresh=True) if metadata.get("trashed"): @@ -671,25 +633,29 @@ def _mkdir(self, path, create_parents, exist_ok): raise FileExistsError(path) return - cache, mount = self._directory_cache() + generation, mount = self._resolve_mount() parent, name = posixpath.split(base) if create_parents: - folders, cache = self._ensure_dirs(parent, cache, mount) + folders, generation = self._ensure_dirs(parent, generation, mount) else: - prefix, match, cache = self._resolve_prefix(parent, cache, mount) + prefix, match, generation = self._resolve_prefix( + parent, generation, mount + ) if not match.folders: raise NotADirectoryError(posixpath.join(root, prefix)) if prefix != parent: raise FileNotFoundError(posixpath.join(root, parent)) folders = match.folders leaf, _ = self._get_or_create_child( - cache, folders, base, name, mount, exist_ok=exist_ok + generation, folders, base, name, mount, exist_ok=exist_ok ) if not leaf.folders: raise FileExistsError(path) def exists(self, path): root, base = self._split_mounted_path(path) + if base and self._dirs.has_directory(base, self.base): + return True try: if not base and root not in {"root", "appDataFolder"}: self.info(path) @@ -725,7 +691,7 @@ def info(self, path): def ls(self, path, detail=False): bucket, base = self._split_mounted_path(path) - match, cache = self._lookup_path(base) + match, generation = self._lookup_path(base) dir_ids = match.ids if not dir_ids: raise FileNotFoundError( @@ -734,69 +700,33 @@ def ls(self, path, detail=False): root_path = posixpath.join(bucket, base) contents = [] - folders = [] - for item in self._gdrive_list_ids(dir_ids): - item_path = posixpath.join(root_path, item["name"]) - contents.append(_file_entry(item_path, item)) - if item["mimeType"] == FOLDER_MIME_TYPE: - folders.append( - (item["id"], posixpath.join(base, item["name"])) + with self._dirs.listing(generation, dir_ids) as listing: + for parent, item in self._list_children(dir_ids): + contents.append( + _file_entry(posixpath.join(root_path, item["name"]), item) ) - - if folders: - self._invalidate_listed_renames(cache, folders) - + listing.add(parent, item) if detail: return contents - else: - return [content["name"] for content in contents] + return [entry["name"] for entry in contents] - def _invalidate_listed_renames(self, cache, folders): - with self._cache_lock: - if cache is not self._directory_ids: - return - changed: set[str] = set() - for item_id, path in folders: - old_path = cache.by_id.get(item_id) - if old_path is not None and old_path != path: - changed.update((old_path, path)) - if changed: - # Re-resolve both names so same-name siblings remain visible. - self._invalidate_paths(*(f"{self.root}/{p}" for p in changed)) - - def _walk_folders(self, base, start_ids, cache, maxdepth): - # Cache entries are hints about which parents can share a request. - # Build paths only from the parent links in the current Drive listing. + def _walk_folders(self, base, start_ids, generation, maxdepth): frontier = dict.fromkeys(start_ids, base) - to_list = dict.fromkeys(frontier) - if maxdepth != 1: - prefix = base + "/" if base else "" - with self._cache_lock: - for item_id, name in cache.by_id.items(): - if name.startswith(prefix) and ( - maxdepth is None - or name[len(prefix) :].count("/") + 1 < maxdepth - ): - to_list[item_id] = None + to_list = self._dirs.warm_parents(frontier, maxdepth, generation) depth = 0 children: dict[str, list[dict]] = {} visited: set[str] = set() while frontier: depth += 1 - children.update({item_id: [] for item_id in to_list}) - for item in self._gdrive_list_ids(to_list): - parent = next( - (p for p in item.get("parents", ()) if p in to_list), None - ) - # Drive reports the canonical ID when a root alias was queried. - if ( - parent is None - and self.root in {"root", "appDataFolder"} - and self.root in to_list - ): - parent = self.root - if parent is not None: - children[parent].append(item) + if to_list: + with self._dirs.listing(generation, to_list) as listing: + children.update((parent, []) for parent in to_list) + for parent, item in self._list_children( + to_list, require_parent=True + ): + children[parent].append(item) + listing.add(parent, item) + generation = listing.generation visited.update(frontier) following = {} @@ -805,7 +735,6 @@ def _walk_folders(self, base, start_ids, cache, maxdepth): path = posixpath.join(parent_path, item["name"]) if item["mimeType"] == FOLDER_MIME_TYPE: item_id = item["id"] - cache = self._cache_path_id(cache, path, item_id) if item_id not in visited: following[item_id] = path yield path, item @@ -833,8 +762,8 @@ def find( root, base = self._split_mounted_path(path) if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") - cache, mount = self._directory_cache() - match, cache = self._resolve_path(base, cache, mount) + generation, mount = self._resolve_mount() + match, generation = self._resolve_path(base, generation, mount) file = ( min(match.files, key=lambda item: item["id"], default=None) if not match.folders @@ -863,7 +792,7 @@ def find( contents = [] for relative, item in self._walk_folders( - base, match.folders, cache, maxdepth + base, match.folders, generation, maxdepth ): check_empty_root = False name = posixpath.join(root, relative) @@ -893,7 +822,9 @@ def upload_fobj(self, stream, rpath, callback=None, **kwargs): stream = CallbackIOWrapper( callback.relative_update, stream, "read" ) - return self._gdrive_upload_fobj(name, parent_id, stream) + item = self._gdrive_upload_fobj(name, parent_id, stream) + self._dirs.file_added(parent_id, name) + return item def put_file(self, lpath, rpath, callback=None, **kwargs): if callback: @@ -914,6 +845,7 @@ def cp_file(self, lpath, rpath, **kwargs): source_id = self._get_item_id(lpath) parent_id = self._get_item_id(parent, create=True) self._gdrive_copy_file(source_id, parent_id, name) + self._dirs.file_added(parent_id, name) @_gdrive_retry def _gdrive_copy_file(self, source_id, parent_id, name): @@ -941,25 +873,35 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): dst_name = posixpath.basename(path2) dst_parent = self._parent(path2) - file1_id = self._get_item_id(path1) - + _, source = self._split_mounted_path(path1) + match, generation = self._lookup_path(source) + file1_id = _select_item_id(path1, match.ids) file1 = self.client.CreateFile({"id": file1_id}) - if src_name != dst_name: file1["name"] = dst_name + destination_parent = None if src_parent != dst_parent: - file2_parent_id = self._get_item_id(dst_parent) - file1["parents"] = [file2_parent_id] + destination_parent = self._get_item_id(dst_parent) + file1["parents"] = [destination_parent] file1.Upload() - if file1.get("mimeType") == FOLDER_MIME_TYPE: - self._invalidate_folder( - file1_id, - path1, - posixpath.join(dst_parent, dst_name), - known_folder=True, - ) + if ( + file1_id in match.folders + or file1.get("mimeType") == FOLDER_MIME_TYPE + ): + destination = posixpath.join(dst_parent, dst_name) + if self._dirs.moved( + generation, file1_id, destination_parent, dst_name + ): + super().invalidate_cache(path1) + super().invalidate_cache(destination) + else: + self._invalidate_folder( + file1_id, path1, destination, known_folder=True + ) + elif destination_parent is not None: + self._dirs.file_added(destination_parent, dst_name) def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): with _translate_not_found(rpath): @@ -1016,7 +958,7 @@ def _gdrive_open_file(self, item_id, block_size=None): def _fresh_folder_match(self, base): # A cached folder ID cannot establish whether the name is still unique. - prefix, match, _ = self._resolve_prefix(base, _DirectoryCache()) + prefix, match, _ = self._resolve_prefix(base, None) if not match.folders: blocked = posixpath.join(self.root, prefix) self.invalidate_cache(blocked) diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index 1b9fca6..69ad46a 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -1,63 +1,76 @@ import re -from unittest.mock import Mock import pytest from pydrive2.fs import GDriveFileSystem +from pydrive2.fs.spec import FOLDER_MIME_TYPE +from pydrive2.test.http_mock import query, response -@pytest.fixture -def listing_fs(): - return GDriveFileSystem( - "root", google_auth=Mock(), skip_instance_cache=True - ) - +def folders(count): + return [ + {"id": f"dir-{i}", "name": "dup", "mimeType": FOLDER_MIME_TYPE} + for i in range(count) + ] -@pytest.mark.parametrize("count", [0, 1, 50, 51, 100, 251]) -@pytest.mark.parametrize("container", [list, dict.fromkeys, iter]) -def test_list_ids_batches(listing_fs, monkeypatch, count, container): - ids = [f"parent-{index}" for index in range(count)] - listed = [] - def list_query(query): - parents = re.findall(r"'([^']+)' in parents", query) - # Model an API that rejects overly complex parent queries. - assert 0 < len(parents) <= 50 - assert query.endswith(") and trashed=false") - listed.extend(parents) - return ({"id": parent} for parent in parents) +def child(parent): + return { + "id": f"file-{parent}", + "name": parent, + "mimeType": "text/plain", + "parents": [parent], + } - monkeypatch.setattr(listing_fs, "_gdrive_list", list_query) +@pytest.mark.parametrize("count", [0, 1, 50, 51, 100, 251]) +def test_ls_queries_each_duplicate_folder_once_in_batches(mock_drive, count): + roots = folders(count) + ids = [item["id"] for item in roots] + batches = [ids[i : i + 50] for i in range(0, count, 50)] + drive, requests = mock_drive( + response({"files": roots}), + *(response({"files": [child(i) for i in batch]}) for batch in batches), + ) + fs = GDriveFileSystem(google_auth=drive.auth, skip_instance_cache=True) + if count: + assert fs.ls("root/dup") == [f"root/dup/{i}" for i in ids] + else: + with pytest.raises(FileNotFoundError): + fs.ls("root/dup") + assert "name='dup'" in query(requests[0])["q"][0] assert [ - item["id"] for item in listing_fs._gdrive_list_ids(container(ids)) - ] == ids - assert listed == ids + re.findall(r"'([^']+)' in parents", query(request)["q"][0]) + for request in requests[1:] + ] == batches -def test_list_ids_lazy(listing_fs, monkeypatch): - consumed = [] - - def parents(): - for index in range(51): - consumed.append(index) - yield str(index) - - list_query = Mock( - side_effect=[ - iter([{"id": "page-1"}, {"id": "page-2"}]), - iter([{"id": "last"}]), - ] +@pytest.mark.parametrize("complete", [True, False]) +def test_ls_finishes_each_batch_before_requesting_the_next( + mock_drive, complete +): + roots = folders(51) + drive, requests = mock_drive( + response({"files": roots}), + response({"files": [child("dir-0")], "nextPageToken": "second"}), + response( + {"files": [child("dir-1")], "incompleteSearch": not complete} + ), + response({"files": [child("dir-50")]}), ) - monkeypatch.setattr(listing_fs, "_gdrive_list", list_query) - result = listing_fs._gdrive_list_ids(parents()) - assert consumed == [] - list_query.assert_not_called() - - assert next(result)["id"] == "page-1" - assert len(consumed) == 50 - assert next(result)["id"] == "page-2" - assert list_query.call_count == 1 - assert list(result) == [{"id": "last"}] - assert len(consumed) == 51 - assert list_query.call_count == 2 + fs = GDriveFileSystem(google_auth=drive.auth, skip_instance_cache=True) + if complete: + assert fs.ls("root/dup") == [ + "root/dup/dir-0", + "root/dup/dir-1", + "root/dup/dir-50", + ] + assert query(requests[3])["q"] == [ + "('dir-50' in parents) and trashed=false" + ] + else: + with pytest.raises(OSError, match="Incomplete Drive listing"): + fs.ls("root/dup") + assert len(requests) == 3 + assert query(requests[2])["q"] == query(requests[1])["q"] + assert query(requests[2])["pageToken"] == ["second"] diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index f600431..ca65b0b 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -524,19 +524,209 @@ def test_ls_evicts_the_old_path_after_a_folder_rename(mock_drive): listing(folder("child", "C")), listing(folder("new", "D"), folder("new", "other")), listing(), - listing(folder("new", "D"), folder("new", "other")), listing({"id": "note", "name": "note", "mimeType": "text/plain"}), ) fs = filesystem(drive) assert fs.exists("root/old/child") assert fs.ls("root") == ["root/new/", "root/new/"] assert not fs.exists("root/old/child") + before = len(requests) assert fs.ls("root/new") == ["root/new/note"] + assert len(requests) == before + 1 assert set( re.findall(r"'([^']+)' in parents", query(requests[-1])["q"][0]) ) == {"D", "other"} +@pytest.mark.parametrize("duplicate_parents", [False, True]) +def test_warm_read_keeps_same_name_file_and_folder_distinct( + mock_drive, duplicate_parents +): + parents = [folder("dup", "P"), folder("dup", "Q")] + file = {"id": "A", "name": "item", "mimeType": "text/plain"} + directory = folder("item", "Z") + if duplicate_parents: + file["parents"] = ["P"] + directory["parents"] = ["Q"] + found = listing(file, directory) + media = ({"status": "200", "content-length": "1"}, b"x") + drive, requests = mock_drive( + *([listing(*parents)] if duplicate_parents else []), + found, + media, + found, + media, + ) + fs = filesystem(drive) + path = "root/dup/item" if duplicate_parents else "root/item" + for _ in range(2): + with fs.open(path, "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +@pytest.mark.parametrize("operation", ["ls", "find"]) +def test_fresh_listing_forgets_only_the_disappeared_folder( + mock_drive, operation +): + keep, gone = folder("keep", "K"), folder("gone", "G") + drive, requests = mock_drive( + listing(gone), listing(keep), listing(keep), listing() + ) + fs = filesystem(drive) + assert fs.exists("root/gone") + assert fs.exists("root/keep") + if operation == "find": + assert fs.find("root", maxdepth=1, withdirs=True) == [ + "root", + "root/keep", + ] + else: + assert fs.ls("root") == ["root/keep/"] + assert fs.exists("root/keep") + assert not fs.exists("root/gone") + assert len(requests) == 4 + assert "name='gone'" in query(requests[-1])["q"][0] + + +def test_local_rename_preserves_cached_child(mock_drive): + drive, requests = mock_drive( + listing(folder("old", "D")), + listing(folder("child", "C")), + listing(), + response(folder("new", "D")), + listing(folder("new", "D")), + listing(), + ) + fs = filesystem(drive) + assert fs.exists("root/old/child") + fs.mv("root/old", "root/new") + before = len(requests) + assert fs.exists("root/new/child") + assert len(requests) == before + 1 + assert "name='new'" in query(requests[-1])["q"][0] + assert not fs.exists("root/old/child") + + +def test_old_lookup_cannot_restore_folder_after_empty_listing(mock_drive): + def list_after_lookup_starts(request): + if "name='gone'" in query(request)["q"][0] and not requests: + assert fs.ls("root") == [] + + drive, requests = mock_drive( + listing(), + listing(folder("gone", "D")), + listing(), + on_request=list_after_lookup_starts, + ) + fs = filesystem(drive) + assert fs.exists("root/gone") + assert not fs.exists("root/gone") + assert len(requests) == 3 + + +@pytest.mark.parametrize("operation", ["touch", "cp_file", "mv"]) +def test_file_written_beside_cached_folder_can_be_read(mock_drive, operation): + directory = folder("item", "Z") + file = {"name": "item", "id": "A", "mimeType": "text/plain"} + src = dict(file, name="item" if operation == "mv" else "source") + dest = folder("dest", "P") + if operation == "touch": + write = [ + ({"status": "200", "location": "https://example.test/upload"}, ""), + response(file), + ] + elif operation == "cp_file": + write = [listing(src), response(file)] + else: + write = [listing(src), response({"parents": ["root"]}), response(file)] + drive, requests = mock_drive( + listing(dest), + listing(directory), + *write, + listing(file, directory), + ({"status": "200", "content-length": "1"}, b"x"), + ) + fs = filesystem(drive) + path = "root/dest/item" + assert fs.exists(path) + if operation == "touch": + fs.touch(path) + elif operation == "cp_file": + fs.cp_file("root/source", path) + else: + fs.mv("root/item", "root/dest") + with fs.open(path, "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +def test_renamed_duplicate_keeps_each_parents_children_warm(mock_drive): + left, right = folder("dup", "P"), folder("dup", "Q") + child = dict(folder("left", "L"), parents=["P"]) + sibling = dict(folder("right", "R"), parents=["Q"]) + drive, requests = mock_drive( + listing(left, right), + listing(child, sibling), + listing(dict(left, name="new"), right), + listing(), + ) + fs = filesystem(drive) + assert fs.find("root", maxdepth=2) == [] + assert fs.exists("root/dup/left") + fs.makedirs("root/dup/right", exist_ok=True) + assert len(requests) == 2 + fs.ls("root") + assert fs.exists("root/new/left") + assert fs.exists("root/dup/right") + assert len(requests) == 3 + assert not fs.exists("root/dup/left") + assert query(requests[-1])["q"] == [ + "('Q' in parents) and trashed=false and name='left'" + ] + + +@pytest.mark.parametrize("operation", ["exists", "ls", "find"]) +def test_failed_later_page_does_not_cache_partial_duplicate_matches( + mock_drive, operation +): + a, b = folder("dup", "A"), folder("dup", "B") + drive, requests = mock_drive( + response({"files": [a], "nextPageToken": "page2"}), + response({"files": [], "incompleteSearch": True}), + listing(a, b), + listing(), + ) + fs = filesystem(drive) + with pytest.raises(OSError, match="Incomplete Drive listing"): + if operation == "exists": + fs.exists("root/dup") + else: + getattr(fs, operation)("root") + assert fs.ls("root/dup") == [] + assert len(requests) == 4 + assert query(requests[1])["pageToken"] == ["page2"] + assert "'A' in parents or 'B' in parents" in query(requests[-1])["q"][0] + + +def test_find_locates_unattributed_child_of_a_batched_parent(mock_drive): + a, b = folder("a", "A"), folder("b", "B") + item = {"id": "F", "name": "note", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(a, b), listing(item), listing(), listing(item) + ) + fs = filesystem(drive) + assert fs.find("root") == ["root/b/note"] + assert [ + re.findall(r"'([^']+)' in parents", query(r)["q"][0]) for r in requests + ] == [ + ["root"], + ["A", "B"], + ["A"], + ["B"], + ] + + def test_ls_started_before_invalidation_cannot_evict_a_new_lookup(mock_drive): def refresh_during_listing(request): if query(request)["q"] == ["('root' in parents) and trashed=false"]: @@ -831,6 +1021,9 @@ def copy(fs, http, name): release.set() pending.result(timeout=5) + assert first.exists("root/one") + assert (other if other_instance else first).exists("root/two") + @pytest.mark.parametrize("trash_only", [True, False]) def test_rmdir_after_external_rename_forgets_the_old_path( @@ -1152,8 +1345,9 @@ def test_rmdir_checks_emptiness_again_after_transient_failure(mock_drive): assert [r[1] for r in requests] == ["GET", "GET", "DELETE", "GET"] -def test_concurrent_copies_share_a_folder_after_unrelated_invalidation( - mock_drive, +@pytest.mark.parametrize("invalidate", [False, True]) +def test_concurrent_copies_create_their_shared_folder_once( + mock_drive, invalidate ): creating, release = Event(), Event() second_started, second_lookup = Event(), Event() @@ -1180,7 +1374,7 @@ def observe_lookup(request): ) second, second_requests = mock_drive( listing(source), - listing(folder("ab", "AB")), + *([listing(folder("ab", "AB"))] if invalidate else []), response({"id": "second-copy"}), on_request=observe_lookup, ) @@ -1194,7 +1388,8 @@ def copy(http, name): one = pool.submit(copy, first.auth.thread_local.http, "one") try: assert creating.wait(5) - fs.invalidate_cache("root/ef") + if invalidate: + fs.invalidate_cache("root/ef") two = pool.submit(copy, second.auth.thread_local.http, "two") assert second_started.wait(5) # Drive cannot return the new folder until the first create finishes. @@ -1207,7 +1402,9 @@ def copy(http, name): for requests in (first_requests, second_requests): assert json.loads(requests[-1][2])["parents"] == ["AB"] assert [r[1] for r in first_requests] == ["GET", "GET", "POST", "POST"] - assert [r[1] for r in second_requests] == ["GET", "GET", "POST"] + assert [r[1] for r in second_requests] == ( + ["GET", "GET", "POST"] if invalidate else ["GET", "POST"] + ) def test_invalidating_an_unopened_mount_needs_no_drive_request(mock_drive): From aa8ca7f8ba6aa4d92ba35e5c412db7eb769c26b8 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 27 Nov 2026 16:39:24 -0800 Subject: [PATCH 02/17] Stop warm directory checks at the first verified match --- pydrive2/fs/cache.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index 0cfb1d0..d0664e4 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -149,7 +149,13 @@ def has_directory(self, path, mount): with self.lock: if mount and not self._known_folder_ids(mount, verified=True): return False - return bool(self._known_folder_ids(path, verified=True)) + parent_path, _, name = path.rpartition("/") + parents = self._known_folder_ids(parent_path, verified=True) + return any( + (parent, name) not in self.incomplete + and self.children.get(parent, {}).get(name) + for parent in parents + ) def _parents_of_path(self, path): parent, _, name = path.rpartition("/") From e59768719d905a2c1e4044d96e4ea904f2fcc064 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 27 Nov 2026 16:41:44 -0800 Subject: [PATCH 03/17] Refresh same-name folders discovered during a file rename --- pydrive2/fs/cache.py | 16 ++++++++++++---- pydrive2/fs/spec.py | 7 +++++-- pydrive2/test/test_fs_unit.py | 24 ++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index d0664e4..3029e23 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -231,11 +231,19 @@ def _supersede(self, parents, name, *, until=None): if same_name and not pending.folders.keys().isdisjoint(parents): pending.generation = None - def file_added(self, parent, name): + def file_added(self, parent_id, name, *, parent_path=None): with self.lock: - self._supersede((parent,), name) - if name in self.children.get(parent, {}): - self.incomplete.add((parent, name)) + # A rename can leave the physical parent unchanged without ever + # requesting its ID. Recheck the name under each possible parent. + parents = ( + self._known_folder_ids(parent_path) + if parent_id is None + else (parent_id,) + ) + self._supersede(parents, name) + for parent in parents: + if name in self.children.get(parent, {}): + self.incomplete.add((parent, name)) @contextmanager def listing(self, generation, parents, *, name=None): diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 68d366d..9429bd4 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -900,8 +900,11 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): self._invalidate_folder( file1_id, path1, destination, known_folder=True ) - elif destination_parent is not None: - self._dirs.file_added(destination_parent, dst_name) + else: + _, parent_path = self._split_mounted_path(dst_parent) + self._dirs.file_added( + destination_parent, dst_name, parent_path=parent_path + ) def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): with _translate_not_found(rpath): diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index ca65b0b..cdac679 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -686,6 +686,30 @@ def test_renamed_duplicate_keeps_each_parents_children_warm(mock_drive): ] +def test_file_rename_rechecks_folder_discovered_during_the_move(mock_drive): + def list_destination(request): + if request[1] == "PATCH": + assert fs.ls("root") == ["root/new/"] + + old = {"id": "A", "name": "old", "mimeType": "text/plain"} + new = dict(old, name="new") + directory = folder("new", "Z") + drive, requests = mock_drive( + listing(), + listing(old), + listing(directory), + response(new), + listing(new, directory), + ({"status": "200", "content-length": "1"}, b"x"), + on_request=list_destination, + ) + fs = filesystem(drive) + fs.mv("root/old", "root/new") + with fs.open("root/new", "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + @pytest.mark.parametrize("operation", ["exists", "ls", "find"]) def test_failed_later_page_does_not_cache_partial_duplicate_matches( mock_drive, operation From 2a809898b3fe6fad37aa5acd1d367ffad93332f9 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 27 Nov 2026 16:42:37 -0800 Subject: [PATCH 04/17] Return a consistent tuple of known folder IDs --- pydrive2/fs/cache.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index 3029e23..d0aa691 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -125,20 +125,20 @@ def _drop_subtrees(self, roots): self.incomplete.discard((parent, name)) pending.extend(ids) - def _known_folder_ids(self, path, *, verified=False): - ids: tuple[str, ...] | list[str] = (self.root,) + def _known_folder_ids(self, path, *, verified=False) -> tuple[str, ...]: + ids: tuple[str, ...] = (self.root,) for part in path.split("/") if path else (): if len(ids) == 1: if verified and (ids[0], part) in self.incomplete: return () ids = self.children.get(ids[0], {}).get(part, ()) else: - ids = [ + ids = tuple( child for parent in ids if not verified or (parent, part) not in self.incomplete for child in self.children.get(parent, {}).get(part, ()) - ] + ) if not ids: break return ids From 51faac31db358c4a0458bfc1141e96d927126855 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 08:06:56 -0800 Subject: [PATCH 05/17] Reuse known folders through file-name collisions and narrow Drive probes --- docs/fsspec.rst | 10 +-- docs/upgrading.rst | 8 ++ pydrive2/fs/cache.py | 52 +++++++++---- pydrive2/fs/spec.py | 136 +++++++++++++++++++++------------- pydrive2/test/test_fs_unit.py | 119 +++++++++++++++++++++++++++++ 5 files changed, 256 insertions(+), 69 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 9abc448..e6ffcff 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -68,11 +68,11 @@ paths without a trailing slash, like fsspec's other traversal methods. Named directory lookups reuse cached Drive IDs. Listing a parent refreshes the folders seen under that parent. If a listing discovers a folder under -a new name, its cached children follow the folder's Drive ID. -If another client moves, -trashes, or deletes a folder, call ``fs.invalidate_cache("root/empty")`` -before looking up its old path again. The next lookup checks Drive for all -folders with that name, including any same-name folder that still exists. +a new name, its cached children follow the folder's Drive ID. If another +client moves, trashes, or deletes a folder, call +``fs.invalidate_cache("root/empty")`` before looking up its old path again. +The next lookup checks Drive for all folders with that name, including any +same-name folder that still exists. Drive queries for directory entries exclude trashed items. For a bare file ID, ``exists()`` returns false and ``info()`` raises ``FileNotFoundError`` diff --git a/docs/upgrading.rst b/docs/upgrading.rst index ecc8b33..1400695 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -23,6 +23,14 @@ Service accounts use their configured JSON or PKCS12 signing key. Keep the key available to the application. Deployments that relied solely on a saved service-account token need to provision the signing key. +Filesystem directory lookups +---------------------------- + +The :doc:`fsspec filesystem ` now caches folders returned by +``ls()``. Later calls such as ``exists("root/data")`` can reuse those IDs. +If another client moves or removes a folder, list its parent again or +call ``fs.invalidate_cache("root/data")`` before checking the old path. + Drive API fields and requests ----------------------------- diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index d0aa691..930037e 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -27,7 +27,14 @@ def add(self, parent, item): item["id"] ) else: - self.files.add((parent, item["name"])) + name = item["name"] + self.files.add((parent, name)) + # Keep all reported collisions even though the listing emits an ID once. + parents = item.get("parents", ()) + if len(parents) > 1: + self.files.update( + (p, name) for p in parents if p in self.folders + ) class DirectoryCache: @@ -43,40 +50,53 @@ def __init__(self, root: str): self.generation = 0 self._pending: dict[FolderListing, None] = {} self.children: dict[str, dict[str, tuple[str, ...]]] = {} + # For each ID in children[parent][name], parents[ID] is (parent, name). self.parents: dict[str, tuple[str, str]] = {} - # Names shared with files (or changed by a mutation) need a fresh lookup. + # A mutation can leave the set of matching folders uncertain. self.incomplete: set[tuple[str, str]] = set() - def _folders(self, parents, name): + # A file with this name matters only when selecting the final item ID. + self.file_collisions: set[tuple[str, str]] = set() + + def _folders(self, parents, name, *, folders_only): result: list[str] = [] for parent in parents: ids = self.children.get(parent, {}).get(name) - if ids is None or (parent, name) in self.incomplete: + edge = (parent, name) + if ( + ids is None + or edge in self.incomplete + or (not folders_only and edge in self.file_collisions) + ): return None result.extend(ids) return result or None - def lookup(self, parents, name, generation): + def lookup(self, parents, name, generation, *, folders_only): with self.lock: if generation == self.generation: - return self._folders(parents, name) + return self._folders(parents, name, folders_only=folders_only) return None - def prefix(self, path, generation): + def prefix(self, path, generation, *, folders_only=False): parts = path.split("/") if path else [] folders = [self.root] with self.lock: if generation != self.generation: return "", folders, parts for i, name in enumerate(parts): - found = self._folders(folders, name) + found = self._folders( + folders, + name, + folders_only=folders_only or i < len(parts) - 1, + ) if not found: return "/".join(parts[:i]), folders, parts[i:] folders = found return path, folders, [] def contains(self, path, generation): - return not self.prefix(path, generation)[2] + return not self.prefix(path, generation, folders_only=True)[2] def warm_parents(self, roots, maxdepth, generation): """Include only parents whose contents can contribute to this walk.""" @@ -100,6 +120,7 @@ def warm_parents(self, roots, maxdepth, generation): def _remove_name(self, parent, name): self.incomplete.discard((parent, name)) + self.file_collisions.discard((parent, name)) names = self.children.get(parent) if not names: return () @@ -123,6 +144,7 @@ def _drop_subtrees(self, roots): self.parents.pop(parent, None) for name, ids in self.children.pop(parent, {}).items(): self.incomplete.discard((parent, name)) + self.file_collisions.discard((parent, name)) pending.extend(ids) def _known_folder_ids(self, path, *, verified=False) -> tuple[str, ...]: @@ -168,6 +190,7 @@ def invalidate(self, path): self.children.clear() self.parents.clear() self.incomplete.clear() + self.file_collisions.clear() return parents, name = self._parents_of_path(path) for parent in parents: @@ -243,7 +266,7 @@ def file_added(self, parent_id, name, *, parent_path=None): self._supersede(parents, name) for parent in parents: if name in self.children.get(parent, {}): - self.incomplete.add((parent, name)) + self.file_collisions.add((parent, name)) @contextmanager def listing(self, generation, parents, *, name=None): @@ -285,7 +308,9 @@ def _observe(self, listing, name): ids = before if before is not None and ( before != ids - or (edge in self.incomplete) != (edge in listing.files) + or edge in self.incomplete + or (edge in self.file_collisions) + != (edge in listing.files) ): changed = True if before and before != ids: @@ -296,10 +321,11 @@ def _observe(self, listing, name): self.children.setdefault(parent, {})[key] = ids for item_id in ids: self.parents[item_id] = edge + self.incomplete.discard(edge) if edge in listing.files: - self.incomplete.add(edge) + self.file_collisions.add(edge) else: - self.incomplete.discard(edge) + self.file_collisions.discard(edge) else: self._remove_name(parent, key) self._drop_subtrees(retired) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 9429bd4..fee27a4 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -13,11 +13,7 @@ import appdirs from fsspec.spec import AbstractFileSystem -from funcy import ( - chunks, - distinct, - retry, -) +from funcy import chunks, retry from google.oauth2 import service_account from tqdm.utils import CallbackIOWrapper @@ -32,7 +28,7 @@ _LIST_FIELDS = ( f"nextPageToken,incompleteSearch,files(id,name,parents,{_INFO_FIELDS})" ) -_PARENT_QUERY_BATCH_SIZE = 50 +_MAX_QUERY_TERMS = 50 _DRIVE_SCOPE = "https://www.googleapis.com/auth/drive" _LIST_ALL_SCOPES = { _DRIVE_SCOPE + suffix @@ -451,22 +447,26 @@ def _gdrive_list(self, query): raise OSError(errno.EIO, "Incomplete Drive listing") yield from page - def _list_children(self, query_ids, *, name=None, require_parent=False): - filters = "trashed=false" - if name is not None: - filters += f" and name={_quote_query_value(name)}" - # Drive can reject large parent queries. Query each parent only once. + def _query_children(self, parents, names=()): + parent_query = " or ".join( + f"{_quote_query_value(p)} in parents" for p in parents + ) + query = f"({parent_query}) and trashed=false" + if names: + terms = " or ".join(f"name={_quote_query_value(n)}" for n in names) + query += f" and {terms}" if len(names) == 1 else f" and ({terms})" + return self._gdrive_list(query) + + def _list_children(self, listing, *, require_parent=False): + names = (listing.name,) if listing.name is not None else () seen_ids = set() - for batch in chunks(_PARENT_QUERY_BATCH_SIZE, distinct(query_ids)): - parents = " or ".join( - f"{_quote_query_value(parent)} in parents" for parent in batch - ) + for batch in chunks(_MAX_QUERY_TERMS, listing.folders): batch_ids = set(batch) - unplaced = set() - for item in self._gdrive_list(f"({parents}) and {filters}"): + unplaced = {} + for item in self._query_children(batch, names): + if names and item["name"] != listing.name: + continue # Drive matches case-insensitively. file_id = item["id"] - if file_id in seen_ids: - continue parent = next( (p for p in item.get("parents", ()) if p in batch_ids), None, @@ -482,49 +482,83 @@ def _list_children(self, query_ids, *, name=None, require_parent=False): # Drive can return the canonical ID of the root alias. parent = self.root if parent is None and require_parent: - unplaced.add(file_id) - else: - unplaced.discard(file_id) - seen_ids.add(file_id) - yield parent, item - # If a batched result omits its parents, find needs to establish - # the path. Probe only that batch, and only for the unplaced IDs. + if file_id not in seen_ids: + unplaced[file_id] = item["name"] + continue + unplaced.pop(file_id, None) + if file_id in seen_ids: + # A file may have moved between two parent queries. + if item["mimeType"] != FOLDER_MIME_TYPE: + listing.add(parent, item) + continue + listing.add(parent, item) + seen_ids.add(file_id) + yield parent, item + + # Some responses omit parents. Resolve only the missing IDs, using + # their names to avoid paging through unrelated siblings. + for parent_id in batch: + if not unplaced: + break + probes = dict.fromkeys(unplaced.values()) + # Bound the OR expression for unusually large sets of names. + if len(probes) > _MAX_QUERY_TERMS: + probes.clear() + for item in self._query_children([parent_id], probes): + file_id = item["id"] + if file_id in unplaced: + del unplaced[file_id] + listing.add(parent_id, item) + seen_ids.add(file_id) + yield parent_id, item if unplaced: - for parent_id in batch: - for _, item in self._list_children([parent_id], name=name): - if item["id"] in unplaced: - unplaced.remove(item["id"]) - seen_ids.add(item["id"]) - yield parent_id, item - if not unplaced: - break - - def _match_child(self, generation, parent_ids, path, name, mount=None): + # An item can change during the probes. This batch cannot + # establish which cached folders have disappeared. + listing.complete = False + + def _match_child( + self, + generation, + parent_ids, + path, + name, + mount=None, + *, + folders_only=False, + ): if path == self.base and mount is not None: return mount, generation - folders = self._dirs.lookup(parent_ids, name, generation) + folders = self._dirs.lookup( + parent_ids, name, generation, folders_only=folders_only + ) if folders: return _PathMatch(folders), generation match = _PathMatch([]) with self._dirs.listing(generation, parent_ids, name=name) as listing: - for parent, item in self._list_children(parent_ids, name=name): - if item["name"] != name: # Drive matches case-insensitively. - continue - listing.add(parent, item) + for _, item in self._list_children(listing): if item["mimeType"] == FOLDER_MIME_TYPE: match.folders.append(item["id"]) else: match.files.append(item) return match, listing.generation - def _resolve_prefix(self, path, generation, mount=None): + def _resolve_prefix( + self, path, generation, mount=None, *, folders_only=False + ): """Return the deepest existing component, its matches and lookup generation.""" - parent, folders, remaining = self._dirs.prefix(path, generation) + parent, folders, remaining = self._dirs.prefix( + path, generation, folders_only=folders_only + ) match = _PathMatch(folders) for name in remaining: child = posixpath.join(parent, name) found, generation = self._match_child( - generation, match.folders, child, name, mount + generation, + match.folders, + child, + name, + mount, + folders_only=folders_only or child != path, ) if not found.folders and not found.files: break @@ -540,7 +574,9 @@ def _resolve_path(self, path, generation, mount=None): return (match if prefix == path else _PathMatch([])), generation def _ensure_dirs(self, path, generation, mount=None): - parent, folders, remaining = self._dirs.prefix(path, generation) + parent, folders, remaining = self._dirs.prefix( + path, generation, folders_only=True + ) for name in remaining: parent = posixpath.join(parent, name) match, generation = self._get_or_create_child( @@ -595,7 +631,7 @@ def _get_or_create_child( with lock: # Check Drive under the same name lock as the create on a cache miss. match, generation = self._match_child( - generation, parents, path, name, mount + generation, parents, path, name, mount, folders_only=True ) if match.folders or match.files: if not exist_ok: @@ -639,7 +675,7 @@ def _mkdir(self, path, create_parents, exist_ok): folders, generation = self._ensure_dirs(parent, generation, mount) else: prefix, match, generation = self._resolve_prefix( - parent, generation, mount + parent, generation, mount, folders_only=True ) if not match.folders: raise NotADirectoryError(posixpath.join(root, prefix)) @@ -701,11 +737,10 @@ def ls(self, path, detail=False): root_path = posixpath.join(bucket, base) contents = [] with self._dirs.listing(generation, dir_ids) as listing: - for parent, item in self._list_children(dir_ids): + for _, item in self._list_children(listing): contents.append( _file_entry(posixpath.join(root_path, item["name"]), item) ) - listing.add(parent, item) if detail: return contents return [entry["name"] for entry in contents] @@ -722,10 +757,9 @@ def _walk_folders(self, base, start_ids, generation, maxdepth): with self._dirs.listing(generation, to_list) as listing: children.update((parent, []) for parent in to_list) for parent, item in self._list_children( - to_list, require_parent=True + listing, require_parent=True ): children[parent].append(item) - listing.add(parent, item) generation = listing.generation visited.update(frontier) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index cdac679..9381b7e 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -453,6 +453,70 @@ def test_ls_deduplicates_a_file_shared_across_parent_batches(mock_drive): ] == [parents[:50], parents[50:]] +@pytest.mark.parametrize( + ("count", "moved"), [(2, False), (51, False), (51, True)] +) +def test_find_remembers_file_collisions_under_every_reported_parent( + mock_drive, count, moved +): + parents = [folder(f"dir{i}", f"P{i}") for i in range(count)] + last = parents[-1] + file = { + "id": "A", + "name": "item", + "mimeType": "text/plain", + "parents": ["P0", last["id"]], + } + directory = dict(folder("item", "Z"), parents=[last["id"]]) + drive, requests = mock_drive( + listing(*parents), + *( + [listing(dict(file, parents=["P0"]) if moved else file)] + if count > 50 + else [] + ), + listing( + dict(file, parents=[last["id"]]) if moved else file, directory + ), + listing(file, directory), + ({"status": "200", "content-length": "1"}, b"x"), + ) + fs = filesystem(drive) + assert fs.find("root", maxdepth=2) == ["root/dir0/item"] + with fs.open(f"root/{last['name']}/item", "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +@pytest.mark.parametrize("mount", ["root", "root/data", "root/data/sub"]) +def test_warm_file_lookup_and_upload_through_a_same_name_folder( + mock_drive, mount +): + data = folder("data", "D") + file = {"id": "A", "name": "data", "mimeType": "text/plain"} + sub = folder("sub", "S") + note = dict(file, id="N", name="note") + drive, requests = mock_drive( + listing(data, file), + listing(sub), + listing(note), + listing(note), + ({"status": "200", "location": "https://example.test/upload"}, ""), + response({"id": "uploaded"}), + ) + fs = filesystem(drive, mount) + assert fs.exists("root/data/sub/note") + before = len(requests) + fs.makedirs("root/data/sub", exist_ok=True) + assert len(requests) == before + assert fs.exists("root/data/sub/note") + assert [query(req)["q"] for req in requests[before:]] == [ + ["('S' in parents) and trashed=false and name='note'"] + ] + fs.touch("root/data/uploaded") + assert [req[1] for req in requests[before + 1 :]] == ["POST", "PUT"] + + def test_ls_finishes_listing_parents_resolved_before_a_rename(mock_drive): parents = [folder("dir", f"id-{i}") for i in range(51)] renamed = dict(parents[-1], name="renamed") @@ -749,6 +813,61 @@ def test_find_locates_unattributed_child_of_a_batched_parent(mock_drive): ["A"], ["B"], ] + assert all("name='note'" in query(r)["q"][0] for r in requests[2:]) + + +def test_find_probes_only_the_remaining_names_and_matches_ids(mock_drive): + a, b = folder("a", "A"), folder("b", "B") + one = {"id": "1", "name": "one", "mimeType": "text/plain"} + two = dict(one, id="2", name="two") + drive, requests = mock_drive( + listing(a, b), + listing(one, two), + listing(one, dict(two, id="unrelated")), + listing(two), + ) + assert filesystem(drive).find("root") == ["root/a/one", "root/b/two"] + assert [query(r)["q"][0] for r in requests[2:]] == [ + "('A' in parents) and trashed=false and (name='one' or name='two')", + "('B' in parents) and trashed=false and name='two'", + ] + + +def test_find_bounds_the_query_when_many_items_omit_their_parents(mock_drive): + items = [ + {"id": str(i), "name": f"file-{i}", "mimeType": "text/plain"} + for i in range(51) + ] + drive, requests = mock_drive( + listing(folder("a", "A"), folder("b", "B")), + listing(*items), + listing(*items), + ) + assert filesystem(drive).find("root") == sorted( + f"root/a/{item['name']}" for item in items + ) + assert len(requests) == 3 + assert query(requests[-1])["q"] == ["('A' in parents) and trashed=false"] + + +def test_unplaced_item_cannot_evict_a_cached_folder(mock_drive): + a, b = (dict(folder(n, n.upper()), parents=["root"]) for n in ("a", "b")) + item = folder("renamed", "C") + drive, requests = mock_drive( + listing(a, b), + listing(folder("old", "C")), + listing(a, b, item), + listing(), + listing(), + listing(), + ) + fs = filesystem(drive) + fs.ls("root") + assert fs.exists("root/a/old") + assert fs.find("root", maxdepth=2) == [] + before = len(requests) + assert fs.exists("root/a/old") + assert len(requests) == before def test_ls_started_before_invalidation_cannot_evict_a_new_lookup(mock_drive): From c595e52bd7a84b8db84257f494143bf6659a1b0c Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 09:38:12 -0800 Subject: [PATCH 06/17] Order folder cache observations across overlapping Drive requests --- pydrive2/fs/cache.py | 112 ++++++++++++++++++----------- pydrive2/fs/spec.py | 66 ++++++++++------- pydrive2/test/test_fs_unit.py | 131 ++++++++++++++++++++++++++++++++++ 3 files changed, 241 insertions(+), 68 deletions(-) diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index 930037e..4674c0f 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -2,15 +2,24 @@ from collections import defaultdict from contextlib import contextmanager +from itertools import count from threading import RLock +from typing import NamedTuple FOLDER_MIME_TYPE = "application/vnd.google-apps.folder" +class FolderLocation(NamedTuple): + parent: str + name: str + revision: int + + class FolderListing: """Accumulate one logical listing across all pages and parent batches.""" - def __init__(self, parents, name, generation): + def __init__(self, parents, name, generation, revision): + self.revision = revision self.name = name self.generation = generation self.folders: dict[str, dict[str, list[str]]] = { @@ -40,18 +49,19 @@ def add(self, parent, item): class DirectoryCache: """Keep children attached to Drive IDs across moves. - Invalidation advances the generation. Overlapping listings of the same - name can also supersede a pending response before it publishes its edges. + Mutations can invalidate an operation's generation. Reads are ordered by + when each listing started, including when an ID appears under a new name. """ def __init__(self, root: str): self.root = root self.lock = RLock() self.generation = 0 + self._revisions = count() self._pending: dict[FolderListing, None] = {} self.children: dict[str, dict[str, tuple[str, ...]]] = {} - # For each ID in children[parent][name], parents[ID] is (parent, name). - self.parents: dict[str, tuple[str, str]] = {} + # Each child records its parent/name and the revision that placed it. + self.parents: dict[str, FolderLocation] = {} # A mutation can leave the set of matching folders uncertain. self.incomplete: set[tuple[str, str]] = set() @@ -130,7 +140,7 @@ def _remove_name(self, parent, name): return ids def _unlink(self, item_id): - parent, name = self.parents.pop(item_id) + parent, name, _ = self.parents.pop(item_id) ids = self.children[parent][name] if len(ids) == 1: self._remove_name(parent, name) @@ -214,7 +224,7 @@ def moved(self, generation, item_id, parent, name): with self.lock: if generation != self.generation or item_id not in self.parents: return False - old_parent, _ = self.parents[item_id] + old_parent = self.parents[item_id].parent # A rename leaves the physical parent unchanged. if parent is None: parent = old_parent @@ -222,36 +232,40 @@ def moved(self, generation, item_id, parent, name): edge = (parent, name) names = self.children.setdefault(parent, {}) names[name] = (*names.get(name, ()), item_id) - self.parents[item_id] = edge + self.parents[item_id] = FolderLocation( + parent, name, next(self._revisions) + ) # The destination can already contain same-name files or folders. self.incomplete.add(edge) self.generation += 1 return True - def created(self, generation, parents, parent, name, item_id): + def created(self, listing, parent, item_id): + # The empty name lookup and the folder POST share this listing. A + # concurrent file write can supersede it until the POST has finished. with self.lock: - # A new child only changes this parent's listing. Independent - # creations can still publish and reuse their own folder IDs. - self._supersede((parent,), name) - if generation == self.generation: - for p in parents: - self.children.setdefault(p, {}).setdefault(name, ()) - ids = self.children[parent][name] - if item_id not in ids: - self.children[parent][name] = (*ids, item_id) - self.parents[item_id] = (parent, name) - elif name in self.children.get(parent, {}): - self.incomplete.add((parent, name)) - return generation - - def _supersede(self, parents, name, *, until=None): + self._supersede((parent,), listing.name, exclude=listing) + if ( + listing.generation != self.generation + and listing.name in self.children.get(parent, {}) + ): + self.incomplete.add((parent, listing.name)) + listing.folders[parent][listing.name] = [item_id] + + def _supersede( + self, parents, name, *, until=None, exclude=None, retired=False + ): # A newer completed listing can confirm an absence before an older # request has even published its first edge for that name. for pending in self._pending: if pending is until: break + if pending is exclude: + continue same_name = name is None or pending.name in (None, name) - if same_name and not pending.folders.keys().isdisjoint(parents): + if retired or ( + same_name and not pending.folders.keys().isdisjoint(parents) + ): pending.generation = None def file_added(self, parent_id, name, *, parent_path=None): @@ -270,14 +284,15 @@ def file_added(self, parent_id, name, *, parent_path=None): @contextmanager def listing(self, generation, parents, *, name=None): - listing = FolderListing(parents, name, generation) with self.lock: + listing = FolderListing( + parents, name, generation, next(self._revisions) + ) self._pending[listing] = None try: yield listing with self.lock: if listing.complete and listing.generation == self.generation: - self._supersede(listing.folders, name, until=listing) self._observe(listing, name) finally: with self.lock: @@ -285,7 +300,20 @@ def listing(self, generation, parents, *, name=None): def _observe(self, listing, name): groups = listing.folders - changed = self._relink(groups) + # Parents resolved by the caller can disappear while Drive is listing. + # Publishing children under detached IDs would create unreachable edges. + if any(p != self.root and p not in self.parents for p in groups): + groups = { + p: names + for p, names in groups.items() + if p == self.root or p in self.parents + } + if not groups: + listing.generation = None + return + if not self._relink(groups, listing.revision): + listing.generation = None + return retired: list[str] = [] has_folder = any(groups.values()) for parent, names in groups.items(): @@ -306,21 +334,15 @@ def _observe(self, listing, name): and set(before) == set(ids) ): ids = before - if before is not None and ( - before != ids - or edge in self.incomplete - or (edge in self.file_collisions) - != (edge in listing.files) - ): - changed = True if before and before != ids: retired.extend(set(before).difference(ids)) # Remember an empty sibling only if this exact name matched # a folder under another queried parent. Never cache misses alone. if ids or (name is not None and has_folder): self.children.setdefault(parent, {})[key] = ids + location = FolderLocation(parent, key, listing.revision) for item_id in ids: - self.parents[item_id] = edge + self.parents[item_id] = location self.incomplete.discard(edge) if edge in listing.files: self.file_collisions.add(edge) @@ -329,11 +351,11 @@ def _observe(self, listing, name): else: self._remove_name(parent, key) self._drop_subtrees(retired) - if changed: - self.generation += 1 - listing.generation = self.generation + # Retired IDs have no reverse entry left to check against an older + # result. Only reads started before this observation need that barrier. + self._supersede(groups, name, until=listing, retired=bool(retired)) - def _relink(self, groups): + def _relink(self, groups, revision): # Unlink moved IDs before pruning absent names. Their children stay # attached to the same ID even when an ancestor changes name or parent. moved = defaultdict(set) @@ -341,8 +363,12 @@ def _relink(self, groups): for name, ids in names.items(): for item_id in ids: old = self.parents.get(item_id) - if old is not None and old != (parent, name): - moved[old].add(item_id) + if old is not None and ( + old.parent != parent or old.name != name + ): + if old.revision > revision: + return False + moved[old.parent, old.name].add(item_id) for (parent, name), leaving in moved.items(): remaining = tuple( i for i in self.children[parent][name] if i not in leaving @@ -351,4 +377,4 @@ def _relink(self, groups): self.children[parent][name] = remaining else: self._remove_name(parent, name) - return bool(moved) + return True diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index fee27a4..a144bc3 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -525,22 +525,40 @@ def _match_child( mount=None, *, folders_only=False, + create_in=None, + exist_ok=True, ): - if path == self.base and mount is not None: - return mount, generation - folders = self._dirs.lookup( - parent_ids, name, generation, folders_only=folders_only - ) - if folders: - return _PathMatch(folders), generation - match = _PathMatch([]) - with self._dirs.listing(generation, parent_ids, name=name) as listing: - for _, item in self._list_children(listing): - if item["mimeType"] == FOLDER_MIME_TYPE: + match = mount if path == self.base else None + if match is None: + folders = self._dirs.lookup( + parent_ids, name, generation, folders_only=folders_only + ) + if folders: + match = _PathMatch(folders) + created = False + if match is None: + match = _PathMatch([]) + with self._dirs.listing( + generation, parent_ids, name=name + ) as listing: + for _, item in self._list_children(listing): + if item["mimeType"] == FOLDER_MIME_TYPE: + match.folders.append(item["id"]) + else: + match.files.append(item) + if ( + create_in is not None + and not match.folders + and not match.files + ): + item = self._gdrive_create_dir(create_in, name) + self._dirs.created(listing, create_in, item["id"]) match.folders.append(item["id"]) - else: - match.files.append(item) - return match, listing.generation + created = True + generation = listing.generation + if not exist_ok and not created: + raise FileExistsError(posixpath.join(self.root, path)) + return match, generation def _resolve_prefix( self, path, generation, mount=None, *, folders_only=False @@ -630,18 +648,16 @@ def _get_or_create_child( lock = self._creation_locks[key] = threading.RLock() with lock: # Check Drive under the same name lock as the create on a cache miss. - match, generation = self._match_child( - generation, parents, path, name, mount, folders_only=True - ) - if match.folders or match.files: - if not exist_ok: - raise FileExistsError(posixpath.join(self.root, path)) - return match, generation - item = self._gdrive_create_dir(parent_id, name) - generation = self._dirs.created( - generation, parents, parent_id, name, item["id"] + return self._match_child( + generation, + parents, + path, + name, + mount, + folders_only=True, + create_in=parent_id, + exist_ok=exist_ok, ) - return _PathMatch([item["id"]]), generation def mkdir(self, path, create_parents=True, **kwargs): self._mkdir(path, create_parents, exist_ok=False) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 9381b7e..87d9e6b 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -1488,6 +1488,137 @@ def test_rmdir_checks_emptiness_again_after_transient_failure(mock_drive): assert [r[1] for r in requests] == ["GET", "GET", "DELETE", "GET"] +def test_upload_while_mkdir_is_waiting_for_drive_keeps_both_matches( + mock_drive, +): + started, release = Event(), Event() + + def pause_create(request): + if request[1] == "POST": + started.set() + assert release.wait(5) + + directory = folder("item", "Z") + file = {"id": "A", "name": "item", "mimeType": "text/plain"} + creator, _ = mock_drive( + listing(), response(directory), on_request=pause_create + ) + drive, requests = mock_drive( + ({"status": "200", "location": "https://example.test/upload"}, ""), + response(file), + listing(file, directory), + ({"status": "200", "content-length": "1"}, b"x"), + ) + fs = filesystem(drive) + http = creator.auth.thread_local.http + + def create(): + drive.auth.thread_local.http = http + fs.mkdir("root/item") + + with ThreadPoolExecutor(max_workers=1) as pool: + pending = pool.submit(create) + try: + assert started.wait(5) + fs.touch("root/item") + finally: + release.set() + pending.result(timeout=5) + + with fs.open("root/item", "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +def test_listing_cannot_warm_children_of_a_detached_folder(mock_drive): + def remove_parent(request): + if query(request).get("q") == ["('D' in parents) and trashed=false"]: + assert fs.ls("root") == [] + + drive, requests = mock_drive( + listing(folder("old", "D")), + listing(), + listing(folder("child", "C")), + listing(folder("new", "D")), + listing(), + on_request=remove_parent, + ) + fs = filesystem(drive) + assert fs.ls("root/old") == ["root/old/child/"] + assert fs.exists("root/new") + assert not fs.exists("root/new/child") + assert "name='child'" in query(requests[-1])["q"][0] + + +def test_delayed_cold_lookup_cannot_restore_a_folders_old_name(mock_drive): + def observe_new_name(request): + if "name='old'" in query(request)["q"][0] and not requests: + assert fs.exists("root/new") + + drive, requests = mock_drive( + listing(folder("new", "D")), + listing(folder("old", "D")), + listing(), + on_request=observe_new_name, + ) + fs = filesystem(drive) + assert fs.exists("root/old") + assert not fs.exists("root/old") + assert fs.exists("root/new") + assert len(requests) == 3 + + +@pytest.mark.parametrize("older_finishes_first", [True, False]) +def test_newer_listing_determines_which_id_a_warm_read_uses( + mock_drive, older_finishes_first +): + file = {"id": "A", "name": "item", "mimeType": "text/plain"} + current, stale = folder("item", "CURRENT"), folder("item", "STALE") + path = "root/item" + media = ({"status": "200", "content-length": "1"}, b"x") + drive, requests = mock_drive( + listing(current, file), listing(current, file), media + ) + fs = filesystem(drive) + fs.ls("root") + + def start(pool, items): + started, release = Event(), Event() + + def hold_lookup(request): + if "q" in query(request): + started.set() + assert release.wait(5) + + worker, _ = mock_drive(listing(*items), media, on_request=hold_lookup) + http = worker.auth.thread_local.http + + def read(): + drive.auth.thread_local.http = http + with fs.open(path, "rb") as stream: + return stream.read() + + result = pool.submit(read) + assert started.wait(5) + return release, result + + with ThreadPoolExecutor(max_workers=2) as pool: + older = start(pool, [stale]) + newer = start(pool, [file, current]) + first, second = ( + (older, newer) if older_finishes_first else (newer, older) + ) + try: + first[0].set() + assert first[1].result(timeout=5) == b"x" + finally: + second[0].set() + assert second[1].result(timeout=5) == b"x" + with fs.open(path, "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + @pytest.mark.parametrize("invalidate", [False, True]) def test_concurrent_copies_create_their_shared_folder_once( mock_drive, invalidate From 22b92f0665132743d5e29e126862a44a9d472b53 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 09:38:25 -0800 Subject: [PATCH 07/17] Use the latest parent seen for an item across Drive listing batches --- pydrive2/fs/spec.py | 32 +++++++++++++++++--------------- pydrive2/test/test_fs_unit.py | 31 ++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 16 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index a144bc3..eb95be2 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -445,7 +445,7 @@ def _gdrive_list(self, query): for page in iter(get_list, None): if file_list.metadata.get("incompleteSearch"): raise OSError(errno.EIO, "Incomplete Drive listing") - yield from page + yield from (item.metadata for item in page) def _query_children(self, parents, names=()): parent_query = " or ".join( @@ -459,7 +459,9 @@ def _query_children(self, parents, names=()): def _list_children(self, listing, *, require_parent=False): names = (listing.name,) if listing.name is not None else () - seen_ids = set() + # Drive can return the same ID on multiple pages or in different + # batches. Wait for the last attributable row before constructing paths. + rows: dict[str, tuple[str | None, dict]] = {} for batch in chunks(_MAX_QUERY_TERMS, listing.folders): batch_ids = set(batch) unplaced = {} @@ -482,18 +484,16 @@ def _list_children(self, listing, *, require_parent=False): # Drive can return the canonical ID of the root alias. parent = self.root if parent is None and require_parent: - if file_id not in seen_ids: - unplaced[file_id] = item["name"] + unplaced[file_id] = item["name"] continue unplaced.pop(file_id, None) - if file_id in seen_ids: - # A file may have moved between two parent queries. - if item["mimeType"] != FOLDER_MIME_TYPE: - listing.add(parent, item) - continue - listing.add(parent, item) - seen_ids.add(file_id) - yield parent, item + previous = rows.get(file_id) + if previous is not None: + previous_parent, _ = previous + if previous_parent in item.get("parents", ()): + # Shared memberships still refer to one output item. + parent = previous_parent + rows[file_id] = parent, item # Some responses omit parents. Resolve only the missing IDs, using # their names to avoid paging through unrelated siblings. @@ -508,14 +508,16 @@ def _list_children(self, listing, *, require_parent=False): file_id = item["id"] if file_id in unplaced: del unplaced[file_id] - listing.add(parent_id, item) - seen_ids.add(file_id) - yield parent_id, item + rows[file_id] = parent_id, item if unplaced: # An item can change during the probes. This batch cannot # establish which cached folders have disappeared. listing.complete = False + for parent, item in rows.values(): + listing.add(parent, item) + yield parent, item + def _match_child( self, generation, diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 87d9e6b..dc5472f 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -482,7 +482,9 @@ def test_find_remembers_file_collisions_under_every_reported_parent( ({"status": "200", "content-length": "1"}, b"x"), ) fs = filesystem(drive) - assert fs.find("root", maxdepth=2) == ["root/dir0/item"] + assert fs.find("root", maxdepth=2) == [ + f"root/{last['name']}/item" if moved else "root/dir0/item" + ] with fs.open(f"root/{last['name']}/item", "rb") as stream: assert stream.read() == b"x" assert urlsplit(requests[-1][0]).path.endswith("/files/A") @@ -517,6 +519,33 @@ def test_warm_file_lookup_and_upload_through_a_same_name_folder( assert [req[1] for req in requests[before + 1 :]] == ["POST", "PUT"] +@pytest.mark.parametrize("is_folder", [True, False]) +def test_find_uses_the_last_location_seen_for_a_moved_id( + mock_drive, is_folder +): + parents = [folder(f"dir{i}", f"P{i}") for i in range(51)] + child = ( + folder("before", "C") + if is_folder + else {"name": "before", "id": "C", "mimeType": "text/plain"} + ) + drive, requests = mock_drive( + listing(*parents), + listing(dict(child, parents=["P0"])), + listing(dict(child, name="after", parents=["P50"])), + listing(), + ) + fs = filesystem(drive) + result = fs.find("root", maxdepth=2, withdirs=True) + assert "root/dir50/after" in result + assert "root/dir0/before" not in result + if is_folder: + before = len(requests) + assert fs.exists("root/dir50/after") + assert len(requests) == before + assert not fs.exists("root/dir0/before") + + def test_ls_finishes_listing_parents_resolved_before_a_rename(mock_drive): parents = [folder("dir", f"id-{i}") for i in range(51)] renamed = dict(parents[-1], name="renamed") From 7b3f614ec4628676de3f8c81e58d4485e248578d Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 09:38:38 -0800 Subject: [PATCH 08/17] Move items into folder IDs when destination names are ambiguous --- pydrive2/fs/spec.py | 20 +++++++++++++++----- pydrive2/test/test_fs_unit.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index eb95be2..4539c1b 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -587,9 +587,11 @@ def _resolve_prefix( break return parent, match, generation - def _resolve_path(self, path, generation, mount=None): + def _resolve_path( + self, path, generation, mount=None, *, folders_only=False + ): prefix, match, generation = self._resolve_prefix( - path, generation, mount + path, generation, mount, folders_only=folders_only ) return (match if prefix == path else _PathMatch([])), generation @@ -607,12 +609,14 @@ def _ensure_dirs(self, path, generation, mount=None): folders = match.folders return folders, generation - def _lookup_path(self, path): + def _lookup_path(self, path, *, folders_only=False): if not path: with self._cache_lock: return _PathMatch([self.root]), self._dirs.generation generation, mount = self._resolve_mount() - return self._resolve_path(path, generation, mount) + return self._resolve_path( + path, generation, mount, folders_only=folders_only + ) def _path_to_item_ids(self, path, create=False): if create and path: @@ -934,7 +938,13 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): destination_parent = None if src_parent != dst_parent: - destination_parent = self._get_item_id(dst_parent) + _, parent_path = self._split_mounted_path(dst_parent) + parent_match, _ = self._lookup_path(parent_path, folders_only=True) + if parent_match.files and not parent_match.folders: + raise NotADirectoryError(dst_parent) + destination_parent = _select_item_id( + dst_parent, parent_match.folders + ) file1["parents"] = [destination_parent] file1.Upload() diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index dc5472f..3ecd284 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -1033,6 +1033,34 @@ def test_directory_mutation_evicts_descendants_only(mock_drive, operation): assert len(requests) == before +def test_move_into_a_folder_that_shares_its_name_with_a_file(mock_drive): + dest = folder("dest", "Z") + file = {"id": "A", "name": "dest", "mimeType": "text/plain"} + source = dict(file, id="source", name="source", parents=["root"]) + drive, requests = mock_drive( + listing(file, dest), + listing(source), + response({"parents": ["root"]}), + response(source), + ) + fs = filesystem(drive) + fs.ls("root") + fs.mv("root/source", "root/dest") + update = requests[-1] + assert update[1] == "PATCH" + assert query(update)["addParents"] == ["Z"] + assert len(requests) == 4 + + +def test_move_rejects_a_file_as_the_destination_parent(mock_drive): + file = {"id": "A", "name": "dest", "mimeType": "text/plain"} + source = dict(file, id="source", name="source") + drive, requests = mock_drive(listing(file), listing(source), listing(file)) + with pytest.raises(NotADirectoryError): + filesystem(drive).mv("root/source", "root/dest") + assert all(r[1] == "GET" for r in requests) + + def test_move_directory_to_implicit_root(mock_drive): moved = folder("dir", "dir-id") drive, requests = mock_drive( From 94b9d130d3e1616bad7dc0e2e4713b63c97659d7 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 10:39:04 -0800 Subject: [PATCH 09/17] Reuse warm folder IDs for traversal and bound hidden-parent lookups --- pydrive2/fs/cache.py | 13 +- pydrive2/fs/spec.py | 55 ++-- pydrive2/test/test_fs_listing.py | 76 ----- pydrive2/test/test_fs_unit.py | 483 ++++++++++++++++++++++++------- 4 files changed, 416 insertions(+), 211 deletions(-) delete mode 100644 pydrive2/test/test_fs_listing.py diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index 4674c0f..2216875 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -29,21 +29,16 @@ def __init__(self, parents, name, generation, revision): self.complete = True def add(self, parent, item): - if parent is None: + # Drive v3 defines one parent per item. An ambiguous response cannot + # establish which names are complete for either parent. + if parent is None or len(item.get("parents", ())) > 1: self.complete = False elif item["mimeType"] == FOLDER_MIME_TYPE: self.folders[parent].setdefault(item["name"], []).append( item["id"] ) else: - name = item["name"] - self.files.add((parent, name)) - # Keep all reported collisions even though the listing emits an ID once. - parents = item.get("parents", ()) - if len(parents) > 1: - self.files.update( - (p, name) for p in parents if p in self.folders - ) + self.files.add((parent, item["name"])) class DirectoryCache: diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 4539c1b..cb6a453 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -487,37 +487,38 @@ def _list_children(self, listing, *, require_parent=False): unplaced[file_id] = item["name"] continue unplaced.pop(file_id, None) - previous = rows.get(file_id) - if previous is not None: - previous_parent, _ = previous - if previous_parent in item.get("parents", ()): - # Shared memberships still refer to one output item. - parent = previous_parent rows[file_id] = parent, item - # Some responses omit parents. Resolve only the missing IDs, using - # their names to avoid paging through unrelated siblings. - for parent_id in batch: - if not unplaced: - break - probes = dict.fromkeys(unplaced.values()) - # Bound the OR expression for unusually large sets of names. - if len(probes) > _MAX_QUERY_TERMS: - probes.clear() - for item in self._query_children([parent_id], probes): - file_id = item["id"] - if file_id in unplaced: - del unplaced[file_id] - rows[file_id] = parent_id, item - if unplaced: - # An item can change during the probes. This batch cannot - # establish which cached folders have disappeared. + if unplaced and not self._locate_children(batch, unplaced, rows): + # An item can move or disappear before the probes finish. listing.complete = False for parent, item in rows.values(): listing.add(parent, item) yield parent, item + def _locate_children(self, parents, missing, rows): + """Place rows with hidden parent IDs using Drive's parent query.""" + size = 1 + while parents and missing: + probe, parents = parents[:size], parents[size:] + names = dict.fromkeys(missing.values()) + if len(names) > _MAX_QUERY_TERMS: + names.clear() + for item in self._query_children(probe, names): + item_id = item["id"] + if item_id not in missing: + continue + if size > 1: + parents = probe + break + rows[item_id] = probe[0], item + del missing[item_id] + # For one remaining ID, narrow the search by halves. Only a + # single-parent query can confirm where to place the item. + size = (len(parents) + 1) // 2 if len(missing) == 1 else 1 + return not missing + def _match_child( self, generation, @@ -749,8 +750,8 @@ def info(self, path): def ls(self, path, detail=False): bucket, base = self._split_mounted_path(path) - match, generation = self._lookup_path(base) - dir_ids = match.ids + match, generation = self._lookup_path(base, folders_only=True) + dir_ids = match.folders or match.ids if not dir_ids: raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), path @@ -819,7 +820,9 @@ def find( if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") generation, mount = self._resolve_mount() - match, generation = self._resolve_path(base, generation, mount) + match, generation = self._resolve_path( + base, generation, mount, folders_only=True + ) file = ( min(match.files, key=lambda item: item["id"], default=None) if not match.folders diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py deleted file mode 100644 index 69ad46a..0000000 --- a/pydrive2/test/test_fs_listing.py +++ /dev/null @@ -1,76 +0,0 @@ -import re - -import pytest - -from pydrive2.fs import GDriveFileSystem -from pydrive2.fs.spec import FOLDER_MIME_TYPE -from pydrive2.test.http_mock import query, response - - -def folders(count): - return [ - {"id": f"dir-{i}", "name": "dup", "mimeType": FOLDER_MIME_TYPE} - for i in range(count) - ] - - -def child(parent): - return { - "id": f"file-{parent}", - "name": parent, - "mimeType": "text/plain", - "parents": [parent], - } - - -@pytest.mark.parametrize("count", [0, 1, 50, 51, 100, 251]) -def test_ls_queries_each_duplicate_folder_once_in_batches(mock_drive, count): - roots = folders(count) - ids = [item["id"] for item in roots] - batches = [ids[i : i + 50] for i in range(0, count, 50)] - drive, requests = mock_drive( - response({"files": roots}), - *(response({"files": [child(i) for i in batch]}) for batch in batches), - ) - fs = GDriveFileSystem(google_auth=drive.auth, skip_instance_cache=True) - if count: - assert fs.ls("root/dup") == [f"root/dup/{i}" for i in ids] - else: - with pytest.raises(FileNotFoundError): - fs.ls("root/dup") - assert "name='dup'" in query(requests[0])["q"][0] - assert [ - re.findall(r"'([^']+)' in parents", query(request)["q"][0]) - for request in requests[1:] - ] == batches - - -@pytest.mark.parametrize("complete", [True, False]) -def test_ls_finishes_each_batch_before_requesting_the_next( - mock_drive, complete -): - roots = folders(51) - drive, requests = mock_drive( - response({"files": roots}), - response({"files": [child("dir-0")], "nextPageToken": "second"}), - response( - {"files": [child("dir-1")], "incompleteSearch": not complete} - ), - response({"files": [child("dir-50")]}), - ) - fs = GDriveFileSystem(google_auth=drive.auth, skip_instance_cache=True) - if complete: - assert fs.ls("root/dup") == [ - "root/dup/dir-0", - "root/dup/dir-1", - "root/dup/dir-50", - ] - assert query(requests[3])["q"] == [ - "('dir-50' in parents) and trashed=false" - ] - else: - with pytest.raises(OSError, match="Incomplete Drive listing"): - fs.ls("root/dup") - assert len(requests) == 3 - assert query(requests[2])["q"] == query(requests[1])["q"] - assert query(requests[2])["pageToken"] == ["second"] diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 3ecd284..b8baa3f 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -423,6 +423,78 @@ def test_recursive_remove_does_not_relist_each_directory(mock_drive): assert all("q" in query(req) for req in requests[:4]) +def batch_child(parent): + return { + "id": f"file-{parent}", + "name": parent, + "mimeType": "text/plain", + "parents": [parent], + } + + +@pytest.mark.parametrize("count", [1, 50, 51, 100, 251]) +def test_ls_queries_each_duplicate_folder_once_in_batches(mock_drive, count): + ids = [f"dir-{i}" for i in range(count)] + batches = [ids[i : i + 50] for i in range(0, count, 50)] + drive, requests = mock_drive( + listing(*(folder("dup", i) for i in ids)), + *(listing(*map(batch_child, batch)) for batch in batches), + ) + assert filesystem(drive).ls("root/dup") == [f"root/dup/{i}" for i in ids] + assert "name='dup'" in query(requests[0])["q"][0] + assert [ + re.findall(r"'([^']+)' in parents", query(req)["q"][0]) + for req in requests[1:] + ] == batches + + +def test_ls_missing_folder_only_queries_its_name(mock_drive): + drive, requests = mock_drive(listing()) + with pytest.raises(FileNotFoundError) as exc: + filesystem(drive).ls("root/dup") + assert exc.value.errno == errno.ENOENT + (request,) = requests + assert "name='dup'" in query(request)["q"][0] + + +def paged_duplicate_folders(mock_drive, last_page, *more): + return mock_drive( + listing(*(folder("dup", f"dir-{i}") for i in range(51))), + response({"files": [batch_child("dir-0")], "nextPageToken": "second"}), + last_page, + *more, + ) + + +def test_ls_finishes_all_pages_before_requesting_the_next_batch(mock_drive): + drive, requests = paged_duplicate_folders( + mock_drive, + listing(batch_child("dir-1")), + listing(batch_child("dir-50")), + ) + assert filesystem(drive).ls("root/dup") == [ + "root/dup/dir-0", + "root/dup/dir-1", + "root/dup/dir-50", + ] + _, first, second, last = requests + assert query(second)["q"] == query(first)["q"] + assert query(second)["pageToken"] == ["second"] + assert query(last)["q"] == ["('dir-50' in parents) and trashed=false"] + + +def test_ls_stops_before_the_next_batch_if_a_page_is_incomplete(mock_drive): + drive, requests = paged_duplicate_folders( + mock_drive, + response({"files": [batch_child("dir-1")], "incompleteSearch": True}), + ) + with pytest.raises(OSError, match="Incomplete Drive listing"): + filesystem(drive).ls("root/dup") + _, first, second = requests + assert query(second)["q"] == query(first)["q"] + assert query(second)["pageToken"] == ["second"] + + def test_ls_deduplicates_a_file_shared_across_parent_batches(mock_drive): parents = [f"parent-{i}" for i in range(51)] shared = { @@ -453,45 +525,46 @@ def test_ls_deduplicates_a_file_shared_across_parent_batches(mock_drive): ] == [parents[:50], parents[50:]] -@pytest.mark.parametrize( - ("count", "moved"), [(2, False), (51, False), (51, True)] -) -def test_find_remembers_file_collisions_under_every_reported_parent( - mock_drive, count, moved +def test_find_tracks_a_moved_file_that_now_shares_its_name_with_a_folder( + mock_drive, ): - parents = [folder(f"dir{i}", f"P{i}") for i in range(count)] - last = parents[-1] - file = { - "id": "A", - "name": "item", - "mimeType": "text/plain", - "parents": ["P0", last["id"]], - } - directory = dict(folder("item", "Z"), parents=[last["id"]]) + parents = [folder(f"dir{i}", f"P{i}") for i in range(51)] + file = {"id": "A", "name": "item", "mimeType": "text/plain"} + moved = dict(file, parents=["P50"]) + directory = dict(folder("item", "Z"), parents=["P50"]) drive, requests = mock_drive( listing(*parents), - *( - [listing(dict(file, parents=["P0"]) if moved else file)] - if count > 50 - else [] - ), - listing( - dict(file, parents=[last["id"]]) if moved else file, directory - ), - listing(file, directory), + listing(dict(file, parents=["P0"])), + listing(moved, directory), + listing(moved, directory), ({"status": "200", "content-length": "1"}, b"x"), ) fs = filesystem(drive) - assert fs.find("root", maxdepth=2) == [ - f"root/{last['name']}/item" if moved else "root/dir0/item" - ] - with fs.open(f"root/{last['name']}/item", "rb") as stream: + assert fs.find("root", maxdepth=2) == ["root/dir50/item"] + with fs.open("root/dir50/item", "rb") as stream: assert stream.read() == b"x" assert urlsplit(requests[-1][0]).path.endswith("/files/A") +@pytest.mark.parametrize("operation", ["ls", "find"]) +def test_warm_directory_listing_uses_one_request_when_a_file_shares_its_name( + mock_drive, operation +): + file = {"id": "A", "name": "data", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(file, folder("data", "Z")), + listing(dict(file, id="N", name="note")), + ) + fs = filesystem(drive) + fs.ls("root") + assert getattr(fs, operation)("root/data") == ["root/data/note"] + assert [query(r)["q"] for r in requests[1:]] == [ + ["('Z' in parents) and trashed=false"] + ] + + @pytest.mark.parametrize("mount", ["root", "root/data", "root/data/sub"]) -def test_warm_file_lookup_and_upload_through_a_same_name_folder( +def test_warm_calls_below_a_folder_with_a_same_name_file_reuse_its_id( mock_drive, mount ): data = folder("data", "D") @@ -519,16 +592,11 @@ def test_warm_file_lookup_and_upload_through_a_same_name_folder( assert [req[1] for req in requests[before + 1 :]] == ["POST", "PUT"] -@pytest.mark.parametrize("is_folder", [True, False]) -def test_find_uses_the_last_location_seen_for_a_moved_id( - mock_drive, is_folder +def test_find_caches_only_the_new_path_for_a_folder_moved_between_batches( + mock_drive, ): parents = [folder(f"dir{i}", f"P{i}") for i in range(51)] - child = ( - folder("before", "C") - if is_folder - else {"name": "before", "id": "C", "mimeType": "text/plain"} - ) + child = folder("before", "C") drive, requests = mock_drive( listing(*parents), listing(dict(child, parents=["P0"])), @@ -539,11 +607,10 @@ def test_find_uses_the_last_location_seen_for_a_moved_id( result = fs.find("root", maxdepth=2, withdirs=True) assert "root/dir50/after" in result assert "root/dir0/before" not in result - if is_folder: - before = len(requests) - assert fs.exists("root/dir50/after") - assert len(requests) == before - assert not fs.exists("root/dir0/before") + before = len(requests) + assert fs.exists("root/dir50/after") + assert len(requests) == before + assert not fs.exists("root/dir0/before") def test_ls_finishes_listing_parents_resolved_before_a_rename(mock_drive): @@ -632,7 +699,7 @@ def test_ls_evicts_the_old_path_after_a_folder_rename(mock_drive): @pytest.mark.parametrize("duplicate_parents", [False, True]) -def test_warm_read_keeps_same_name_file_and_folder_distinct( +def test_second_open_of_a_name_shared_by_a_file_and_folder_reads_the_same_id( mock_drive, duplicate_parents ): parents = [folder("dup", "P"), folder("dup", "Q")] @@ -718,38 +785,60 @@ def list_after_lookup_starts(request): assert len(requests) == 3 -@pytest.mark.parametrize("operation", ["touch", "cp_file", "mv"]) -def test_file_written_beside_cached_folder_can_be_read(mock_drive, operation): +WRITTEN_FILE = {"name": "item", "id": "A", "mimeType": "text/plain"} + + +@pytest.mark.parametrize( + ("write", "responses"), + [ + pytest.param( + lambda fs: fs.touch("root/dest/item"), + [ + ( + { + "status": "200", + "location": "https://example.test/upload", + }, + "", + ), + response(WRITTEN_FILE), + ], + id="touch", + ), + pytest.param( + lambda fs: fs.cp_file("root/source", "root/dest/item"), + [ + listing(dict(WRITTEN_FILE, name="source")), + response(WRITTEN_FILE), + ], + id="copy", + ), + pytest.param( + lambda fs: fs.mv("root/item", "root/dest"), + [ + listing(WRITTEN_FILE), + response({"parents": ["root"]}), + response(WRITTEN_FILE), + ], + id="move", + ), + ], +) +def test_file_written_beside_cached_folder_can_be_read( + mock_drive, write, responses +): directory = folder("item", "Z") - file = {"name": "item", "id": "A", "mimeType": "text/plain"} - src = dict(file, name="item" if operation == "mv" else "source") - dest = folder("dest", "P") - if operation == "touch": - write = [ - ({"status": "200", "location": "https://example.test/upload"}, ""), - response(file), - ] - elif operation == "cp_file": - write = [listing(src), response(file)] - else: - write = [listing(src), response({"parents": ["root"]}), response(file)] drive, requests = mock_drive( - listing(dest), + listing(folder("dest", "P")), listing(directory), - *write, - listing(file, directory), + *responses, + listing(WRITTEN_FILE, directory), ({"status": "200", "content-length": "1"}, b"x"), ) fs = filesystem(drive) - path = "root/dest/item" - assert fs.exists(path) - if operation == "touch": - fs.touch(path) - elif operation == "cp_file": - fs.cp_file("root/source", path) - else: - fs.mv("root/item", "root/dest") - with fs.open(path, "rb") as stream: + assert fs.exists("root/dest/item") + write(fs) + with fs.open("root/dest/item", "rb") as stream: assert stream.read() == b"x" assert urlsplit(requests[-1][0]).path.endswith("/files/A") @@ -826,26 +915,43 @@ def test_failed_later_page_does_not_cache_partial_duplicate_matches( assert "'A' in parents or 'B' in parents" in query(requests[-1])["q"][0] -def test_find_locates_unattributed_child_of_a_batched_parent(mock_drive): - a, b = folder("a", "A"), folder("b", "B") - item = {"id": "F", "name": "note", "mimeType": "text/plain"} - drive, requests = mock_drive( - listing(a, b), listing(item), listing(), listing(item) +@pytest.mark.parametrize( + ("actual_parent", "max_probes"), [("P0", 1), ("P24", 8), ("P49", 7)] +) +def test_find_bounds_requests_to_locate_one_item_without_parents( + mock_drive, mocker, actual_parent, max_probes +): + from httplib2 import Response + + folders = [folder(f"dir{i}", f"P{i}") for i in range(50)] + note = {"id": "N", "name": "note", "mimeType": "text/plain"} + drive, _ = mock_drive() + queries = [] + + def list_files(uri, method="GET", **kwargs): + assert method == "GET" + q = query((uri,))["q"][0] + parents = re.findall(r"'([^']+)' in parents", q) + queries.append(q) + if parents == ["root"]: + items = folders + else: + items = [note] if actual_parent in parents else [] + return Response({"status": "200"}), json.dumps( + {"files": items} + ).encode() + + mocker.patch.object( + drive.auth.thread_local.http, "request", side_effect=list_files ) - fs = filesystem(drive) - assert fs.find("root") == ["root/b/note"] - assert [ - re.findall(r"'([^']+)' in parents", query(r)["q"][0]) for r in requests - ] == [ - ["root"], - ["A", "B"], - ["A"], - ["B"], + assert filesystem(drive).find("root") == [ + f"root/dir{actual_parent[1:]}/note" ] - assert all("name='note'" in query(r)["q"][0] for r in requests[2:]) + assert 1 <= len(queries) - 2 <= max_probes + assert all("name='note'" in q for q in queries[2:]) -def test_find_probes_only_the_remaining_names_and_matches_ids(mock_drive): +def test_find_places_items_without_parents_by_name_and_id(mock_drive): a, b = folder("a", "A"), folder("b", "B") one = {"id": "1", "name": "one", "mimeType": "text/plain"} two = dict(one, id="2", name="two") @@ -862,7 +968,7 @@ def test_find_probes_only_the_remaining_names_and_matches_ids(mock_drive): ] -def test_find_bounds_the_query_when_many_items_omit_their_parents(mock_drive): +def test_find_bounds_the_query_for_many_items_without_parents(mock_drive): items = [ {"id": str(i), "name": f"file-{i}", "mimeType": "text/plain"} for i in range(51) @@ -879,7 +985,9 @@ def test_find_bounds_the_query_when_many_items_omit_their_parents(mock_drive): assert query(requests[-1])["q"] == ["('A' in parents) and trashed=false"] -def test_unplaced_item_cannot_evict_a_cached_folder(mock_drive): +def test_find_keeps_cached_folders_when_items_without_parents_disappear( + mock_drive, +): a, b = (dict(folder(n, n.upper()), parents=["root"]) for n in ("a", "b")) item = folder("renamed", "C") drive, requests = mock_drive( @@ -999,6 +1107,31 @@ def test_find_matches_legacy_parent_before_assuming_root(mock_drive): assert fs.find("root") == ["root/sub/child"] +def test_ambiguous_parent_row_cannot_hide_a_file_at_the_root_alias(mock_drive): + sub = dict(folder("sub", "P"), parents=["canonical-root"]) + directory = dict(folder("item", "Z"), parents=["canonical-root"]) + file = { + "name": "item", + "id": "A", + "mimeType": "text/plain", + "parents": ["canonical-root", "P"], + } + drive, requests = mock_drive( + listing(sub), + listing(sub, directory, file), + listing(), + listing(directory, file), + ({"status": "200", "content-length": "1"}, b"x"), + ) + fs = filesystem(drive) + assert fs.exists("root/sub") + assert fs.find("root", maxdepth=2) == ["root/sub/item"] + with fs.open("root/item", "rb") as stream: + assert stream.read() == b"x" + assert "name='item'" in query(requests[-2])["q"][0] + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + @pytest.mark.parametrize("operation", ["trash", "rename"]) def test_directory_mutation_evicts_descendants_only(mock_drive, operation): moved = folder("renamed", "dir-id") @@ -1587,27 +1720,174 @@ def create(): assert urlsplit(requests[-1][0]).path.endswith("/files/A") -def test_listing_cannot_warm_children_of_a_detached_folder(mock_drive): - def remove_parent(request): - if query(request).get("q") == ["('D' in parents) and trashed=false"]: - assert fs.ls("root") == [] +def finish_request_during_read( + mock_drive, responses, should_pause, first, second, *read_responses +): + """Start the second read while the first operation is waiting on Drive. + Return its older snapshot only after the first operation finishes. + """ + started, release = Event(), Event() - drive, requests = mock_drive( - listing(folder("old", "D")), - listing(), + def pause(request): + if should_pause(request): + started.set() + assert release.wait(5) + + def finish(request): + release.set() + pending.result(timeout=5) + + writer, _ = mock_drive(*responses, on_request=pause) + reader, requests = mock_drive(*read_responses, on_request=finish) + write_http = writer.auth.thread_local.http + + def run(): + fs.client.auth.thread_local.http = write_http + first(fs) + + fs = filesystem(reader) + with ThreadPoolExecutor(max_workers=1) as pool: + pending = pool.submit(run) + try: + assert started.wait(5) + second(fs) + finally: + release.set() + pending.result(timeout=5) + return fs, requests + + +def test_folder_retired_before_its_children_arrive_cannot_warm_the_new_path( + mock_drive, +): + def retire(fs): + assert fs.exists("root/old") + assert fs.ls("root") == [] + + def list_children(fs): + assert fs.ls("root/old") == ["root/old/child/"] + + fs, _ = finish_request_during_read( + mock_drive, + [listing(folder("old", "D")), listing()], + lambda req: ( + query(req).get("q") == ["('root' in parents) and trashed=false"] + ), + retire, + list_children, listing(folder("child", "C")), listing(folder("new", "D")), listing(), - on_request=remove_parent, ) - fs = filesystem(drive) - assert fs.ls("root/old") == ["root/old/child/"] assert fs.exists("root/new") assert not fs.exists("root/new/child") - assert "name='child'" in query(requests[-1])["q"][0] -def test_delayed_cold_lookup_cannot_restore_a_folders_old_name(mock_drive): +def test_late_lookup_cannot_reattach_an_id_retired_under_another_parent( + mock_drive, +): + def retire(request): + if ( + "name='previous'" in query(request).get("q", [""])[0] + and len(requests) == 2 + ): + assert fs.ls("root/p") == [] + + drive, requests = mock_drive( + listing(folder("p", "P")), + listing(folder("current", "D")), + listing(), + listing(folder("previous", "D")), + listing(), + on_request=retire, + ) + fs = filesystem(drive) + assert fs.exists("root/p/current") + assert fs.exists("root/previous") + assert not fs.exists("root/previous") + + +def test_listing_started_during_create_cannot_evict_the_new_folder(mock_drive): + def read(fs): + assert fs.ls("root") == [] + + fs, requests = finish_request_during_read( + mock_drive, + [listing(), response(folder("item", "A"))], + lambda req: req[1] == "POST", + lambda fs: fs.mkdir("root/item"), + read, + listing(), + listing(folder("item", "A")), + ) + before = len(requests) + assert fs.exists("root/item") + assert len(requests) == before + + +def test_create_rechecks_a_sibling_discovered_during_the_folder_post( + mock_drive, +): + sibling, created = folder("item", "Z"), folder("item", "A") + + def see_sibling(request): + if request[1] == "GET" and "q" not in query(request): + assert urlsplit(request[0]).path.endswith("/files/A") + if request[1] == "POST": + assert fs.ls("root") == ["root/item/"] + + drive, requests = mock_drive( + listing(), + listing(sibling), + response(created), + listing(sibling, created), + response(created), + on_request=see_sibling, + ) + fs = filesystem(drive) + fs.mkdir("root/item") + assert fs.info("root/item")["type"] == "directory" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +def test_listing_started_before_move_cannot_hide_the_arriving_folder( + mock_drive, +): + dest, moved, other = ( + folder("dest", "P"), + folder("item", "A"), + folder("item", "Z"), + ) + + def move(request): + if ( + request[1] == "GET" + and query(request).get("fields") != ["parents"] + and "q" not in query(request) + ): + assert urlsplit(request[0]).path.endswith("/files/A") + if query(request).get("q") == ["('P' in parents) and trashed=false"]: + fs.mv("root/item", "root/dest") + + drive, requests = mock_drive( + listing(dest, moved), + response({"parents": ["root"]}), + response(moved), + listing(other), + listing(other, moved), + response(moved), + on_request=move, + ) + fs = filesystem(drive) + fs.ls("root") + assert fs.ls("root/dest") == ["root/dest/item/"] + assert fs.info("root/dest/item")["type"] == "directory" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + +def test_delayed_lookup_caches_neither_the_old_name_nor_its_children( + mock_drive, +): def observe_new_name(request): if "name='old'" in query(request)["q"][0] and not requests: assert fs.exists("root/new") @@ -1615,14 +1895,17 @@ def observe_new_name(request): drive, requests = mock_drive( listing(folder("new", "D")), listing(folder("old", "D")), + listing(folder("child", "C")), + listing(), listing(), on_request=observe_new_name, ) fs = filesystem(drive) - assert fs.exists("root/old") + assert fs.exists("root/old/child") assert not fs.exists("root/old") assert fs.exists("root/new") - assert len(requests) == 3 + assert not fs.exists("root/new/child") + assert len(requests) == 5 @pytest.mark.parametrize("older_finishes_first", [True, False]) From 2d57699134f0e1d3e0dbf10c74401922a91e455e Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 14:23:50 -0800 Subject: [PATCH 10/17] Bound memory used by paginated Drive directory listings --- pydrive2/fs/cache.py | 35 +++++--- pydrive2/fs/spec.py | 160 ++++++++++++++++++++++------------ pydrive2/test/test_fs_unit.py | 51 +++++++++++ 3 files changed, 179 insertions(+), 67 deletions(-) diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index 2216875..d862795 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -28,17 +28,30 @@ def __init__(self, parents, name, generation, revision): self.files: set[tuple[str, str]] = set() self.complete = True - def add(self, parent, item): - # Drive v3 defines one parent per item. An ambiguous response cannot - # establish which names are complete for either parent. - if parent is None or len(item.get("parents", ())) > 1: - self.complete = False - elif item["mimeType"] == FOLDER_MIME_TYPE: - self.folders[parent].setdefault(item["name"], []).append( - item["id"] - ) - else: - self.files.add((parent, item["name"])) + def observe(self, children): + for child in children: + if child.parent is None or child.ambiguous: + self.complete = False + elif child.is_folder: + self.folders[child.parent].setdefault(child.name, []).append( + child.id + ) + + if not any(self.folders.values()): + return + + # A named lookup can find a folder under another same-name parent. + # For a full listing only names shared within one parent can collide. + for child in children: + if ( + not child.is_folder + and child.parent is not None + and ( + self.name is not None + or child.name in self.folders[child.parent] + ) + ): + self.files.add((child.parent, child.name)) class DirectoryCache: diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index cb6a453..086f9ad 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -7,6 +7,7 @@ import tempfile import threading import warnings +from collections import deque from contextlib import contextmanager from dataclasses import dataclass, field from weakref import WeakValueDictionary @@ -28,6 +29,7 @@ _LIST_FIELDS = ( f"nextPageToken,incompleteSearch,files(id,name,parents,{_INFO_FIELDS})" ) +_NAME_FIELDS = "nextPageToken,incompleteSearch,files(id,name,parents,mimeType)" _MAX_QUERY_TERMS = 50 _DRIVE_SCOPE = "https://www.googleapis.com/auth/drive" _LIST_ALL_SCOPES = { @@ -45,14 +47,46 @@ } +@dataclass(slots=True) +class _ListedChild: + id: str + parent: str | None + name: str + is_folder: bool + ambiguous: bool + size: int | None + checksum: str | None + + @classmethod + def from_drive(cls, parent, item): + size = item.get("size") + return cls( + id=item["id"], + parent=parent, + name=item["name"], + is_folder=item["mimeType"] == FOLDER_MIME_TYPE, + ambiguous=len(item.get("parents", ())) > 1, + size=int(size) if size is not None else None, + checksum=item.get("md5Checksum"), + ) + + def entry(self, name, detail=True): + if self.is_folder: + name = name.rstrip("/") + "/" + return _directory_entry(name) if detail else name + if detail: + return _regular_file_entry(name, self.size, self.checksum) + return name + + @dataclass class _PathMatch: folders: list[str] - files: list[dict] = field(default_factory=list) + files: list[_ListedChild] = field(default_factory=list) @property def ids(self): - return self.folders + [item["id"] for item in self.files] + return self.folders + [item.id for item in self.files] def _in_subtrees(path: str, roots: tuple[str, ...]) -> bool: @@ -76,18 +110,21 @@ def _directory_entry(name): return {"name": name, "type": "directory", "size": 0} -def _file_entry(name, item): - if item["mimeType"] == FOLDER_MIME_TYPE: - return _directory_entry(name.rstrip("/") + "/") - size = item.get("size") +def _regular_file_entry(name, size, checksum): return { "name": name, "type": "file", "size": int(size) if size is not None else None, - "checksum": item.get("md5Checksum"), + "checksum": checksum, } +def _file_entry(name, item): + if item["mimeType"] == FOLDER_MIME_TYPE: + return _directory_entry(name.rstrip("/") + "/") + return _regular_file_entry(name, item.get("size"), item.get("md5Checksum")) + + def _quote_query_value(value): escaped = value.replace("\\", "\\\\").replace("'", "\\'") return f"'{escaped}'" @@ -432,11 +469,11 @@ def _get_root_metadata( } return item.metadata - def _gdrive_list(self, query): + def _gdrive_list(self, query, fields=_LIST_FIELDS): param = { "q": query, "pageSize": 1000, - "fields": _LIST_FIELDS, + "fields": fields, } param.update(self._list_params) file_list = self.client.ListFile(param) @@ -447,7 +484,7 @@ def _gdrive_list(self, query): raise OSError(errno.EIO, "Incomplete Drive listing") yield from (item.metadata for item in page) - def _query_children(self, parents, names=()): + def _query_children(self, parents, names=(), *, fields=_LIST_FIELDS): parent_query = " or ".join( f"{_quote_query_value(p)} in parents" for p in parents ) @@ -455,29 +492,35 @@ def _query_children(self, parents, names=()): if names: terms = " or ".join(f"name={_quote_query_value(n)}" for n in names) query += f" and {terms}" if len(names) == 1 else f" and ({terms})" - return self._gdrive_list(query) + return self._gdrive_list(query, fields) - def _list_children(self, listing, *, require_parent=False): + def _list_children( + self, listing, *, require_parent=False, fields=_LIST_FIELDS + ): + # A later page or batch may report a new location for the same ID. + rows = {} names = (listing.name,) if listing.name is not None else () - # Drive can return the same ID on multiple pages or in different - # batches. Wait for the last attributable row before constructing paths. - rows: dict[str, tuple[str | None, dict]] = {} for batch in chunks(_MAX_QUERY_TERMS, listing.folders): - batch_ids = set(batch) + batch_ids = {parent: parent for parent in batch} unplaced = {} - for item in self._query_children(batch, names): + for item in self._query_children(batch, names, fields=fields): if names and item["name"] != listing.name: continue # Drive matches case-insensitively. file_id = item["id"] - parent = next( - (p for p in item.get("parents", ()) if p in batch_ids), - None, - ) - if parent is None: - if len(batch) == 1: - parent = batch[0] - elif ( - self.root in {"root", "appDataFolder"} + if len(batch) == 1: + parent = batch[0] + else: + parent = next( + ( + batch_ids[p] + for p in item.get("parents", ()) + if p in batch_ids + ), + None, + ) + if ( + parent is None + and self.root in {"root", "appDataFolder"} and self.root in batch_ids and item.get("parents") ): @@ -487,15 +530,16 @@ def _list_children(self, listing, *, require_parent=False): unplaced[file_id] = item["name"] continue unplaced.pop(file_id, None) - rows[file_id] = parent, item + rows[file_id] = _ListedChild.from_drive(parent, item) - if unplaced and not self._locate_children(batch, unplaced, rows): - # An item can move or disappear before the probes finish. - listing.complete = False + if unplaced: + self._locate_children(batch, unplaced, rows) + if unplaced: + # An item can move or disappear before the probes finish. + listing.complete = False - for parent, item in rows.values(): - listing.add(parent, item) - yield parent, item + listing.observe(rows.values()) + return deque(rows.values()) def _locate_children(self, parents, missing, rows): """Place rows with hidden parent IDs using Drive's parent query.""" @@ -512,12 +556,11 @@ def _locate_children(self, parents, missing, rows): if size > 1: parents = probe break - rows[item_id] = probe[0], item del missing[item_id] + rows[item_id] = _ListedChild.from_drive(probe[0], item) # For one remaining ID, narrow the search by halves. Only a # single-parent query can confirm where to place the item. size = (len(parents) + 1) // 2 if len(missing) == 1 else 1 - return not missing def _match_child( self, @@ -544,9 +587,9 @@ def _match_child( with self._dirs.listing( generation, parent_ids, name=name ) as listing: - for _, item in self._list_children(listing): - if item["mimeType"] == FOLDER_MIME_TYPE: - match.folders.append(item["id"]) + for item in self._list_children(listing): + if item.is_folder: + match.folders.append(item.id) else: match.files.append(item) if ( @@ -758,40 +801,41 @@ def ls(self, path, detail=False): ) root_path = posixpath.join(bucket, base) + fields = _LIST_FIELDS if detail else _NAME_FIELDS contents = [] with self._dirs.listing(generation, dir_ids) as listing: - for _, item in self._list_children(listing): - contents.append( - _file_entry(posixpath.join(root_path, item["name"]), item) - ) - if detail: - return contents - return [entry["name"] for entry in contents] + children = self._list_children(listing, fields=fields) + # Release each row as its public entry takes its place in memory. + while children: + child = children.popleft() + name = posixpath.join(root_path, child.name) + contents.append(child.entry(name, detail)) + return contents def _walk_folders(self, base, start_ids, generation, maxdepth): frontier = dict.fromkeys(start_ids, base) to_list = self._dirs.warm_parents(frontier, maxdepth, generation) depth = 0 - children: dict[str, list[dict]] = {} + children: dict[str, list[_ListedChild]] = {} visited: set[str] = set() while frontier: depth += 1 if to_list: with self._dirs.listing(generation, to_list) as listing: children.update((parent, []) for parent in to_list) - for parent, item in self._list_children( + for item in self._list_children( listing, require_parent=True ): - children[parent].append(item) + children[item.parent].append(item) generation = listing.generation visited.update(frontier) following = {} for parent, parent_path in frontier.items(): for item in children.pop(parent): - path = posixpath.join(parent_path, item["name"]) - if item["mimeType"] == FOLDER_MIME_TYPE: - item_id = item["id"] + path = posixpath.join(parent_path, item.name) + if item.is_folder: + item_id = item.id if item_id not in visited: following[item_id] = path yield path, item @@ -824,7 +868,7 @@ def find( base, generation, mount, folders_only=True ) file = ( - min(match.files, key=lambda item: item["id"], default=None) + min(match.files, key=lambda item: item.id, default=None) if not match.folders else None ) @@ -843,9 +887,13 @@ def find( if metadata.get("trashed"): return {} if detail else [] if metadata["mimeType"] != FOLDER_MIME_TYPE: - file = metadata + return ( + {start: _file_entry(start, metadata)} + if detail + else [start] + ) if file is not None: - return {start: _file_entry(start, file)} if detail else [start] + return {start: file.entry(start)} if detail else [start] if not match.folders: return {} if detail else [] @@ -855,11 +903,11 @@ def find( ): check_empty_root = False name = posixpath.join(root, relative) - if item["mimeType"] == FOLDER_MIME_TYPE: + if item.is_folder: if withdirs: contents.append(_directory_entry(name)) else: - contents.append(_file_entry(name, item)) + contents.append(item.entry(name)) if check_empty_root: try: diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index b8baa3f..2369082 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -495,6 +495,57 @@ def test_ls_stops_before_the_next_batch_if_a_page_is_incomplete(mock_drive): assert query(second)["pageToken"] == ["second"] +@pytest.mark.parametrize( + ("detail", "fields", "expected"), + [ + (False, "id,name,parents,mimeType", ["root/final", "root/final/"]), + ( + True, + "id,name,parents,mimeType,size,md5Checksum", + [ + { + "name": "root/final", + "type": "file", + "size": 2, + "checksum": "new", + }, + {"name": "root/final/", "type": "directory", "size": 0}, + ], + ), + ], +) +def test_ls_requests_only_needed_fields_and_uses_the_latest_page( + mock_drive, detail, fields, expected +): + file = { + "id": "A", + "name": "initial", + "mimeType": "text/plain", + "size": "1", + "md5Checksum": "old", + } + updated = dict(file, name="final", size="2", md5Checksum="new") + directory = folder("final", "Z") + drive, requests = mock_drive( + response({"files": [file, directory], "nextPageToken": "next"}), + listing(updated), + listing(updated, directory), + ({"status": "200", "content-length": "1"}, b"x"), + ) + fs = filesystem(drive) + assert fs.ls("root", detail=detail) == expected + first, second = requests + assert ( + query(first)["fields"] + == query(second)["fields"] + == [f"nextPageToken,incompleteSearch,files({fields})"] + ) + assert query(second)["pageToken"] == ["next"] + with fs.open("root/final", "rb") as stream: + assert stream.read() == b"x" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + def test_ls_deduplicates_a_file_shared_across_parent_batches(mock_drive): parents = [f"parent-{i}" for i in range(51)] shared = { From 741751e71e64ad892363fdb8fa900d692d3710c5 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 14:41:46 -0800 Subject: [PATCH 11/17] Recheck moved folders by destination ID and cover review findings --- pydrive2/fs/cache.py | 18 ++--- pydrive2/fs/spec.py | 16 +++- pydrive2/test/test_fs_unit.py | 142 ++++++++++++++++++++++++++-------- 3 files changed, 130 insertions(+), 46 deletions(-) diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index d862795..7378e72 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -214,15 +214,20 @@ def invalidate(self, path): for parent in parents: self._drop_subtrees(self._remove_name(parent, name)) - def removed(self, item_id, paths): + def removed(self, item_id, paths, *, destination=None): """Discard this ID. Recheck affected names without evicting siblings.""" with self.lock: self.generation += 1 if item_id in self.parents: self._unlink(item_id) self._drop_subtrees([item_id]) - for path in paths: - parents, name = self._parents_of_path(path) + groups = [self._parents_of_path(path) for path in paths] + if destination is not None: + # A move can resolve its destination by ID even when part of + # the path could not be cached. + parent, name = destination + groups.append(((parent,), name)) + for parents, name in groups: for parent in parents: if name in self.children.get(parent, {}): self.incomplete.add((parent, name)) @@ -335,13 +340,6 @@ def _observe(self, listing, name): before = previous.get(key) ids = tuple(names.get(key, ())) edge = (parent, key) - if ( - before - and ids - and before != ids - and set(before) == set(ids) - ): - ids = before if before and before != ids: retired.extend(set(before).difference(ids)) # Remember an empty sibling only if this exact name matched diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 086f9ad..e53c1d3 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -410,7 +410,9 @@ def invalidate_cache(self, path=None): self._root_metadata = {} self._dirs.invalidate(base) - def _invalidate_folder(self, item_id, *paths, known_folder=False): + def _invalidate_folder( + self, item_id, *paths, known_folder=False, destination=None + ): with self._cache_lock: if item_id == self.root: self.invalidate_cache(self.root) @@ -418,7 +420,9 @@ def _invalidate_folder(self, item_id, *paths, known_folder=False): for path in paths: super().invalidate_cache(path) self._dirs.removed( - item_id, [self._split_mounted_path(p)[1] for p in paths] + item_id, + [self._split_mounted_path(p)[1] for p in paths], + destination=destination, ) @property @@ -1011,7 +1015,13 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): super().invalidate_cache(destination) else: self._invalidate_folder( - file1_id, path1, destination, known_folder=True + file1_id, + path1, + destination, + known_folder=True, + destination=(destination_parent, dst_name) + if destination_parent is not None + else None, ) else: _, parent_path = self._split_mounted_path(dst_parent) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 2369082..3022e57 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -11,6 +11,7 @@ from google.oauth2 import service_account from google.oauth2.credentials import Credentials from googleapiclient.http import DEFAULT_CHUNK_SIZE +from httplib2 import Response from pydrive2.fs import GDriveFileSystem from pydrive2.fs.spec import FOLDER_MIME_TYPE @@ -800,6 +801,27 @@ def test_fresh_listing_forgets_only_the_disappeared_folder( assert "name='gone'" in query(requests[-1])["q"][0] +def test_repeated_stat_reuses_the_folder_after_a_same_name_file_is_removed( + mock_drive, +): + file = {"id": "A", "name": "item", "mimeType": "text/plain"} + directory = folder("item", "Z") + drive, requests = mock_drive( + listing(file, directory), + response({}), + listing(directory), + response(directory), + response(directory), + ) + fs = filesystem(drive) + fs.rm_file("root/item") + assert fs.info("root/item")["type"] == "directory" + before = len(requests) + assert fs.info("root/item")["type"] == "directory" + (metadata,) = requests[before:] + assert urlsplit(metadata[0]).path.endswith("/files/Z") + + def test_local_rename_preserves_cached_child(mock_drive): drive, requests = mock_drive( listing(folder("old", "D")), @@ -972,8 +994,6 @@ def test_failed_later_page_does_not_cache_partial_duplicate_matches( def test_find_bounds_requests_to_locate_one_item_without_parents( mock_drive, mocker, actual_parent, max_probes ): - from httplib2 import Response - folders = [folder(f"dir{i}", f"P{i}") for i in range(50)] note = {"id": "N", "name": "note", "mimeType": "text/plain"} drive, _ = mock_drive() @@ -1019,6 +1039,23 @@ def test_find_places_items_without_parents_by_name_and_id(mock_drive): ] +def test_find_places_two_items_without_parents_in_different_folders( + mock_drive, +): + one = {"id": "1", "name": "one", "mimeType": "text/plain"} + two = dict(one, id="2", name="two") + drive, requests = mock_drive( + listing(*(folder(name, name.upper()) for name in "abcd")), + listing(one, two), + listing(), + listing(one), + listing(), + listing(two), + ) + assert filesystem(drive).find("root") == ["root/b/one", "root/d/two"] + assert len(requests) == 6 + + def test_find_bounds_the_query_for_many_items_without_parents(mock_drive): items = [ {"id": str(i), "name": f"file-{i}", "mimeType": "text/plain"} @@ -1217,6 +1254,54 @@ def test_directory_mutation_evicts_descendants_only(mock_drive, operation): assert len(requests) == before +def test_move_rechecks_the_physical_destination_when_its_path_was_uncached( + mock_drive, +): + duplicate_parents = listing(folder("dup", "P"), folder("dup", "R")) + q, t = folder("q", "Q"), folder("t", "T") + cached, arriving = folder("x", "X"), folder("x", "N") + # Drive returns q below one of the two dup folders without exposing which + # one. The move can use Q and T even while q's path cannot be cached. + hidden_parent = listing(q) + move_t = [ + hidden_parent, + hidden_parent, + response({"parents": ["root"]}), + response(t), + ] + move_x = [ + hidden_parent, + listing(t), + hidden_parent, + listing(arriving), + hidden_parent, + listing(t), + response({"parents": ["Q"]}), + response(arriving), + ] + drive, requests = mock_drive( + listing(t), + listing(cached), + duplicate_parents, + *move_t, + *move_x, + listing(dict(q, parents=["P"])), + listing(t), + listing(cached, arriving), + response({}), + ) + fs = filesystem(drive) + assert fs.exists("root/t/x") + assert fs.exists("root/dup") + fs.mv("root/t", "root/dup/q") + fs.mv("root/dup/q/x", "root/dup/q/t") + fs.rm_file("root/dup/q/t/x") + assert urlsplit(requests[-1][0]).path.endswith("/files/N") + assert query(requests[-2])["q"] == [ + "('T' in parents) and trashed=false and name='x'" + ] + + def test_move_into_a_folder_that_shares_its_name_with_a_file(mock_drive): dest = folder("dest", "Z") file = {"id": "A", "name": "dest", "mimeType": "text/plain"} @@ -1771,16 +1856,14 @@ def create(): assert urlsplit(requests[-1][0]).path.endswith("/files/A") -def finish_request_during_read( - mock_drive, responses, should_pause, first, second, *read_responses +def overlap_requests( + mock_drive, *, first, first_responses, pause_on, second, second_responses ): - """Start the second read while the first operation is waiting on Drive. - Return its older snapshot only after the first operation finishes. - """ + """Finish the first operation while the second awaits its Drive response.""" started, release = Event(), Event() def pause(request): - if should_pause(request): + if pause_on(request): started.set() assert release.wait(5) @@ -1788,8 +1871,8 @@ def finish(request): release.set() pending.result(timeout=5) - writer, _ = mock_drive(*responses, on_request=pause) - reader, requests = mock_drive(*read_responses, on_request=finish) + writer, _ = mock_drive(*first_responses, on_request=pause) + reader, requests = mock_drive(*second_responses, on_request=finish) write_http = writer.auth.thread_local.http def run(): @@ -1818,17 +1901,19 @@ def retire(fs): def list_children(fs): assert fs.ls("root/old") == ["root/old/child/"] - fs, _ = finish_request_during_read( + fs, _ = overlap_requests( mock_drive, - [listing(folder("old", "D")), listing()], - lambda req: ( + first=retire, + first_responses=[listing(folder("old", "D")), listing()], + pause_on=lambda req: ( query(req).get("q") == ["('root' in parents) and trashed=false"] ), - retire, - list_children, - listing(folder("child", "C")), - listing(folder("new", "D")), - listing(), + second=list_children, + second_responses=[ + listing(folder("child", "C")), + listing(folder("new", "D")), + listing(), + ], ) assert fs.exists("root/new") assert not fs.exists("root/new/child") @@ -1862,14 +1947,13 @@ def test_listing_started_during_create_cannot_evict_the_new_folder(mock_drive): def read(fs): assert fs.ls("root") == [] - fs, requests = finish_request_during_read( + fs, requests = overlap_requests( mock_drive, - [listing(), response(folder("item", "A"))], - lambda req: req[1] == "POST", - lambda fs: fs.mkdir("root/item"), - read, - listing(), - listing(folder("item", "A")), + first=lambda fs: fs.mkdir("root/item"), + first_responses=[listing(), response(folder("item", "A"))], + pause_on=lambda req: req[1] == "POST", + second=read, + second_responses=[listing(), listing(folder("item", "A"))], ) before = len(requests) assert fs.exists("root/item") @@ -1882,8 +1966,6 @@ def test_create_rechecks_a_sibling_discovered_during_the_folder_post( sibling, created = folder("item", "Z"), folder("item", "A") def see_sibling(request): - if request[1] == "GET" and "q" not in query(request): - assert urlsplit(request[0]).path.endswith("/files/A") if request[1] == "POST": assert fs.ls("root") == ["root/item/"] @@ -1911,12 +1993,6 @@ def test_listing_started_before_move_cannot_hide_the_arriving_folder( ) def move(request): - if ( - request[1] == "GET" - and query(request).get("fields") != ["parents"] - and "q" not in query(request) - ): - assert urlsplit(request[0]).path.endswith("/files/A") if query(request).get("q") == ["('P' in parents) and trashed=false"]: fs.mv("root/item", "root/dest") From c89809bf7167aeeaab7c789b66f1f2f0cbc859c8 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 29 Nov 2026 09:31:45 -0800 Subject: [PATCH 12/17] Share directory resolution and keep names-only scans lightweight --- docs/fsspec.rst | 5 + pydrive2/fs/cache.py | 135 ++++++------ pydrive2/fs/spec.py | 381 ++++++++++++++-------------------- pydrive2/test/test_fs_unit.py | 45 ++++ 4 files changed, 271 insertions(+), 295 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index e6ffcff..76522d7 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -74,6 +74,11 @@ client moves, trashes, or deletes a folder, call The next lookup checks Drive for all folders with that name, including any same-name folder that still exists. +The cache retains folder IDs between calls. For a DVC remote with 256 hash +prefixes, adding files under those prefixes does not grow the directory +index. Each ``ls()`` or ``find()`` call builds its result in memory, so its +peak memory use depends on the number of entries it returns. + Drive queries for directory entries exclude trashed items. For a bare file ID, ``exists()`` returns false and ``info()`` raises ``FileNotFoundError`` when the item is in the trash. Opening or downloading by ID requests the diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index 7378e72..5559615 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -147,13 +147,14 @@ def _remove_name(self, parent, name): del self.children[parent] return ids - def _unlink(self, item_id): - parent, name, _ = self.parents.pop(item_id) + def _unlink(self, parent, name, leaving): ids = self.children[parent][name] - if len(ids) == 1: + if len(ids) == len(leaving): self._remove_name(parent, name) else: - self.children[parent][name] = tuple(i for i in ids if i != item_id) + self.children[parent][name] = tuple( + i for i in ids if i not in leaving + ) def _drop_subtrees(self, roots): pending = list(roots) @@ -214,44 +215,42 @@ def invalidate(self, path): for parent in parents: self._drop_subtrees(self._remove_name(parent, name)) - def removed(self, item_id, paths, *, destination=None): - """Discard this ID. Recheck affected names without evicting siblings.""" + def removed(self, item_id, path): + """Discard this folder and recheck any same-name siblings.""" with self.lock: self.generation += 1 - if item_id in self.parents: - self._unlink(item_id) + if old := self.parents.get(item_id): + self._unlink(old.parent, old.name, (item_id,)) self._drop_subtrees([item_id]) - groups = [self._parents_of_path(path) for path in paths] - if destination is not None: - # A move can resolve its destination by ID even when part of - # the path could not be cached. - parent, name = destination - groups.append(((parent,), name)) - for parents, name in groups: - for parent in parents: - if name in self.children.get(parent, {}): - self.incomplete.add((parent, name)) - - def moved(self, generation, item_id, parent, name): - """Relink a known folder while retaining all edges below its ID.""" + self._recheck_path(path) + + def _recheck_path(self, path): + parents, name = self._parents_of_path(path) + for parent in parents: + if name in self.children.get(parent, {}): + self.incomplete.add((parent, name)) + + def moved(self, generation, item_id, parent, source, destination): + """Relink the folder by ID, keeping its descendants warm.""" + name = destination.rpartition("/")[2] with self.lock: - if generation != self.generation or item_id not in self.parents: - return False - old_parent = self.parents[item_id].parent - # A rename leaves the physical parent unchanged. - if parent is None: - parent = old_parent - self._unlink(item_id) - edge = (parent, name) + old = self.parents.get(item_id) + if generation != self.generation or old is None: + self.removed(item_id, source) + self._recheck_path(destination) + # A caller can resolve a physical parent through an uncached path. + if name in self.children.get(parent, {}): + self.incomplete.add((parent, name)) + return + self._unlink(old.parent, old.name, (item_id,)) + parent = old.parent if parent is None else parent names = self.children.setdefault(parent, {}) names[name] = (*names.get(name, ()), item_id) self.parents[item_id] = FolderLocation( parent, name, next(self._revisions) ) - # The destination can already contain same-name files or folders. - self.incomplete.add(edge) + self.incomplete.add((parent, name)) self.generation += 1 - return True def created(self, listing, parent, item_id): # The empty name lookup and the folder POST share this listing. A @@ -312,50 +311,44 @@ def listing(self, generation, parents, *, name=None): del self._pending[listing] def _observe(self, listing, name): - groups = listing.folders - # Parents resolved by the caller can disappear while Drive is listing. - # Publishing children under detached IDs would create unreachable edges. - if any(p != self.root and p not in self.parents for p in groups): - groups = { - p: names - for p, names in groups.items() - if p == self.root or p in self.parents - } - if not groups: - listing.generation = None - return - if not self._relink(groups, listing.revision): + # Only publish under parents that are still attached to this root. + groups = { + parent: names + for parent, names in listing.folders.items() + if parent == self.root or parent in self.parents + } + if not groups or not self._relink(groups, listing.revision): listing.generation = None return - retired: list[str] = [] + + retired = [] has_folder = any(groups.values()) for parent, names in groups.items(): previous = self.children.get(parent, {}) - keys = ( - (name,) - if name is not None - else dict.fromkeys((*names, *previous)) - ) - for key in keys: + if name is None: + for missing in previous.keys() - names.keys(): + retired.extend(self._remove_name(parent, missing)) + elif has_folder: + # An empty sibling matters only when another parent has this folder. + names.setdefault(name, []) + else: + retired.extend(self._remove_name(parent, name)) + + for key, matches in names.items(): + ids = tuple(matches) before = previous.get(key) - ids = tuple(names.get(key, ())) - edge = (parent, key) if before and before != ids: retired.extend(set(before).difference(ids)) - # Remember an empty sibling only if this exact name matched - # a folder under another queried parent. Never cache misses alone. - if ids or (name is not None and has_folder): - self.children.setdefault(parent, {})[key] = ids - location = FolderLocation(parent, key, listing.revision) - for item_id in ids: - self.parents[item_id] = location - self.incomplete.discard(edge) - if edge in listing.files: - self.file_collisions.add(edge) - else: - self.file_collisions.discard(edge) + self.children.setdefault(parent, {})[key] = ids + location = FolderLocation(parent, key, listing.revision) + for item_id in ids: + self.parents[item_id] = location + edge = (parent, key) + self.incomplete.discard(edge) + if edge in listing.files: + self.file_collisions.add(edge) else: - self._remove_name(parent, key) + self.file_collisions.discard(edge) self._drop_subtrees(retired) # Retired IDs have no reverse entry left to check against an older # result. Only reads started before this observation need that barrier. @@ -376,11 +369,5 @@ def _relink(self, groups, revision): return False moved[old.parent, old.name].add(item_id) for (parent, name), leaving in moved.items(): - remaining = tuple( - i for i in self.children[parent][name] if i not in leaving - ) - if remaining: - self.children[parent][name] = remaining - else: - self._remove_name(parent, name) + self._unlink(parent, name, leaving) return True diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index e53c1d3..3d11e60 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -8,7 +8,7 @@ import threading import warnings from collections import deque -from contextlib import contextmanager +from contextlib import contextmanager, nullcontext from dataclasses import dataclass, field from weakref import WeakValueDictionary @@ -71,12 +71,11 @@ def from_drive(cls, parent, item): ) def entry(self, name, detail=True): + if not detail: + return name if self.is_folder: - name = name.rstrip("/") + "/" - return _directory_entry(name) if detail else name - if detail: - return _regular_file_entry(name, self.size, self.checksum) - return name + return _directory_entry(name) + return _regular_file_entry(name, self.size, self.checksum) @dataclass @@ -84,18 +83,14 @@ class _PathMatch: folders: list[str] files: list[_ListedChild] = field(default_factory=list) + def __bool__(self): + return bool(self.folders or self.files) + @property def ids(self): return self.folders + [item.id for item in self.files] -def _in_subtrees(path: str, roots: tuple[str, ...]) -> bool: - return any( - not root or path == root or path.startswith(root + "/") - for root in roots - ) - - def _select_item_id(path, ids): if ids: return min(ids) @@ -319,7 +314,6 @@ def __init__( self.path = path self.root, self.base = self.split_path(path) self._dirs = DirectoryCache(self.root) - self._cache_lock = self._dirs.lock self._mount_lock = threading.RLock() self._root_lock = threading.RLock() self._root_metadata: dict = {} @@ -394,7 +388,7 @@ def _resolve_mount(self): with self._mount_lock: generation = self._dirs.generation mount, generation = self._resolve_path(self.base, generation) - if not mount.ids: + if not mount: raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), @@ -405,25 +399,19 @@ def _resolve_mount(self): def invalidate_cache(self, path=None): base = self._split_mounted_path(path)[1] if path else "" super().invalidate_cache(path) - with self._cache_lock: + with self._dirs.lock: if not base: self._root_metadata = {} self._dirs.invalidate(base) - def _invalidate_folder( - self, item_id, *paths, known_folder=False, destination=None - ): - with self._cache_lock: + def _invalidate_folder(self, item_id, path, *, known_folder): + with self._dirs.lock: if item_id == self.root: self.invalidate_cache(self.root) elif known_folder or item_id in self._dirs.parents: - for path in paths: - super().invalidate_cache(path) - self._dirs.removed( - item_id, - [self._split_mounted_path(p)[1] for p in paths], - destination=destination, - ) + super().invalidate_cache(path) + _, base = self._split_mounted_path(path) + self._dirs.removed(item_id, base) @property def _list_params(self): @@ -457,11 +445,11 @@ def _get_root_metadata( with _translate_not_found(self.root): item.FetchMetadata(f"{fields},spaces") except FileNotFoundError: - with self._cache_lock: + with self._dirs.lock: if self._root_metadata is cached: self.invalidate_cache(self.root) raise - with self._cache_lock: + with self._dirs.lock: if self._root_metadata is cached: if item.get("trashed"): self.invalidate_cache(self.root) @@ -473,21 +461,6 @@ def _get_root_metadata( } return item.metadata - def _gdrive_list(self, query, fields=_LIST_FIELDS): - param = { - "q": query, - "pageSize": 1000, - "fields": fields, - } - param.update(self._list_params) - file_list = self.client.ListFile(param) - - get_list = _gdrive_retry(lambda: next(file_list, None)) - for page in iter(get_list, None): - if file_list.metadata.get("incompleteSearch"): - raise OSError(errno.EIO, "Incomplete Drive listing") - yield from (item.metadata for item in page) - def _query_children(self, parents, names=(), *, fields=_LIST_FIELDS): parent_query = " or ".join( f"{_quote_query_value(p)} in parents" for p in parents @@ -496,7 +469,14 @@ def _query_children(self, parents, names=(), *, fields=_LIST_FIELDS): if names: terms = " or ".join(f"name={_quote_query_value(n)}" for n in names) query += f" and {terms}" if len(names) == 1 else f" and ({terms})" - return self._gdrive_list(query, fields) + pages = self.client.ListFile( + dict(self._list_params, q=query, pageSize=1000, fields=fields) + ) + get_page = _gdrive_retry(lambda: next(pages, None)) + for page in iter(get_page, None): + if pages.metadata.get("incompleteSearch"): + raise OSError(errno.EIO, "Incomplete Drive listing") + yield from (item.metadata for item in page) def _list_children( self, listing, *, require_parent=False, fields=_LIST_FIELDS @@ -506,6 +486,12 @@ def _list_children( names = (listing.name,) if listing.name is not None else () for batch in chunks(_MAX_QUERY_TERMS, listing.folders): batch_ids = {parent: parent for parent in batch} + # Drive may report the canonical ID instead of the requested root alias. + root_alias = ( + batch_ids.get(self.root) + if self.root in {"root", "appDataFolder"} + else None + ) unplaced = {} for item in self._query_children(batch, names, fields=fields): if names and item["name"] != listing.name: @@ -514,22 +500,11 @@ def _list_children( if len(batch) == 1: parent = batch[0] else: + parents = item.get("parents", ()) parent = next( - ( - batch_ids[p] - for p in item.get("parents", ()) - if p in batch_ids - ), - None, + (batch_ids[p] for p in parents if p in batch_ids), + root_alias if parents else None, ) - if ( - parent is None - and self.root in {"root", "appDataFolder"} - and self.root in batch_ids - and item.get("parents") - ): - # Drive can return the canonical ID of the root alias. - parent = self.root if parent is None and require_parent: unplaced[file_id] = item["name"] continue @@ -537,7 +512,7 @@ def _list_children( rows[file_id] = _ListedChild.from_drive(parent, item) if unplaced: - self._locate_children(batch, unplaced, rows) + self._locate_children(batch, unplaced, rows, fields) if unplaced: # An item can move or disappear before the probes finish. listing.complete = False @@ -545,7 +520,7 @@ def _list_children( listing.observe(rows.values()) return deque(rows.values()) - def _locate_children(self, parents, missing, rows): + def _locate_children(self, parents, missing, rows, fields): """Place rows with hidden parent IDs using Drive's parent query.""" size = 1 while parents and missing: @@ -553,7 +528,7 @@ def _locate_children(self, parents, missing, rows): names = dict.fromkeys(missing.values()) if len(names) > _MAX_QUERY_TERMS: names.clear() - for item in self._query_children(probe, names): + for item in self._query_children(probe, names, fields=fields): item_id = item["id"] if item_id not in missing: continue @@ -566,71 +541,71 @@ def _locate_children(self, parents, missing, rows): # single-parent query can confirm where to place the item. size = (len(parents) + 1) // 2 if len(missing) == 1 else 1 + def _creation_lock(self, parent_id, name): + key = (parent_id, name) + with self._dirs.lock: + lock = self._creation_locks.get(key) + if lock is None: + lock = self._creation_locks[key] = threading.RLock() + return lock + def _match_child( self, - generation, - parent_ids, + parents, path, name, - mount=None, + generation, + mount, *, - folders_only=False, - create_in=None, - exist_ok=True, + folders_only, + create=False, ): - match = mount if path == self.base else None - if match is None: + if path == self.base and mount is not None: + return mount, generation, False + + # A creator must check the cache and Drive under the same name lock. + parent = min(parents) if create else None + lock = self._creation_lock(parent, name) if create else nullcontext() + with lock: folders = self._dirs.lookup( - parent_ids, name, generation, folders_only=folders_only + parents, name, generation, folders_only=folders_only ) if folders: - match = _PathMatch(folders) - created = False - if match is None: + return _PathMatch(folders), generation, False + match = _PathMatch([]) - with self._dirs.listing( - generation, parent_ids, name=name - ) as listing: + with self._dirs.listing(generation, parents, name=name) as listing: for item in self._list_children(listing): if item.is_folder: match.folders.append(item.id) else: match.files.append(item) - if ( - create_in is not None - and not match.folders - and not match.files - ): - item = self._gdrive_create_dir(create_in, name) - self._dirs.created(listing, create_in, item["id"]) - match.folders.append(item["id"]) - created = True - generation = listing.generation - if not exist_ok and not created: - raise FileExistsError(posixpath.join(self.root, path)) - return match, generation - - def _resolve_prefix( - self, path, generation, mount=None, *, folders_only=False + created = create and not match + if created: + item_id = self._gdrive_create_dir(parent, name)["id"] + self._dirs.created(listing, parent, item_id) + match.folders.append(item_id) + return match, listing.generation, created + + def _walk_path( + self, path, generation, mount, *, folders_only, create=False ): - """Return the deepest existing component, its matches and lookup generation.""" + """Return the last component reached and its Drive matches.""" parent, folders, remaining = self._dirs.prefix( path, generation, folders_only=folders_only ) match = _PathMatch(folders) for name in remaining: - child = posixpath.join(parent, name) - found, generation = self._match_child( - generation, + parent = posixpath.join(parent, name) + match, generation, _ = self._match_child( match.folders, - child, + parent, name, + generation, mount, - folders_only=folders_only or child != path, + folders_only=folders_only or parent != path, + create=create, ) - if not found.folders and not found.files: - break - parent, match = child, found if not match.folders: break return parent, match, generation @@ -638,46 +613,52 @@ def _resolve_prefix( def _resolve_path( self, path, generation, mount=None, *, folders_only=False ): - prefix, match, generation = self._resolve_prefix( + last, match, generation = self._walk_path( path, generation, mount, folders_only=folders_only ) - return (match if prefix == path else _PathMatch([])), generation + return (match if last == path else _PathMatch([])), generation - def _ensure_dirs(self, path, generation, mount=None): - parent, folders, remaining = self._dirs.prefix( - path, generation, folders_only=True + def _resolve_directory( + self, path, generation=None, mount=None, *, create=False, fresh=False + ): + last, match, generation = self._walk_path( + path, + None if fresh else generation, + mount, + folders_only=True, + create=create, ) - for name in remaining: - parent = posixpath.join(parent, name) - match, generation = self._get_or_create_child( - generation, folders, parent, name, mount + if not match.folders: + blocked = posixpath.join(self.root, last) + if fresh: + self.invalidate_cache(blocked) + if match: + raise NotADirectoryError( + errno.ENOTDIR, os.strerror(errno.ENOTDIR), blocked + ) + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), blocked ) - if not match.folders: - raise NotADirectoryError(posixpath.join(self.root, parent)) - folders = match.folders - return folders, generation + return match, generation def _lookup_path(self, path, *, folders_only=False): if not path: - with self._cache_lock: - return _PathMatch([self.root]), self._dirs.generation + return _PathMatch([self.root]), self._dirs.generation generation, mount = self._resolve_mount() return self._resolve_path( path, generation, mount, folders_only=folders_only ) - def _path_to_item_ids(self, path, create=False): - if create and path: - generation, mount = self._resolve_mount() - folders, _ = self._ensure_dirs(path, generation, mount) - return folders - match, _ = self._lookup_path(path) - return match.ids - def _get_item_id(self, path, create=False): _, base = self._split_mounted_path(path) - ids = self._path_to_item_ids(base, create=create) - return _select_item_id(path, ids) + if create and base: + generation, mount = self._resolve_mount() + match, _ = self._resolve_directory( + base, generation, mount, create=True + ) + return _select_item_id(path, match.folders) + match, _ = self._lookup_path(base) + return _select_item_id(path, match.ids) @_gdrive_retry def _gdrive_create_dir(self, parent_id, name): @@ -691,28 +672,6 @@ def _gdrive_create_dir(self, parent_id, name): item.Upload() return item - def _get_or_create_child( - self, generation, parents, path, name, mount=None, *, exist_ok=True - ): - parent_id = min(parents) - key = (parent_id, name) - with self._cache_lock: - lock = self._creation_locks.get(key) - if lock is None: - lock = self._creation_locks[key] = threading.RLock() - with lock: - # Check Drive under the same name lock as the create on a cache miss. - return self._match_child( - generation, - parents, - path, - name, - mount, - folders_only=True, - create_in=parent_id, - exist_ok=exist_ok, - ) - def mkdir(self, path, create_parents=True, **kwargs): self._mkdir(path, create_parents, exist_ok=False) @@ -741,21 +700,19 @@ def _mkdir(self, path, create_parents, exist_ok): generation, mount = self._resolve_mount() parent, name = posixpath.split(base) - if create_parents: - folders, generation = self._ensure_dirs(parent, generation, mount) - else: - prefix, match, generation = self._resolve_prefix( - parent, generation, mount, folders_only=True - ) - if not match.folders: - raise NotADirectoryError(posixpath.join(root, prefix)) - if prefix != parent: - raise FileNotFoundError(posixpath.join(root, parent)) - folders = match.folders - leaf, _ = self._get_or_create_child( - generation, folders, base, name, mount, exist_ok=exist_ok + parent_match, generation = self._resolve_directory( + parent, generation, mount, create=create_parents ) - if not leaf.folders: + leaf, _, created = self._match_child( + parent_match.folders, + base, + name, + generation, + mount, + folders_only=True, + create=True, + ) + if not leaf.folders or (not exist_ok and not created): raise FileExistsError(path) def exists(self, path): @@ -813,11 +770,13 @@ def ls(self, path, detail=False): while children: child = children.popleft() name = posixpath.join(root_path, child.name) + if child.is_folder: + name = name.rstrip("/") + "/" contents.append(child.entry(name, detail)) return contents - def _walk_folders(self, base, start_ids, generation, maxdepth): - frontier = dict.fromkeys(start_ids, base) + def _walk_folders(self, start, start_ids, generation, maxdepth, fields): + frontier = dict.fromkeys(start_ids, start) to_list = self._dirs.warm_parents(frontier, maxdepth, generation) depth = 0 children: dict[str, list[_ListedChild]] = {} @@ -828,7 +787,7 @@ def _walk_folders(self, base, start_ids, generation, maxdepth): with self._dirs.listing(generation, to_list) as listing: children.update((parent, []) for parent in to_list) for item in self._list_children( - listing, require_parent=True + listing, require_parent=True, fields=fields ): children[item.parent].append(item) generation = listing.generation @@ -836,7 +795,11 @@ def _walk_folders(self, base, start_ids, generation, maxdepth): visited.update(frontier) following = {} for parent, parent_path in frontier.items(): - for item in children.pop(parent): + entries = children.pop(parent) + # Release each row in Drive order as its result is built. + entries.reverse() + while entries: + item = entries.pop() path = posixpath.join(parent_path, item.name) if item.is_folder: item_id = item.id @@ -871,11 +834,6 @@ def find( match, generation = self._resolve_path( base, generation, mount, folders_only=True ) - file = ( - min(match.files, key=lambda item: item.id, default=None) - if not match.folders - else None - ) start = posixpath.join(root, base).rstrip("/") check_empty_root = False if not base and root not in {"root", "appDataFolder"}: @@ -896,22 +854,22 @@ def find( if detail else [start] ) - if file is not None: - return {start: file.entry(start)} if detail else [start] if not match.folders: + if match.files: + file = min(match.files, key=lambda item: item.id) + return {start: file.entry(start)} if detail else [start] return {} if detail else [] contents = [] - for relative, item in self._walk_folders( - base, match.folders, generation, maxdepth + if withdirs: + contents.append(_directory_entry(start) if detail else start) + fields = _LIST_FIELDS if detail else _NAME_FIELDS + for name, item in self._walk_folders( + start, match.folders, generation, maxdepth, fields ): check_empty_root = False - name = posixpath.join(root, relative) - if item.is_folder: - if withdirs: - contents.append(_directory_entry(name)) - else: - contents.append(item.entry(name)) + if withdirs or not item.is_folder: + contents.append(item.entry(name, detail)) if check_empty_root: try: @@ -919,12 +877,11 @@ def find( except FileNotFoundError: return {} if detail else [] - if withdirs: - contents.insert(0, _directory_entry(start)) - contents.sort(key=lambda entry: entry["name"]) if detail: + contents.sort(key=lambda entry: entry["name"]) return {entry["name"]: entry for entry in contents} - return [entry["name"] for entry in contents] + contents.sort() + return contents def upload_fobj(self, stream, rpath, callback=None, **kwargs): parent, name = self._split_file_path(rpath) @@ -985,6 +942,7 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): dst_parent = self._parent(path2) _, source = self._split_mounted_path(path1) + _, parent_path = self._split_mounted_path(dst_parent) match, generation = self._lookup_path(source) file1_id = _select_item_id(path1, match.ids) file1 = self.client.CreateFile({"id": file1_id}) @@ -993,7 +951,6 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): destination_parent = None if src_parent != dst_parent: - _, parent_path = self._split_mounted_path(dst_parent) parent_match, _ = self._lookup_path(parent_path, folders_only=True) if parent_match.files and not parent_match.folders: raise NotADirectoryError(dst_parent) @@ -1008,23 +965,19 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): or file1.get("mimeType") == FOLDER_MIME_TYPE ): destination = posixpath.join(dst_parent, dst_name) - if self._dirs.moved( - generation, file1_id, destination_parent, dst_name - ): - super().invalidate_cache(path1) - super().invalidate_cache(destination) + if file1_id == self.root: + self.invalidate_cache(self.root) else: - self._invalidate_folder( + self._dirs.moved( + generation, file1_id, - path1, - destination, - known_folder=True, - destination=(destination_parent, dst_name) - if destination_parent is not None - else None, + destination_parent, + source, + posixpath.join(parent_path, dst_name), ) + super().invalidate_cache(path1) + super().invalidate_cache(destination) else: - _, parent_path = self._split_mounted_path(dst_parent) self._dirs.file_added( destination_parent, dst_name, parent_path=parent_path ) @@ -1082,32 +1035,18 @@ def _gdrive_open_file(self, item_id, block_size=None): ) return IterStream(iter(fd)) - def _fresh_folder_match(self, base): - # A cached folder ID cannot establish whether the name is still unique. - prefix, match, _ = self._resolve_prefix(base, None) - if not match.folders: - blocked = posixpath.join(self.root, prefix) - self.invalidate_cache(blocked) - raise NotADirectoryError( - errno.ENOTDIR, os.strerror(errno.ENOTDIR), blocked - ) - if prefix != base: - missing = base.removeprefix(prefix).lstrip("/").partition("/")[0] - path = posixpath.join(self.root, prefix, missing) - self.invalidate_cache(path) - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), path - ) - return match - def rmdir(self, path): """Remove one empty Drive folder, honoring the trash_only setting.""" root, base = self._split_mounted_path(path) if base: # Walking the target also checks the mount when it is an ancestor. - if not _in_subtrees(base, (self.base,)): - self._fresh_folder_match(self.base) - match = self._fresh_folder_match(base) + if ( + self.base + and base != self.base + and not base.startswith(self.base + "/") + ): + self._resolve_directory(self.base, fresh=True) + match, _ = self._resolve_directory(base, fresh=True) if len(match.ids) != 1: raise FileExistsError( errno.EEXIST, diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 3022e57..1a1db6a 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -1,7 +1,9 @@ import errno +import gc import json import re import tempfile +import tracemalloc from concurrent.futures import ThreadPoolExecutor from threading import Event from urllib.parse import urlsplit @@ -288,6 +290,10 @@ def test_find_wide_directory(mock_drive, detail): ) calls = requests[before:] assert len(calls) == expected_calls + for req in calls: + fields = query(req)["fields"][0] + assert ("size" in fields) == detail + assert ("md5Checksum" in fields) == detail batches = [ re.findall(r"'([^']+)' in parents", query(req)["q"][0]) for req in calls @@ -299,6 +305,45 @@ def test_find_wide_directory(mock_drive, detail): ] +@pytest.mark.parametrize("operation", ["ls", "find"]) +def test_listing_a_hash_prefix_releases_file_names_and_ids( + mock_drive, operation +): + # Either field alone takes about 1 MiB if retained for every file. + page = listing( + *( + { + "id": f"{i:01024x}", + "name": f"{i:01024d}", + "mimeType": "text/plain", + } + for i in range(1000) + ) + ) + drive, requests = mock_drive(listing(folder("ab", "A")), listing(), page) + fs = filesystem(drive) + fs.ls("root") + scan = getattr(fs, operation) + assert scan("root/ab") == [] + + tracing = tracemalloc.is_tracing() + if not tracing: + tracemalloc.start() + try: + gc.collect() + before = tracemalloc.get_traced_memory()[0] + assert len(scan("root/ab")) == 1000 + gc.collect() + retained = tracemalloc.get_traced_memory()[0] - before + finally: + if not tracing: + tracemalloc.stop() + + assert retained < 256 * 1024 + assert fs.exists("root/ab") + assert len(requests) == 3 + + @pytest.mark.parametrize("operation", ["find", "expand_path"]) @pytest.mark.parametrize("maxdepth", [1, 2, 3]) def test_bounded_traversal_from_root(mock_drive, operation, maxdepth): From c1541acf00743e55bd3527bb04fa21a915c8409d Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 29 Nov 2026 09:57:46 -0800 Subject: [PATCH 13/17] Simplify Drive lookups and release stale listing entries --- pydrive2/files.py | 30 ++-- pydrive2/fs/cache.py | 87 +++++---- pydrive2/fs/spec.py | 320 ++++++++++++++++------------------ pydrive2/test/test_fs_unit.py | 84 +++++++-- 4 files changed, 282 insertions(+), 239 deletions(-) diff --git a/pydrive2/files.py b/pydrive2/files.py index bcc8e1c..9d2edc0 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -20,6 +20,7 @@ ) from .auth import LoadAuth +FOLDER_MIME_TYPE = "application/vnd.google-apps.folder" DEFAULT_FILE_FIELDS = ( "id,name,mimeType,description,parents,trashed,size,md5Checksum," "resourceKey,webViewLink,createdTime,modifiedTime" @@ -99,22 +100,11 @@ def _decorated(self, *args, **kwargs): return _decorated -class GoogleDriveFileList(ApiResourceList): - """Google Drive FileList instance. - - Equivalent to Files.list() in Drive APIs. - """ - - def __init__(self, auth=None, param=None): - """Create an instance of GoogleDriveFileList.""" - super().__init__(auth=auth, metadata=param) +class _FileMetadataPages(ApiResourceList): + """Drive file metadata, one API response per iteration.""" @LoadAuth def _GetList(self): - """Overwritten method which actually makes API call to list files. - - :returns: list -- list of pydrive2.files.GoogleDriveFile. - """ params = dict( self, supportsAllDrives=True, includeItemsFromAllDrives=True ) @@ -130,9 +120,19 @@ def _GetList(self): except errors.HttpError as error: raise ApiRequestError(error) + return self.metadata.get("files", []) + + +class GoogleDriveFileList(_FileMetadataPages): + """GoogleDriveFile objects returned by Drive's files.list API.""" + + def __init__(self, auth=None, param=None): + super().__init__(auth=auth, metadata=param) + + def _GetList(self): return [ GoogleDriveFile(self.auth, metadata, uploaded=True) - for metadata in self.metadata.get("files", []) + for metadata in super()._GetList() ] @@ -485,7 +485,7 @@ def FetchContent(self, mimetype=None, remove_bom=False): if not self.uploaded and not self._SourceMimeType(): self.FetchMetadata() if self._SourceMimeType() in { - "application/vnd.google-apps.folder", + FOLDER_MIME_TYPE, "application/vnd.google-apps.shortcut", }: raise FileNotDownloadableError( diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index 5559615..e2402e3 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -6,8 +6,6 @@ from threading import RLock from typing import NamedTuple -FOLDER_MIME_TYPE = "application/vnd.google-apps.folder" - class FolderLocation(NamedTuple): parent: str @@ -28,11 +26,19 @@ def __init__(self, parents, name, generation, revision): self.files: set[tuple[str, str]] = set() self.complete = True + def overlaps(self, parents, name): + return ( + name is None or self.name is None or self.name == name + ) and not self.folders.keys().isdisjoint(parents) + def observe(self, children): + if not self.complete: + return for child in children: if child.parent is None or child.ambiguous: self.complete = False - elif child.is_folder: + return + if child.is_folder: self.folders[child.parent].setdefault(child.name, []).append( child.id ) @@ -43,13 +49,9 @@ def observe(self, children): # A named lookup can find a folder under another same-name parent. # For a full listing only names shared within one parent can collide. for child in children: - if ( - not child.is_folder - and child.parent is not None - and ( - self.name is not None - or child.name in self.folders[child.parent] - ) + if not child.is_folder and ( + self.name is not None + or child.name in self.folders[child.parent] ): self.files.add((child.parent, child.name)) @@ -66,6 +68,7 @@ def __init__(self, root: str): self.lock = RLock() self.generation = 0 self._revisions = count() + # Publication compares overlapping reads in their start order. self._pending: dict[FolderListing, None] = {} self.children: dict[str, dict[str, tuple[str, ...]]] = {} # Each child records its parent/name and the revision that placed it. @@ -224,11 +227,27 @@ def removed(self, item_id, path): self._drop_subtrees([item_id]) self._recheck_path(path) + def _recheck_name(self, parent, name): + # An uncertain empty match tells us nothing. A surviving folder still + # anchors its cached descendants while Drive rechecks its siblings. + if self.children.get(parent, {}).get(name): + self.incomplete.add((parent, name)) + else: + self._remove_name(parent, name) + def _recheck_path(self, path): parents, name = self._parents_of_path(path) for parent in parents: - if name in self.children.get(parent, {}): - self.incomplete.add((parent, name)) + self._recheck_name(parent, name) + + def _discard_empty_siblings(self, path): + """An empty sibling is useful only while another parent has this folder.""" + parents, name = self._parents_of_path(path) + if len(parents) > 1 and not any( + self.children.get(parent, {}).get(name) for parent in parents + ): + for parent in parents: + self._remove_name(parent, name) def moved(self, generation, item_id, parent, source, destination): """Relink the folder by ID, keeping its descendants warm.""" @@ -239,8 +258,8 @@ def moved(self, generation, item_id, parent, source, destination): self.removed(item_id, source) self._recheck_path(destination) # A caller can resolve a physical parent through an uncached path. - if name in self.children.get(parent, {}): - self.incomplete.add((parent, name)) + if parent is not None: + self._recheck_name(parent, name) return self._unlink(old.parent, old.name, (item_id,)) parent = old.parent if parent is None else parent @@ -250,34 +269,23 @@ def moved(self, generation, item_id, parent, source, destination): parent, name, next(self._revisions) ) self.incomplete.add((parent, name)) + self._discard_empty_siblings(source) self.generation += 1 def created(self, listing, parent, item_id): # The empty name lookup and the folder POST share this listing. A # concurrent file write can supersede it until the POST has finished. with self.lock: - self._supersede((parent,), listing.name, exclude=listing) - if ( - listing.generation != self.generation - and listing.name in self.children.get(parent, {}) - ): - self.incomplete.add((parent, listing.name)) + self._invalidate_pending_reads( + (parent,), listing.name, keep=listing + ) + if listing.generation != self.generation: + self._recheck_name(parent, listing.name) listing.folders[parent][listing.name] = [item_id] - def _supersede( - self, parents, name, *, until=None, exclude=None, retired=False - ): - # A newer completed listing can confirm an absence before an older - # request has even published its first edge for that name. + def _invalidate_pending_reads(self, parents, name, *, keep=None): for pending in self._pending: - if pending is until: - break - if pending is exclude: - continue - same_name = name is None or pending.name in (None, name) - if retired or ( - same_name and not pending.folders.keys().isdisjoint(parents) - ): + if pending is not keep and pending.overlaps(parents, name): pending.generation = None def file_added(self, parent_id, name, *, parent_path=None): @@ -289,7 +297,7 @@ def file_added(self, parent_id, name, *, parent_path=None): if parent_id is None else (parent_id,) ) - self._supersede(parents, name) + self._invalidate_pending_reads(parents, name) for parent in parents: if name in self.children.get(parent, {}): self.file_collisions.add((parent, name)) @@ -305,12 +313,13 @@ def listing(self, generation, parents, *, name=None): yield listing with self.lock: if listing.complete and listing.generation == self.generation: - self._observe(listing, name) + self._publish(listing) finally: with self.lock: del self._pending[listing] - def _observe(self, listing, name): + def _publish(self, listing): + name = listing.name # Only publish under parents that are still attached to this root. groups = { parent: names @@ -352,7 +361,11 @@ def _observe(self, listing, name): self._drop_subtrees(retired) # Retired IDs have no reverse entry left to check against an older # result. Only reads started before this observation need that barrier. - self._supersede(groups, name, until=listing, retired=bool(retired)) + for older in self._pending: + if older is listing: + break + if retired or older.overlaps(groups, name): + older.generation = None def _relink(self, groups, revision): # Unlink moved IDs before pruning absent names. Their children stay diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 3d11e60..32e27de 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -7,20 +7,21 @@ import tempfile import threading import warnings -from collections import deque from contextlib import contextmanager, nullcontext from dataclasses import dataclass, field +from itertools import islice from weakref import WeakValueDictionary import appdirs from fsspec.spec import AbstractFileSystem -from funcy import chunks, retry +from funcy import chunks, distinct, retry from google.oauth2 import service_account from tqdm.utils import CallbackIOWrapper from pydrive2.auth import GoogleAuth, InvalidCredentialsError from pydrive2.drive import GoogleDrive -from pydrive2.fs.cache import FOLDER_MIME_TYPE, DirectoryCache +from pydrive2.files import FOLDER_MIME_TYPE, _FileMetadataPages +from pydrive2.fs.cache import DirectoryCache from pydrive2.fs.utils import IterStream logger = logging.getLogger(__name__) @@ -31,6 +32,7 @@ ) _NAME_FIELDS = "nextPageToken,incompleteSearch,files(id,name,parents,mimeType)" _MAX_QUERY_TERMS = 50 +_ROOT_ALIASES = {"root", "appDataFolder"} _DRIVE_SCOPE = "https://www.googleapis.com/auth/drive" _LIST_ALL_SCOPES = { _DRIVE_SCOPE + suffix @@ -91,6 +93,92 @@ def ids(self): return self.folders + [item.id for item in self.files] +class _PathResolver: + """Resolve paths for one operation. A superseded lookup finishes uncached.""" + + def __init__(self, fs, *, fresh=False): + self.fs = fs + self.fresh = fresh + self.generation = None if fresh else fs._dirs.generation + self.mount: _PathMatch | None = None + + def child(self, parents, path, name, *, folders_only, create=False): + if path == self.fs.base and self.mount is not None: + return self.mount, False + + cache = self.fs._dirs + # Hold the name lock across both the lookup and a possible creation. + parent = min(parents) if create else None + lock = ( + self.fs._creation_lock(parent, name) if create else nullcontext() + ) + with lock: + folders = cache.lookup( + parents, name, self.generation, folders_only=folders_only + ) + if folders: + return _PathMatch(folders), False + + match = _PathMatch([]) + with cache.listing(self.generation, parents, name=name) as listing: + for item in self.fs._list_children(listing): + if item.is_folder: + match.folders.append(item.id) + else: + match.files.append(item) + created = create and not match + if created: + item_id = self.fs._gdrive_create_dir(parent, name)["id"] + cache.created(listing, parent, item_id) + match.folders.append(item_id) + self.generation = listing.generation + return match, created + + def _walk(self, path, *, folders_only, create=False): + parent, folders, remaining = self.fs._dirs.prefix( + path, self.generation, folders_only=folders_only + ) + match = _PathMatch(folders) + for name in remaining: + parent = posixpath.join(parent, name) + match, _ = self.child( + match.folders, + parent, + name, + folders_only=folders_only or parent != path, + create=create, + ) + if not match.folders: + break + return parent, match + + def resolve(self, path, *, folders_only=False): + last, match = self._walk(path, folders_only=folders_only) + return match if last == path else _PathMatch([]) + + def directory(self, path, *, create=False): + last, match = self._walk(path, folders_only=True, create=create) + if match.folders: + return match + blocked = posixpath.join(self.fs.root, last) + if self.fresh: + self.fs.invalidate_cache(blocked) + if match: + raise NotADirectoryError( + errno.ENOTDIR, os.strerror(errno.ENOTDIR), blocked + ) + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), blocked + ) + + +def _drain(items): + """Consume a list in order so each row can be freed as its result is built.""" + items.reverse() + while items: + yield items.pop() + + def _select_item_id(path, ids): if ids: return min(ids) @@ -381,20 +469,21 @@ def _split_file_path(self, path): parent, name = posixpath.split(base) return posixpath.join(root, parent), name - def _resolve_mount(self): - generation = self._dirs.generation - if not self.base or self._dirs.contains(self.base, generation): - return generation, None - with self._mount_lock: - generation = self._dirs.generation - mount, generation = self._resolve_path(self.base, generation) - if not mount: - raise FileNotFoundError( - errno.ENOENT, - os.strerror(errno.ENOENT), - f"Confirm {self.path} exists and you can access it", - ) - return generation, mount + def _resolver(self): + resolver = _PathResolver(self) + if self.base and not self._dirs.contains( + self.base, resolver.generation + ): + with self._mount_lock: + resolver.generation = self._dirs.generation + resolver.mount = resolver.resolve(self.base) + if not resolver.mount: + raise FileNotFoundError( + errno.ENOENT, + os.strerror(errno.ENOENT), + f"Confirm {self.path} exists and you can access it", + ) + return resolver def invalidate_cache(self, path=None): base = self._split_mounted_path(path)[1] if path else "" @@ -469,14 +558,15 @@ def _query_children(self, parents, names=(), *, fields=_LIST_FIELDS): if names: terms = " or ".join(f"name={_quote_query_value(n)}" for n in names) query += f" and {terms}" if len(names) == 1 else f" and ({terms})" - pages = self.client.ListFile( - dict(self._list_params, q=query, pageSize=1000, fields=fields) + pages = _FileMetadataPages( + self.client.auth, + dict(self._list_params, q=query, pageSize=1000, fields=fields), ) get_page = _gdrive_retry(lambda: next(pages, None)) for page in iter(get_page, None): if pages.metadata.get("incompleteSearch"): raise OSError(errno.EIO, "Incomplete Drive listing") - yield from (item.metadata for item in page) + yield from page def _list_children( self, listing, *, require_parent=False, fields=_LIST_FIELDS @@ -485,11 +575,12 @@ def _list_children( rows = {} names = (listing.name,) if listing.name is not None else () for batch in chunks(_MAX_QUERY_TERMS, listing.folders): + # Reuse the queried parent string for all children in a large folder. batch_ids = {parent: parent for parent in batch} # Drive may report the canonical ID instead of the requested root alias. root_alias = ( batch_ids.get(self.root) - if self.root in {"root", "appDataFolder"} + if self.root in _ROOT_ALIASES else None ) unplaced = {} @@ -514,18 +605,24 @@ def _list_children( if unplaced: self._locate_children(batch, unplaced, rows, fields) if unplaced: - # An item can move or disappear before the probes finish. + # Later observations supersede earlier pages, even if the + # item disappeared before its new parent could be found. listing.complete = False + for file_id in unplaced: + rows.pop(file_id, None) listing.observe(rows.values()) - return deque(rows.values()) + return list(rows.values()) def _locate_children(self, parents, missing, rows, fields): """Place rows with hidden parent IDs using Drive's parent query.""" size = 1 while parents and missing: probe, parents = parents[:size], parents[size:] - names = dict.fromkeys(missing.values()) + # Stop once the names no longer fit in a single Drive query. + names = list( + islice(distinct(missing.values()), _MAX_QUERY_TERMS + 1) + ) if len(names) > _MAX_QUERY_TERMS: names.clear() for item in self._query_children(probe, names, fields=fields): @@ -549,113 +646,17 @@ def _creation_lock(self, parent_id, name): lock = self._creation_locks[key] = threading.RLock() return lock - def _match_child( - self, - parents, - path, - name, - generation, - mount, - *, - folders_only, - create=False, - ): - if path == self.base and mount is not None: - return mount, generation, False - - # A creator must check the cache and Drive under the same name lock. - parent = min(parents) if create else None - lock = self._creation_lock(parent, name) if create else nullcontext() - with lock: - folders = self._dirs.lookup( - parents, name, generation, folders_only=folders_only - ) - if folders: - return _PathMatch(folders), generation, False - - match = _PathMatch([]) - with self._dirs.listing(generation, parents, name=name) as listing: - for item in self._list_children(listing): - if item.is_folder: - match.folders.append(item.id) - else: - match.files.append(item) - created = create and not match - if created: - item_id = self._gdrive_create_dir(parent, name)["id"] - self._dirs.created(listing, parent, item_id) - match.folders.append(item_id) - return match, listing.generation, created - - def _walk_path( - self, path, generation, mount, *, folders_only, create=False - ): - """Return the last component reached and its Drive matches.""" - parent, folders, remaining = self._dirs.prefix( - path, generation, folders_only=folders_only - ) - match = _PathMatch(folders) - for name in remaining: - parent = posixpath.join(parent, name) - match, generation, _ = self._match_child( - match.folders, - parent, - name, - generation, - mount, - folders_only=folders_only or parent != path, - create=create, - ) - if not match.folders: - break - return parent, match, generation - - def _resolve_path( - self, path, generation, mount=None, *, folders_only=False - ): - last, match, generation = self._walk_path( - path, generation, mount, folders_only=folders_only - ) - return (match if last == path else _PathMatch([])), generation - - def _resolve_directory( - self, path, generation=None, mount=None, *, create=False, fresh=False - ): - last, match, generation = self._walk_path( - path, - None if fresh else generation, - mount, - folders_only=True, - create=create, - ) - if not match.folders: - blocked = posixpath.join(self.root, last) - if fresh: - self.invalidate_cache(blocked) - if match: - raise NotADirectoryError( - errno.ENOTDIR, os.strerror(errno.ENOTDIR), blocked - ) - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), blocked - ) - return match, generation - def _lookup_path(self, path, *, folders_only=False): if not path: return _PathMatch([self.root]), self._dirs.generation - generation, mount = self._resolve_mount() - return self._resolve_path( - path, generation, mount, folders_only=folders_only - ) + resolver = self._resolver() + match = resolver.resolve(path, folders_only=folders_only) + return match, resolver.generation def _get_item_id(self, path, create=False): _, base = self._split_mounted_path(path) if create and base: - generation, mount = self._resolve_mount() - match, _ = self._resolve_directory( - base, generation, mount, create=True - ) + match = self._resolver().directory(base, create=True) return _select_item_id(path, match.folders) match, _ = self._lookup_path(base) return _select_item_id(path, match.ids) @@ -681,7 +682,7 @@ def makedirs(self, path, exist_ok=False): def _mkdir(self, path, create_parents, exist_ok): root, base = self._split_mounted_path(path) cached = base and self._dirs.has_directory(base, self.base) - if not cached and root not in {"root", "appDataFolder"}: + if not cached and root not in _ROOT_ALIASES: metadata = self._get_root_metadata(fresh=True) if metadata.get("trashed"): raise FileNotFoundError( @@ -698,19 +699,11 @@ def _mkdir(self, path, create_parents, exist_ok): raise FileExistsError(path) return - generation, mount = self._resolve_mount() + resolver = self._resolver() parent, name = posixpath.split(base) - parent_match, generation = self._resolve_directory( - parent, generation, mount, create=create_parents - ) - leaf, _, created = self._match_child( - parent_match.folders, - base, - name, - generation, - mount, - folders_only=True, - create=True, + parent_match = resolver.directory(parent, create=create_parents) + leaf, created = resolver.child( + parent_match.folders, base, name, folders_only=True, create=True ) if not leaf.folders or (not exist_ok and not created): raise FileExistsError(path) @@ -720,7 +713,7 @@ def exists(self, path): if base and self._dirs.has_directory(base, self.base): return True try: - if not base and root not in {"root", "appDataFolder"}: + if not base and root not in _ROOT_ALIASES: self.info(path) else: with _translate_not_found(path): @@ -732,7 +725,7 @@ def exists(self, path): def info(self, path): bucket, base = self._split_mounted_path(path) - if not base and bucket not in {"root", "appDataFolder"}: + if not base and bucket not in _ROOT_ALIASES: gdrive_file = self._get_root_metadata( fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}" ) @@ -766,9 +759,7 @@ def ls(self, path, detail=False): contents = [] with self._dirs.listing(generation, dir_ids) as listing: children = self._list_children(listing, fields=fields) - # Release each row as its public entry takes its place in memory. - while children: - child = children.popleft() + for child in _drain(children): name = posixpath.join(root_path, child.name) if child.is_folder: name = name.rstrip("/") + "/" @@ -795,16 +786,10 @@ def _walk_folders(self, start, start_ids, generation, maxdepth, fields): visited.update(frontier) following = {} for parent, parent_path in frontier.items(): - entries = children.pop(parent) - # Release each row in Drive order as its result is built. - entries.reverse() - while entries: - item = entries.pop() + for item in _drain(children.pop(parent)): path = posixpath.join(parent_path, item.name) - if item.is_folder: - item_id = item.id - if item_id not in visited: - following[item_id] = path + if item.is_folder and item.id not in visited: + following[item.id] = path yield path, item if depth == maxdepth: return @@ -830,30 +815,20 @@ def find( root, base = self._split_mounted_path(path) if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") - generation, mount = self._resolve_mount() - match, generation = self._resolve_path( - base, generation, mount, folders_only=True - ) + resolver = self._resolver() + match = resolver.resolve(base, folders_only=True) start = posixpath.join(root, base).rstrip("/") check_empty_root = False - if not base and root not in {"root", "appDataFolder"}: + if not base and root not in _ROOT_ALIASES: if self._root_metadata.get("mimeType") == FOLDER_MIME_TYPE: check_empty_root = withdirs else: try: - metadata = self._get_root_metadata( - fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}" - ) + entry = self.info(start) except FileNotFoundError: return {} if detail else [] - if metadata.get("trashed"): - return {} if detail else [] - if metadata["mimeType"] != FOLDER_MIME_TYPE: - return ( - {start: _file_entry(start, metadata)} - if detail - else [start] - ) + if entry["type"] == "file": + return {start: entry} if detail else [start] if not match.folders: if match.files: file = min(match.files, key=lambda item: item.id) @@ -865,7 +840,7 @@ def find( contents.append(_directory_entry(start) if detail else start) fields = _LIST_FIELDS if detail else _NAME_FIELDS for name, item in self._walk_folders( - start, match.folders, generation, maxdepth, fields + start, match.folders, resolver.generation, maxdepth, fields ): check_empty_root = False if withdirs or not item.is_folder: @@ -1039,14 +1014,15 @@ def rmdir(self, path): """Remove one empty Drive folder, honoring the trash_only setting.""" root, base = self._split_mounted_path(path) if base: - # Walking the target also checks the mount when it is an ancestor. + # Check uniqueness on Drive before removing a directory by name. + resolver = _PathResolver(self, fresh=True) if ( self.base and base != self.base and not base.startswith(self.base + "/") ): - self._resolve_directory(self.base, fresh=True) - match, _ = self._resolve_directory(base, fresh=True) + resolver.directory(self.base) + match = resolver.directory(base) if len(match.ids) != 1: raise FileExistsError( errno.EEXIST, @@ -1055,7 +1031,7 @@ def rmdir(self, path): ) item_id = match.folders[0] else: - if root in {"root", "appDataFolder"}: + if root in _ROOT_ALIASES: raise PermissionError( errno.EPERM, "Cannot remove a Drive root", path ) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 1a1db6a..154f978 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -5,6 +5,7 @@ import tempfile import tracemalloc from concurrent.futures import ThreadPoolExecutor +from itertools import pairwise from threading import Event from urllib.parse import urlsplit @@ -305,9 +306,25 @@ def test_find_wide_directory(mock_drive, detail): ] +@pytest.fixture +def live_heap_bytes(): + def measure(): + gc.collect() + return tracemalloc.get_traced_memory()[0] + + tracing = tracemalloc.is_tracing() + if not tracing: + tracemalloc.start() + try: + yield measure + finally: + if not tracing: + tracemalloc.stop() + + @pytest.mark.parametrize("operation", ["ls", "find"]) def test_listing_a_hash_prefix_releases_file_names_and_ids( - mock_drive, operation + mock_drive, operation, live_heap_bytes ): # Either field alone takes about 1 MiB if retained for every file. page = listing( @@ -326,24 +343,43 @@ def test_listing_a_hash_prefix_releases_file_names_and_ids( scan = getattr(fs, operation) assert scan("root/ab") == [] - tracing = tracemalloc.is_tracing() - if not tracing: - tracemalloc.start() - try: - gc.collect() - before = tracemalloc.get_traced_memory()[0] - assert len(scan("root/ab")) == 1000 - gc.collect() - retained = tracemalloc.get_traced_memory()[0] - before - finally: - if not tracing: - tracemalloc.stop() - - assert retained < 256 * 1024 + before = live_heap_bytes() + assert len(scan("root/ab")) == 1000 + assert live_heap_bytes() - before < 256 * 1024 assert fs.exists("root/ab") assert len(requests) == 3 +@pytest.mark.parametrize("operation", ["remove", "rename"]) +def test_folder_mutations_release_old_names_under_duplicate_parents( + mock_drive, live_heap_bytes, operation +): + # Long names make a retained entry distinguishable from test overhead. + names = [f"folder-{i}-" + "x" * 1024 for i in range(65)] + replies = [listing(folder("dup", "A"), folder("dup", "B"))] + for i, (old, new) in enumerate(pairwise(names)): + if operation == "rename": + replies.append(listing()) # The destination does not exist. + item_id = "D" if operation == "rename" else f"D{i}" + replies.append(listing(dict(folder(old, item_id), parents=["A"]))) + replies.append( + response(folder(new, item_id) if operation == "rename" else {}) + ) + drive, requests = mock_drive(*replies) + fs = filesystem(drive, trash_only=False) + fs.ls("root") + for old, new in pairwise(names): + if operation == "rename": + fs.mv(f"root/dup/{old}", f"root/dup/{new}") + else: + fs.rm_file(f"root/dup/{old}") + assert len(requests) == len(replies) + + before = live_heap_bytes() + fs.invalidate_cache() + assert before - live_heap_bytes() < 32 * 1024 + + @pytest.mark.parametrize("operation", ["find", "expand_path"]) @pytest.mark.parametrize("maxdepth", [1, 2, 3]) def test_bounded_traversal_from_root(mock_drive, operation, maxdepth): @@ -1118,6 +1154,24 @@ def test_find_bounds_the_query_for_many_items_without_parents(mock_drive): assert query(requests[-1])["q"] == ["('A' in parents) and trashed=false"] +def test_find_omits_a_file_that_disappears_between_pages(mock_drive): + note = {"id": "N", "name": "note", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(folder("a", "A"), folder("b", "B")), + response( + {"files": [dict(note, parents=["A"])], "nextPageToken": "next"} + ), + listing(note), + listing(), + listing(), + ) + assert filesystem(drive).find("root") == [] + assert [query(req)["q"][0] for req in requests[-2:]] == [ + "('A' in parents) and trashed=false and name='note'", + "('B' in parents) and trashed=false and name='note'", + ] + + def test_find_keeps_cached_folders_when_items_without_parents_disappear( mock_drive, ): From 3cb93e772c44c28c208b1212f7d4b572ba8dbec4 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 29 Nov 2026 10:00:17 -0800 Subject: [PATCH 14/17] Describe filesystem caching and credentials in PyDrive2 terms --- docs/fsspec.rst | 7 +++---- docs/upgrading.rst | 5 ++--- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 76522d7..b943961 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -74,10 +74,9 @@ client moves, trashes, or deletes a folder, call The next lookup checks Drive for all folders with that name, including any same-name folder that still exists. -The cache retains folder IDs between calls. For a DVC remote with 256 hash -prefixes, adding files under those prefixes does not grow the directory -index. Each ``ls()`` or ``find()`` call builds its result in memory, so its -peak memory use depends on the number of entries it returns. +Only folder IDs are cached between calls. Both ``ls()`` and ``find()`` +build their results in memory, so larger listings use more memory during +the call. Drive queries for directory entries exclude trashed items. For a bare file ID, ``exists()`` returns false and ``info()`` raises ``FileNotFoundError`` diff --git a/docs/upgrading.rst b/docs/upgrading.rst index 1400695..3cedb4c 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -15,9 +15,8 @@ during sign-in and provision the resulting token JSON. See :doc:`oauth`. The fsspec backend uses a separate default cache for 2.0. Its first interactive connection prompts for a login. If you pass an explicit user -cache path, choose a new path. For DVC remotes that use -``GDRIVE_CREDENTIALS_DATA`` for a user account, replace its value with the -newly saved credentials. +cache path, choose a new path. If you pass user credentials through +``client_json``, use the newly saved token JSON. Service accounts use their configured JSON or PKCS12 signing key. Keep the key available to the application. Deployments that relied solely on a From 535085c0fa8c0fb21e45c69e4f4702e4f325248e Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 29 Nov 2026 10:26:13 -0800 Subject: [PATCH 15/17] Count Drive API listings in the live cache test --- pydrive2/test/test_fs.py | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index fb381a7..f47876f 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -5,9 +5,11 @@ import uuid from concurrent import futures from io import StringIO +from urllib.parse import parse_qsl, urlsplit import fsspec import pytest +from googleapiclient.http import HttpRequest from pydrive2.auth import GoogleAuth from pydrive2.fs import GDriveFileSystem @@ -213,14 +215,24 @@ def by_name(details): assert dirs == expected -def test_basic_ops_caching(fs, remote_dir, mocker): - # Count logical Drive listings. Transport retries and pages belong to - # the same ListFile call. The offline test counts individual requests. - lists = mocker.spy(fs.client, "ListFile") +def test_basic_ops_caching(fs, remote_dir, monkeypatch): + queries = [] + execute = HttpRequest.execute + + def record_listing(request, *args, **kwargs): + result = execute(request, *args, **kwargs) + if request.methodId == "drive.files.list": + params = dict(parse_qsl(urlsplit(request.uri).query)) + # Each successful first page starts one logical listing. + if "pageToken" not in params: + queries.append(params.get("q")) + return result + + monkeypatch.setattr(HttpRequest, "execute", record_listing) leaf = remote_dir + "/a/b/c" path = leaf + "/test.txt" fs.touch(path) - assert lists.call_count == 5 + assert len(queries) == 5 for operation, target, expected in ( (fs.exists, path, True), @@ -229,9 +241,9 @@ def test_basic_ops_caching(fs, remote_dir, mocker): (fs.find, leaf, [path]), (fs.find, remote_dir, [path]), ): - before = lists.call_count + queries.clear() assert operation(target) == expected - assert lists.call_count - before == 1, (operation.__name__, target) + assert len(queries) == 1, (operation.__name__, target, queries) def test_ops_work_with_duplicate_names(fs_factory, remote_dir): From b7ef2ab5a4d0e009719ba8087b285a37d227d606 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 29 Nov 2026 16:59:45 -0800 Subject: [PATCH 16/17] Keep moved folders reachable and reduce listing memory --- docs/upgrading.rst | 4 ++ pydrive2/fs/cache.py | 41 +++++++++++- pydrive2/fs/spec.py | 89 ++++++++++++++++++++----- pydrive2/test/test_fs_unit.py | 121 ++++++++++++++++++++++++++++++++++ 4 files changed, 235 insertions(+), 20 deletions(-) diff --git a/docs/upgrading.rst b/docs/upgrading.rst index 3cedb4c..a9961c7 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -30,6 +30,10 @@ The :doc:`fsspec filesystem ` now caches folders returned by If another client moves or removes a folder, list its parent again or call ``fs.invalidate_cache("root/data")`` before checking the old path. +Filesystem listings and path lookups read Drive metadata pages directly. +If your application intercepts requests through ``GoogleDrive.ListFile()``, +use the HTTP transport to observe those filesystem requests. + Drive API fields and requests ----------------------------- diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index e2402e3..f8657e7 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -35,7 +35,9 @@ def observe(self, children): if not self.complete: return for child in children: - if child.parent is None or child.ambiguous: + if child.parent is None or ( + child.ambiguous and (child.is_folder or len(self.folders) > 1) + ): self.complete = False return if child.is_folder: @@ -254,7 +256,16 @@ def moved(self, generation, item_id, parent, source, destination): name = destination.rpartition("/")[2] with self.lock: old = self.parents.get(item_id) - if generation != self.generation or old is None: + if parent is None and old is not None: + parent = old.parent + if ( + generation != self.generation + or old is None + or ( + parent != old.parent + and not self._rooted_moves({item_id: parent}) + ) + ): self.removed(item_id, source) self._recheck_path(destination) # A caller can resolve a physical parent through an uncached path. @@ -262,7 +273,6 @@ def moved(self, generation, item_id, parent, source, destination): self._recheck_name(parent, name) return self._unlink(old.parent, old.name, (item_id,)) - parent = old.parent if parent is None else parent names = self.children.setdefault(parent, {}) names[name] = (*names.get(name, ()), item_id) self.parents[item_id] = FolderLocation( @@ -367,20 +377,45 @@ def _publish(self, listing): if retired or older.overlaps(groups, name): older.generation = None + def _rooted_moves(self, moves): + """Check proposed parent changes together, following each link once.""" + rooted = {self.root} + for folder in moves: + path = set() + while folder not in rooted: + if folder in path: + return False + path.add(folder) + if folder in moves: + folder = moves[folder] + elif location := self.parents.get(folder): + folder = location.parent + else: + return False + rooted.update(path) + return self.root not in moves + def _relink(self, groups, revision): # Unlink moved IDs before pruning absent names. Their children stay # attached to the same ID even when an ancestor changes name or parent. moved = defaultdict(set) + new_parents = {} for parent, names in groups.items(): for name, ids in names.items(): for item_id in ids: old = self.parents.get(item_id) + if item_id == self.root or (old and old.parent != parent): + new_parents[item_id] = parent if old is not None and ( old.parent != parent or old.name != name ): if old.revision > revision: return False moved[old.parent, old.name].add(item_id) + if new_parents and not self._rooted_moves(new_parents): + # A partial view of an external move can put a folder below itself. + self.invalidate("") + return False for (parent, name), leaving in moved.items(): self._unlink(parent, name, leaving) return True diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 32e27de..16dd30c 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -193,19 +193,33 @@ def _directory_entry(name): return {"name": name, "type": "directory", "size": 0} +@dataclass +class _FileEntry: + """Instance dictionaries share their keys across a detailed listing.""" + + name: str + type: str + size: int | None + checksum: str | None + + def _regular_file_entry(name, size, checksum): - return { - "name": name, - "type": "file", - "size": int(size) if size is not None else None, - "checksum": checksum, - } + return vars( + _FileEntry( + name, "file", int(size) if size is not None else None, checksum + ) + ) -def _file_entry(name, item): +def _file_entry(name, item, detail=True): if item["mimeType"] == FOLDER_MIME_TYPE: - return _directory_entry(name.rstrip("/") + "/") - return _regular_file_entry(name, item.get("size"), item.get("md5Checksum")) + name = name.rstrip("/") + "/" + return _directory_entry(name) if detail else name + if detail: + return _regular_file_entry( + name, item.get("size"), item.get("md5Checksum") + ) + return name def _quote_query_value(value): @@ -612,7 +626,7 @@ def _list_children( rows.pop(file_id, None) listing.observe(rows.values()) - return list(rows.values()) + return rows.values() def _locate_children(self, parents, missing, rows, fields): """Place rows with hidden parent IDs using Drive's parent query.""" @@ -756,16 +770,48 @@ def ls(self, path, detail=False): root_path = posixpath.join(bucket, base) fields = _LIST_FIELDS if detail else _NAME_FIELDS - contents = [] + if len(dir_ids) == 1: + with self._dirs.listing(generation, dir_ids) as listing: + entries = self._ls_folder( + listing, dir_ids[0], root_path, fields, detail + ) + return list(entries) + with self._dirs.listing(generation, dir_ids) as listing: - children = self._list_children(listing, fields=fields) - for child in _drain(children): - name = posixpath.join(root_path, child.name) - if child.is_folder: - name = name.rstrip("/") + "/" - contents.append(child.entry(name, detail)) + children = list(self._list_children(listing, fields=fields)) + contents = [] + for child in _drain(children): + name = posixpath.join(root_path, child.name) + if child.is_folder: + name = name.rstrip("/") + "/" + contents.append(child.entry(name, detail)) return contents + def _ls_folder(self, listing, parent, path, fields, detail): + """Build results as pages arrive. Only folders need cache metadata.""" + entries = {} + folders = {} + for item in self._query_children([parent], fields=fields): + item_id = item["id"] + name = posixpath.join(path, item["name"]) + entries[item_id] = _file_entry(name, item, detail) + if item["mimeType"] == FOLDER_MIME_TYPE: + folders[item_id] = _ListedChild.from_drive(parent, item) + else: + folders.pop(item_id, None) + + listing.observe(folders.values()) + if folders and listing.complete: + names = { + posixpath.join(path, name): name + for name in listing.folders[parent] + } + for item_id, entry in entries.items(): + file_path = entry["name"] if detail else entry + if file_path in names and item_id not in folders: + listing.files.add((parent, names[file_path])) + return entries.values() + def _walk_folders(self, start, start_ids, generation, maxdepth, fields): frontier = dict.fromkeys(start_ids, start) to_list = self._dirs.warm_parents(frontier, maxdepth, generation) @@ -953,6 +999,15 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): super().invalidate_cache(path1) super().invalidate_cache(destination) else: + if destination_parent is None: + destination_parent = next( + ( + item.parent + for item in match.files + if item.id == file1_id and not item.ambiguous + ), + None, + ) self._dirs.file_added( destination_parent, dst_name, parent_path=parent_path ) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 154f978..b45cc83 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -1022,6 +1022,45 @@ def test_renamed_duplicate_keeps_each_parents_children_warm(mock_drive): ] +@pytest.mark.parametrize("is_folder", [True, False], ids=["folder", "file"]) +def test_rename_rechecks_destination_after_parent_is_renamed( + mock_drive, is_folder +): + parent = folder("parent", "P") + renamed_parent = dict(parent, name="renamed") + source = folder("before", "A") + if not is_folder: + source["mimeType"] = "text/plain" + renamed = dict(source, name="after") + sibling = folder("after", "Z") + + def rename_parent(request): + if request[1] == "PATCH" and urlsplit(request[0]).path.endswith("/A"): + fs.mv("root/parent", "root/renamed") + fs.ls("root/renamed") + + drive, requests = mock_drive( + listing(parent), + listing(), + listing(source), + listing(), + response(renamed_parent), + listing(renamed_parent), + listing(source, sibling), + response(renamed), + listing(sibling, renamed), + response(renamed), + on_request=rename_parent, + ) + fs = filesystem(drive) + fs.mv("root/parent/before", "root/parent/after") + fs.info("root/renamed/after") + assert query(requests[-2])["q"] == [ + "('P' in parents) and trashed=false and name='after'" + ] + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + def test_file_rename_rechecks_folder_discovered_during_the_move(mock_drive): def list_destination(request): if request[1] == "PATCH": @@ -1294,6 +1333,22 @@ def test_find_matches_legacy_parent_before_assuming_root(mock_drive): assert fs.find("root") == ["root/sub/child"] +def test_ls_warms_folders_alongside_a_shared_file(mock_drive): + sibling = folder("item", "Z") + shared = dict(WRITTEN_FILE, parents=["root", "another-parent"]) + drive, requests = mock_drive( + listing(shared, sibling, folder("child", "C")), + listing(sibling, shared), + response(shared), + ) + fs = filesystem(drive) + assert fs.ls("root") == ["root/item", "root/item/", "root/child/"] + assert fs.exists("root/child") + assert len(requests) == 1 + assert fs.info("root/item")["type"] == "file" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + def test_ambiguous_parent_row_cannot_hide_a_file_at_the_root_alias(mock_drive): sub = dict(folder("sub", "P"), parents=["canonical-root"]) directory = dict(folder("item", "Z"), parents=["canonical-root"]) @@ -1401,6 +1456,72 @@ def test_move_rechecks_the_physical_destination_when_its_path_was_uncached( ] +def test_invalidate_after_move_to_a_folder_with_hidden_parent(mock_drive): + parents = listing(folder("dup", "P"), folder("dup", "R")) + target = folder("q", "Q") + moved = folder("t", "T") + drive, requests = mock_drive( + listing(moved), + listing(folder("x", "X")), + parents, + listing(target), + listing(target), + response({"parents": ["root"]}), + response(moved), + parents, + listing(dict(target, parents=["P"])), + listing(moved), + listing(), + ) + fs = filesystem(drive) + assert fs.exists("root/t/x") + fs.mv("root/t", "root/dup/q") + # Another client deletes x before this branch is rediscovered. + fs.invalidate_cache("root/dup") + assert fs.exists("root/dup/q/t") + assert not fs.exists("root/dup/q/t/x") + assert query(requests[-1])["q"] == [ + "('T' in parents) and trashed=false and name='x'" + ] + + +def test_listing_after_parent_and_child_swap_places(mock_drive): + a, b = folder("a", "A"), folder("b", "B") + drive, requests = mock_drive( + listing(a), + listing(b, folder("gone", "X")), + listing(a), # Drive now has root/b/a and has removed gone. + listing(b), + listing(a), + listing(), + ) + fs = filesystem(drive) + fs.ls("root/a") + assert fs.ls("root/a/b") == ["root/a/b/a/"] + fs.invalidate_cache("root/a") + assert fs.ls("root/b") == ["root/b/a/"] + assert not fs.exists("root/b/a/gone") + assert query(requests[-1])["q"] == [ + "('A' in parents) and trashed=false and name='gone'" + ] + + +def test_find_keeps_folders_warm_after_observing_both_sides_of_a_move( + mock_drive, +): + a, b = folder("a", "A"), folder("b", "B") + drive, requests = mock_drive( + listing(a), + listing(b), + listing(dict(a, parents=["B"]), dict(b, parents=["root"])), + ) + fs = filesystem(drive) + assert fs.exists("root/a/b") + assert fs.find("root", withdirs=True) == ["root", "root/b", "root/b/a"] + assert fs.exists("root/b/a") + assert len(requests) == 3 + + def test_move_into_a_folder_that_shares_its_name_with_a_file(mock_drive): dest = folder("dest", "Z") file = {"id": "A", "name": "dest", "mimeType": "text/plain"} From d28828b172124f72cef6146daa529ee0b6cf26d0 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 29 Nov 2026 19:15:49 -0800 Subject: [PATCH 17/17] Reuse fully listed parents and release file IDs between pages --- docs/fsspec.rst | 3 + pydrive2/fs/cache.py | 17 ++++- pydrive2/fs/spec.py | 20 +++--- pydrive2/test/test_fs_unit.py | 116 +++++++++++++++++++++++++++++++++- 4 files changed, 140 insertions(+), 16 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index b943961..8ce4b06 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -195,6 +195,9 @@ repeated lookups. After an external move or deletion, use ``fs.invalidate_cache(path)`` for the affected path or ``fs.invalidate_cache()`` to clear the whole cache. +When listing a single Drive folder, ``ls()`` returns entries in page order. +A file renamed during pagination can appear under both names. + For sequential reads, pass a positive ``block_size`` to ``fs.open()`` to set the Drive download request size in bytes. A writer buffers data locally, using a temporary file for larger uploads. Calling ``flush()`` flushes the diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index f8657e7..bff5af7 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -73,6 +73,8 @@ def __init__(self, root: str): # Publication compares overlapping reads in their start order. self._pending: dict[FolderListing, None] = {} self.children: dict[str, dict[str, tuple[str, ...]]] = {} + # A full listing accounts for absent folder names under this parent. + self._listed_parents: set[str] = set() # Each child records its parent/name and the revision that placed it. self.parents: dict[str, FolderLocation] = {} # A mutation can leave the set of matching folders uncertain. @@ -85,6 +87,8 @@ def _folders(self, parents, name, *, folders_only): result: list[str] = [] for parent in parents: ids = self.children.get(parent, {}).get(name) + if ids is None and folders_only and parent in self._listed_parents: + continue edge = (parent, name) if ( ids is None @@ -166,6 +170,7 @@ def _drop_subtrees(self, roots): while pending: parent = pending.pop() self.parents.pop(parent, None) + self._listed_parents.discard(parent) for name, ids in self.children.pop(parent, {}).items(): self.incomplete.discard((parent, name)) self.file_collisions.discard((parent, name)) @@ -212,12 +217,14 @@ def invalidate(self, path): self.generation += 1 if not path: self.children.clear() + self._listed_parents.clear() self.parents.clear() self.incomplete.clear() self.file_collisions.clear() return parents, name = self._parents_of_path(path) for parent in parents: + self._listed_parents.discard(parent) self._drop_subtrees(self._remove_name(parent, name)) def removed(self, item_id, path): @@ -235,6 +242,7 @@ def _recheck_name(self, parent, name): if self.children.get(parent, {}).get(name): self.incomplete.add((parent, name)) else: + self._listed_parents.discard(parent) self._remove_name(parent, name) def _recheck_path(self, path): @@ -291,6 +299,7 @@ def created(self, listing, parent, item_id): ) if listing.generation != self.generation: self._recheck_name(parent, listing.name) + self._listed_parents.discard(parent) listing.folders[parent][listing.name] = [item_id] def _invalidate_pending_reads(self, parents, name, *, keep=None): @@ -322,8 +331,11 @@ def listing(self, generation, parents, *, name=None): try: yield listing with self.lock: - if listing.complete and listing.generation == self.generation: - self._publish(listing) + if listing.generation == self.generation: + if listing.complete: + self._publish(listing) + else: + self._listed_parents.difference_update(listing.folders) finally: with self.lock: del self._pending[listing] @@ -345,6 +357,7 @@ def _publish(self, listing): for parent, names in groups.items(): previous = self.children.get(parent, {}) if name is None: + self._listed_parents.add(parent) for missing in previous.keys() - names.keys(): retired.extend(self._remove_name(parent, missing)) elif has_folder: diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 16dd30c..8e747db 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -772,10 +772,9 @@ def ls(self, path, detail=False): fields = _LIST_FIELDS if detail else _NAME_FIELDS if len(dir_ids) == 1: with self._dirs.listing(generation, dir_ids) as listing: - entries = self._ls_folder( + return self._ls_folder( listing, dir_ids[0], root_path, fields, detail ) - return list(entries) with self._dirs.listing(generation, dir_ids) as listing: children = list(self._list_children(listing, fields=fields)) @@ -789,16 +788,15 @@ def ls(self, path, detail=False): def _ls_folder(self, listing, parent, path, fields, detail): """Build results as pages arrive. Only folders need cache metadata.""" - entries = {} + entries = [] folders = {} for item in self._query_children([parent], fields=fields): - item_id = item["id"] name = posixpath.join(path, item["name"]) - entries[item_id] = _file_entry(name, item, detail) + entries.append(_file_entry(name, item, detail)) if item["mimeType"] == FOLDER_MIME_TYPE: - folders[item_id] = _ListedChild.from_drive(parent, item) - else: - folders.pop(item_id, None) + folders[item["id"]] = _ListedChild.from_drive(parent, item) + elif folders: + folders.pop(item["id"], None) listing.observe(folders.values()) if folders and listing.complete: @@ -806,11 +804,11 @@ def _ls_folder(self, listing, parent, path, fields, detail): posixpath.join(path, name): name for name in listing.folders[parent] } - for item_id, entry in entries.items(): + for entry in entries: file_path = entry["name"] if detail else entry - if file_path in names and item_id not in folders: + if file_path in names: listing.files.add((parent, names[file_path])) - return entries.values() + return entries def _walk_folders(self, start, start_ids, generation, maxdepth, fields): frontier = dict.fromkeys(start_ids, start) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index b45cc83..08055fb 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -350,6 +350,31 @@ def test_listing_a_hash_prefix_releases_file_names_and_ids( assert len(requests) == 3 +def test_ls_releases_file_ids_between_pages(mock_drive, live_heap_bytes): + pages = [] + for page in range(3): + items = [ + {"id": f"{i:08192x}", "name": str(i), "mimeType": "text/plain"} + for i in range(page * 128, (page + 1) * 128) + ] + data = {"files": items} + if page < 2: + data["nextPageToken"] = str(page + 1) + pages.append(response(data)) + + samples = [] + + def measure(request): + if "pageToken" in query(request): + samples.append(live_heap_bytes()) + + drive, _ = mock_drive(*pages, on_request=measure) + assert len(filesystem(drive).ls("root")) == 384 + first, second = samples + # Retaining another page of IDs would add 1 MiB. + assert second - first < 512 * 1024 + + @pytest.mark.parametrize("operation", ["remove", "rename"]) def test_folder_mutations_release_old_names_under_duplicate_parents( mock_drive, live_heap_bytes, operation @@ -530,6 +555,65 @@ def test_ls_queries_each_duplicate_folder_once_in_batches(mock_drive, count): ] == batches +@pytest.mark.parametrize("warmup", ["ls", "find"]) +def test_listed_duplicate_parents_reuse_their_child_folders( + mock_drive, warmup +): + sub = dict(folder("sub", "S"), parents=["left"]) + file = { + "name": "sub", + "id": "F", + "mimeType": "text/plain", + "parents": ["right"], + } + page = listing(sub, file) + drive, requests = mock_drive( + listing(folder("dup", "left"), folder("dup", "right")), + page, + listing(), + page, + listing(), + page, + response(file), + ) + fs = filesystem(drive) + for _ in range(2): + if warmup == "ls": + fs.ls("root/dup") + else: + fs.find("root/dup", maxdepth=1) + before = len(requests) + assert fs.ls("root/dup/sub") == [] + (children,) = requests[before:] + assert query(children)["q"] == ["('S' in parents) and trashed=false"] + + assert fs.info("root/dup/sub")["type"] == "file" + assert "name='sub'" in query(requests[-2])["q"][0] + assert urlsplit(requests[-1][0]).path.endswith("/files/F") + + +def test_incomplete_relisting_rechecks_children_of_duplicate_parents( + mock_drive, +): + first = dict(folder("sub", "S"), parents=["left"]) + second = folder("sub", "T") + drive, requests = mock_drive( + listing(folder("dup", "left"), folder("dup", "right")), + listing(first), + listing(first, second), # Drive hides the second folder's parent. + listing(first, dict(second, parents=["right"])), + listing(), + ) + fs = filesystem(drive) + fs.ls("root/dup") + fs.ls("root/dup") + assert fs.ls("root/dup/sub") == [] + assert "name='sub'" in query(requests[-2])["q"][0] + assert query(requests[-1])["q"] == [ + "('S' in parents or 'T' in parents) and trashed=false" + ] + + def test_ls_missing_folder_only_queries_its_name(mock_drive): drive, requests = mock_drive(listing()) with pytest.raises(FileNotFoundError) as exc: @@ -580,23 +664,33 @@ def test_ls_stops_before_the_next_batch_if_a_page_is_incomplete(mock_drive): @pytest.mark.parametrize( ("detail", "fields", "expected"), [ - (False, "id,name,parents,mimeType", ["root/final", "root/final/"]), + ( + False, + "id,name,parents,mimeType", + ["root/initial", "root/final/", "root/final"], + ), ( True, "id,name,parents,mimeType,size,md5Checksum", [ + { + "name": "root/initial", + "type": "file", + "size": 1, + "checksum": "old", + }, + {"name": "root/final/", "type": "directory", "size": 0}, { "name": "root/final", "type": "file", "size": 2, "checksum": "new", }, - {"name": "root/final/", "type": "directory", "size": 0}, ], ), ], ) -def test_ls_requests_only_needed_fields_and_uses_the_latest_page( +def test_ls_requests_only_needed_fields_and_returns_rows_in_page_order( mock_drive, detail, fields, expected ): file = { @@ -2977,6 +3071,22 @@ def test_missing_mount_discards_cached_children( assert all("q" not in query(req) for req in requests[2:]) +def test_exists_rechecks_a_removed_mount_before_using_a_cached_folder( + mock_drive, +): + drive, requests = mock_drive( + listing(folder("mount", "M")), + listing(folder("other", "O")), + response({"trashed": True}), + listing(), + ) + fs = filesystem(drive, "root/mount") + assert fs.exists("root/other") + fs.rm_file("root/mount") + assert not fs.exists("root/other") + assert "name='mount'" in query(requests[-1])["q"][0] + + def test_makedirs_after_trashing_and_restoring_the_mount(mock_drive): root = {"mimeType": FOLDER_MIME_TYPE} drive, _ = mock_drive(