From 800bbf309e4ed78c0041a88c5b5650e3f8de032c Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 19:19:14 -0800 Subject: [PATCH 01/19] Invalidate cached directory IDs after moves and removals --- pydrive2/fs/spec.py | 99 ++++++++++++++++++++++++++------ pydrive2/test/test_fs_listing.py | 46 +++++++++++++++ 2 files changed, 126 insertions(+), 19 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 57eb993..1370d11 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -17,7 +17,6 @@ chunks, distinct, retry, - wrap_prop, wrap_with, ) from tqdm.utils import CallbackIOWrapper @@ -254,6 +253,7 @@ def __init__( :raises: GDriveAuthError """ super().__init__(**kwargs) + self._cache_lock = threading.RLock() self.path = path self.root, self.base = self.split_path(self.path) @@ -317,9 +317,13 @@ def _split_file_path(self, path): parent, name = posixpath.split(base) return posixpath.join(root, parent), name - @wrap_prop(threading.RLock()) - @cached_property + @property def _ids_cache(self) -> _IdsCache: + with self._cache_lock: + return self._directory_ids + + @cached_property + def _directory_ids(self) -> _IdsCache: cache: _IdsCache = {"dirs": defaultdict(list), "ids": {}} base_item_ids = self._path_to_item_ids(self.base, use_cache=False) @@ -335,10 +339,47 @@ def _ids_cache(self) -> _IdsCache: return cache def _cache_path_id(self, path, *item_ids, cache=None): - cache = cache or self._ids_cache - for item_id in item_ids: - cache["ids"][item_id] = path - cache["dirs"][path].append(item_id) + with self._cache_lock: + cache = self._ids_cache if cache is None else cache + for item_id in item_ids: + old_path = cache["ids"].get(item_id) + if old_path == path: + continue + if old_path is not None: + cache["dirs"][old_path].remove(item_id) + if not cache["dirs"][old_path]: + del cache["dirs"][old_path] + cache["ids"][item_id] = path + cache["dirs"][path].append(item_id) + + def invalidate_cache(self, path=None): + base = self._split_mounted_path(path)[1] if path is not None else "" + super().invalidate_cache(path) + with self._cache_lock: + old = self.__dict__.get("_directory_ids") + if old is None: + return + if ( + not base + or self.base == base + or self.base.startswith(base + "/") + ): + del self.__dict__["_directory_ids"] + return + # Publish both indexes together. Reads already in flight can only + # populate the cache they started with. + kept: _IdsCache = {"dirs": defaultdict(list), "ids": {}} + for name, ids in old["dirs"].items(): + if name != base and not name.startswith(base + "/"): + self._cache_path_id(name, *ids, cache=kept) + self.__dict__["_directory_ids"] = kept + + def _is_cached_directory(self, item_id): + with self._cache_lock: + cache = self.__dict__.get("_directory_ids") + return cache is not None and ( + item_id == self.root or item_id in cache["ids"] + ) @cached_property def _list_params(self): @@ -409,10 +450,12 @@ def _gdrive_list_ids(self, query_ids, *, name=None): yield item def _get_remote_item_ids( - self, parent_ids, parent_path, name, use_cache=True + self, parent_ids, parent_path, name, use_cache=True, cache=None ): if not parent_ids: return None + if use_cache and cache is None: + cache = self._ids_cache res = [] for item in self._gdrive_list_ids(parent_ids, name=name): # GDrive list API is case insensitive, we need to compare @@ -422,28 +465,40 @@ def _get_remote_item_ids( if item["mimeType"] == FOLDER_MIME_TYPE and use_cache: self._cache_path_id( - posixpath.join(parent_path, item["name"]), item["id"] + posixpath.join(parent_path, item["name"]), + item["id"], + cache=cache, ) return res - def _get_cached_item_ids(self, path, use_cache): + def _get_cached_item_ids(self, path, use_cache, cache=None): if not path: return [self.root] if use_cache: # Another caller can add parents while a batched lookup is running. - return self._ids_cache["dirs"].get(path, []).copy() + with self._cache_lock: + cache = self._ids_cache if cache is None else cache + return cache["dirs"].get(path, []).copy() return [] - def _path_to_item_ids(self, path, create=False, use_cache=True): - item_ids = self._get_cached_item_ids(path, use_cache) + def _path_to_item_ids( + self, path, create=False, use_cache=True, cache=None + ): + if not path: + return [self.root] + if use_cache and cache is None: + cache = self._ids_cache + item_ids = self._get_cached_item_ids(path, use_cache, cache) if item_ids: return item_ids parent_path, name = posixpath.split(path) - parent_ids = self._path_to_item_ids(parent_path, create, use_cache) + parent_ids = self._path_to_item_ids( + parent_path, create, use_cache, cache + ) item_ids = self._get_remote_item_ids( - parent_ids, parent_path, name, use_cache + parent_ids, parent_path, name, use_cache, cache ) if item_ids: return item_ids @@ -540,9 +595,11 @@ def find(self, path, detail=False, **kwargs): # Make sure the base path is cached and dir_ids below has some # dirs revelant to this call - self._path_to_item_ids(base) + cache = self._ids_cache + self._path_to_item_ids(base, cache=cache) - dir_ids = [self._ids_cache["ids"].copy()] + with self._cache_lock: + dir_ids = [cache["ids"].copy()] seen_paths: set[str] = set() contents = [] while dir_ids: @@ -575,7 +632,7 @@ def find(self, path, detail=False, **kwargs): item_path = posixpath.join(query_ids[parent_id], item["name"]) if item["mimeType"] == FOLDER_MIME_TYPE: new_query_ids[item["id"]] = item_path - self._cache_path_id(item_path, item["id"]) + self._cache_path_id(item_path, item["id"], cache=cache) continue contents.append( _file_entry(posixpath.join(bucket, item_path), item) @@ -651,8 +708,10 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): file2_parent_id = self._get_item_id(dst_parent) file1["parents"] = [file2_parent_id] - # TODO need to invalidate the cache for the old path, see #232 file1.Upload() + if self._is_cached_directory(file1_id): + self.invalidate_cache(path1) + self.invalidate_cache(posixpath.join(dst_parent, dst_name)) def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): with _translate_not_found(rpath): @@ -710,6 +769,8 @@ def _gdrive_open_file(self, item_id, block_size=None): def rm_file(self, path): item_id = self._get_item_id(path) self._gdrive_delete_file(item_id) + if self._is_cached_directory(item_id): + self.invalidate_cache(path) @_gdrive_retry def _gdrive_delete_file(self, item_id): diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index b97fb33..89426ca 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -185,3 +185,49 @@ def list_query(query): } for path, item in files.items() ) + + +@pytest.mark.parametrize("operation", ["trash", "move"]) +def test_directory_mutation_invalidates_subtree(listing_fs, mocker, operation): + fs = listing_fs + fs._cache_path_id("dir", "first", "second") + fs._cache_path_id("dir/nested", "nested") + fs._cache_path_id("directory", "unrelated") + mocker.patch.object(fs, "_gdrive_list_ids", return_value=[]) + if operation == "trash": + delete = mocker.patch.object(fs, "_gdrive_delete_file") + fs.rm_file("root/dir") + delete.assert_called_once_with("first") + else: + source = mocker.patch.object(fs.client, "CreateFile") + fs.mv("root/dir", "root/renamed") + source.assert_called_once_with({"id": "first"}) + source.return_value.Upload.assert_called_once_with() + assert not fs.exists("root/dir/nested") + assert not fs.exists("root/dir") + assert fs.exists("root/directory") + assert set(fs._ids_cache["ids"]) == {"root", "unrelated"} + + +def test_invalidation_during_lookup(listing_fs, monkeypatch): + fs = listing_fs + + def listing(*args, **kwargs): + fs.invalidate_cache("root/dir") + return [{"name": "dir", "id": "stale", "mimeType": FOLDER_MIME_TYPE}] + + monkeypatch.setattr(fs, "_gdrive_list_ids", listing) + assert fs.exists("root/dir") + assert "stale" not in fs._ids_cache["ids"] + fs.invalidate_cache() + assert fs._ids_cache["ids"] == {"root": ""} + + +def test_failed_removal_preserves_cache(listing_fs, mocker): + listing_fs._cache_path_id("dir", "folder") + mocker.patch.object( + listing_fs, "_gdrive_delete_file", side_effect=PermissionError + ) + with pytest.raises(PermissionError): + listing_fs.rm_file("root/dir") + assert listing_fs.exists("root/dir") From ae0d8572fbc4e3b35707c9ad19616388aa9b21b8 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 19:22:08 -0800 Subject: [PATCH 02/19] Create Drive directories in mkdir and makedirs --- pydrive2/fs/spec.py | 47 ++++++++++++++++++++++++++++++++++- pydrive2/test/test_fs.py | 10 +++++++- pydrive2/test/test_fs_unit.py | 46 ++++++++++++++++++++++++++++++++++ 3 files changed, 101 insertions(+), 2 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 57eb993..76162c2 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -475,9 +475,11 @@ def _gdrive_create_dir(self, parent_id, name): return item @wrap_with(threading.RLock()) - def _create_dir(self, parent_id, name, remote_path): + def _create_dir(self, parent_id, name, remote_path, *, exist_ok=True): cached = self._ids_cache["dirs"].get(remote_path) if cached: + if not exist_ok: + raise FileExistsError(posixpath.join(self.root, remote_path)) return cached[0] item = self._gdrive_create_dir(parent_id, name) @@ -485,6 +487,49 @@ def _create_dir(self, parent_id, name, remote_path): return item["id"] + def mkdir(self, path, create_parents=True, **kwargs): + self._mkdir(path, create_parents, exist_ok=False) + + def makedirs(self, path, exist_ok=False): + self._mkdir(path, create_parents=True, exist_ok=exist_ok) + + def _mkdir(self, path, create_parents, exist_ok): + root, base = self._split_mounted_path(path) + if not base: + if ( + root not in {"root", "appDataFolder"} + and self.info(path)["type"] != "directory" + ): + raise FileExistsError(path) + if not exist_ok: + raise FileExistsError(path) + return + + parent_ids = [root] + parent = "" + for name in base.split("/"): + child = posixpath.join(parent, name) + leaf = child == base + dirs = self._get_cached_item_ids(child, use_cache=True) + if not dirs: + items = self._get_remote_item_ids(parent_ids, parent, name) + dirs = self._get_cached_item_ids(child, use_cache=True) + if items and not dirs: + if leaf: + raise FileExistsError(path) + raise NotADirectoryError(posixpath.join(root, child)) + if dirs: + if leaf and not exist_ok: + raise FileExistsError(path) + else: + if not leaf and not create_parents: + raise FileNotFoundError(posixpath.join(root, child)) + item_id = self._create_dir( + min(parent_ids), name, child, exist_ok=not leaf or exist_ok + ) + dirs = [item_id] + parent, parent_ids = child, dirs + def exists(self, path): root, base = self._split_mounted_path(path) try: diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index cc444a6..0b0b9da 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -131,6 +131,14 @@ def test_move(fs, remote_dir): assert initial_info == secondary_info +def test_create_empty_directory(fs, fs_factory, remote_dir): + path = remote_dir + "/empty/sub" + fs.makedirs(path) + other, _ = fs_factory() + assert other.info(path)["type"] == "directory" + assert other.ls(path) == [] + + def test_copy_file_to_new_directory(fs, remote_dir): source = remote_dir + "/source" target = remote_dir + "/nested/copy" @@ -285,7 +293,7 @@ def test_find(fs, fs_factory, remote_dir): dirnames = {posixpath.dirname(file) for file in files} for dirname in dirnames: - fs.mkdir(dirname) + fs.makedirs(dirname, exist_ok=True) for file in files: fs.touch(file) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 23ff39d..9efa123 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -352,3 +352,49 @@ def test_large_write_after_close_does_not_open_a_tempfile(mock_drive, mocker): with pytest.raises(ValueError, match="closed"): writer.write(b"too large") backing_file.assert_not_called() + + +def test_makedirs_creates_empty_drive_folders(mock_drive): + drive, requests = mock_drive( + response({"driveId": "shared"}), + response({"files": []}), + response({"id": "A"}), + response({"files": []}), + response({"id": "B"}), + ) + fs = filesystem(drive, "shared") + fs.makedirs("gdrive://shared/parent/leaf") + assert fs.exists("shared/parent/leaf") + fs.makedirs("shared/parent/leaf", exist_ok=True) + with pytest.raises(FileExistsError): + fs.makedirs("shared/parent/leaf") + assert [json.loads(req[2]) for req in requests if req[1] == "POST"] == [ + { + "name": "parent", + "parents": ["shared"], + "mimeType": FOLDER_MIME_TYPE, + }, + {"name": "leaf", "parents": ["A"], "mimeType": FOLDER_MIME_TYPE}, + ] + + +def test_mkdir_without_missing_parents(mock_drive): + drive, requests = mock_drive(response({"files": []})) + with pytest.raises(FileNotFoundError): + filesystem(drive).mkdir("root/missing/leaf", create_parents=False) + assert [req[1] for req in requests] == ["GET"] + + +@pytest.mark.parametrize( + "path,expected", + [("root/blob", FileExistsError), ("root/blob/sub", NotADirectoryError)], +) +def test_makedirs_rejects_file(mock_drive, path, expected): + drive, requests = mock_drive( + response( + {"files": [{"name": "blob", "id": "F", "mimeType": "text/plain"}]} + ) + ) + with pytest.raises(expected): + filesystem(drive).makedirs(path, exist_ok=True) + assert [req[1] for req in requests] == ["GET"] From 61d250680aa2787d0f97e48c427e7e9228bc3511 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 19:44:00 -0800 Subject: [PATCH 03/19] Make the directory cache lifecycle explicit --- pydrive2/fs/spec.py | 57 ++++++++++++++++++-------------- pydrive2/test/test_fs_listing.py | 29 ++++++++++++++++ 2 files changed, 61 insertions(+), 25 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 1370d11..ac3d459 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -5,7 +5,6 @@ import posixpath import tempfile import threading -from collections import defaultdict from contextlib import contextmanager from itertools import chain from typing import TypedDict @@ -42,10 +41,27 @@ class _IdsCache(TypedDict): - dirs: defaultdict[str, list[str]] + dirs: dict[str, list[str]] ids: dict[str, str] +def _in_subtree(path: str, root: str) -> bool: + return not root or path == root or path.startswith(root + "/") + + +def _without_subtree(cache: _IdsCache, root: str) -> _IdsCache: + # In-flight lookups can still append to the old lists. + dirs = { + path: ids.copy() + for path, ids in cache["dirs"].items() + if not _in_subtree(path, root) + } + paths_by_id = { + item_id: path for path, ids in dirs.items() for item_id in ids + } + return {"dirs": dirs, "ids": paths_by_id} + + class GDriveAuthError(Exception): pass @@ -254,6 +270,7 @@ def __init__( """ super().__init__(**kwargs) self._cache_lock = threading.RLock() + self._directory_ids: _IdsCache | None = None self.path = path self.root, self.base = self.split_path(self.path) @@ -320,11 +337,12 @@ def _split_file_path(self, path): @property def _ids_cache(self) -> _IdsCache: with self._cache_lock: + if self._directory_ids is None: + self._directory_ids = self._load_directory_ids() return self._directory_ids - @cached_property - def _directory_ids(self) -> _IdsCache: - cache: _IdsCache = {"dirs": defaultdict(list), "ids": {}} + def _load_directory_ids(self) -> _IdsCache: + cache: _IdsCache = {"dirs": {}, "ids": {}} base_item_ids = self._path_to_item_ids(self.base, use_cache=False) if not base_item_ids: @@ -350,33 +368,22 @@ def _cache_path_id(self, path, *item_ids, cache=None): if not cache["dirs"][old_path]: del cache["dirs"][old_path] cache["ids"][item_id] = path - cache["dirs"][path].append(item_id) + cache["dirs"].setdefault(path, []).append(item_id) def invalidate_cache(self, path=None): - base = self._split_mounted_path(path)[1] if path is not None else "" + subtree = self._split_mounted_path(path)[1] if path is not None else "" super().invalidate_cache(path) with self._cache_lock: - old = self.__dict__.get("_directory_ids") - if old is None: - return - if ( - not base - or self.base == base - or self.base.startswith(base + "/") - ): - del self.__dict__["_directory_ids"] - return - # Publish both indexes together. Reads already in flight can only - # populate the cache they started with. - kept: _IdsCache = {"dirs": defaultdict(list), "ids": {}} - for name, ids in old["dirs"].items(): - if name != base and not name.startswith(base + "/"): - self._cache_path_id(name, *ids, cache=kept) - self.__dict__["_directory_ids"] = kept + if _in_subtree(self.base, subtree): + self._directory_ids = None + elif self._directory_ids is not None: + self._directory_ids = _without_subtree( + self._directory_ids, subtree + ) def _is_cached_directory(self, item_id): with self._cache_lock: - cache = self.__dict__.get("_directory_ids") + cache = self._directory_ids return cache is not None and ( item_id == self.root or item_id in cache["ids"] ) diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index 89426ca..c430aa1 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -223,6 +223,35 @@ def listing(*args, **kwargs): assert fs._ids_cache["ids"] == {"root": ""} +def test_invalidating_parent_reloads_mount_on_next_lookup(mocker): + fs = GDriveFileSystem( + "root/parent/mount", google_auth=Mock(), skip_instance_cache=True + ) + parent = { + "id": "parent-id", + "name": "parent", + "mimeType": FOLDER_MIME_TYPE, + } + mount = {"id": "original", "name": "mount", "mimeType": FOLDER_MIME_TYPE} + listing = mocker.patch.object( + fs, + "_gdrive_list_ids", + side_effect=[ + [parent], + [mount], + [parent], + [dict(mount, id="replacement")], + ], + ) + + fs.invalidate_cache("root/parent") + listing.assert_not_called() + assert fs._get_item_id(fs.path) == "original" + fs.invalidate_cache("root/parent") + assert listing.call_count == 2 + assert fs._get_item_id(fs.path) == "replacement" + + def test_failed_removal_preserves_cache(listing_fs, mocker): listing_fs._cache_path_id("dir", "folder") mocker.patch.object( From 5c8e21dd4897caddcfafc3f44c5eb77ea63d5293 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 22:58:44 -0800 Subject: [PATCH 04/19] Invalidate both moved directory paths using Drive metadata --- pydrive2/fs/spec.py | 40 +++++++++++------- pydrive2/test/test_fs_listing.py | 72 +++++++++++++++++++++++++++++++- 2 files changed, 95 insertions(+), 17 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ac3d459..7c4ee2c 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -45,16 +45,19 @@ class _IdsCache(TypedDict): ids: dict[str, str] -def _in_subtree(path: str, root: str) -> bool: - return not root or path == root or path.startswith(root + "/") +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 _without_subtree(cache: _IdsCache, root: str) -> _IdsCache: +def _without_subtrees(cache: _IdsCache, roots: tuple[str, ...]) -> _IdsCache: # In-flight lookups can still append to the old lists. dirs = { path: ids.copy() for path, ids in cache["dirs"].items() - if not _in_subtree(path, root) + if not _in_subtrees(path, roots) } paths_by_id = { item_id: path for path, ids in dirs.items() for item_id in ids @@ -371,14 +374,20 @@ def _cache_path_id(self, path, *item_ids, cache=None): cache["dirs"].setdefault(path, []).append(item_id) def invalidate_cache(self, path=None): - subtree = self._split_mounted_path(path)[1] if path is not None else "" - super().invalidate_cache(path) + 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) with self._cache_lock: - if _in_subtree(self.base, subtree): + if _in_subtrees(self.base, subtrees): self._directory_ids = None elif self._directory_ids is not None: - self._directory_ids = _without_subtree( - self._directory_ids, subtree + self._directory_ids = _without_subtrees( + self._directory_ids, subtrees ) def _is_cached_directory(self, item_id): @@ -538,12 +547,13 @@ def _gdrive_create_dir(self, parent_id, name): @wrap_with(threading.RLock()) def _create_dir(self, parent_id, name, remote_path): - cached = self._ids_cache["dirs"].get(remote_path) + cached = self._get_cached_item_ids(remote_path, use_cache=True) if cached: return cached[0] + cache = self._ids_cache item = self._gdrive_create_dir(parent_id, name) - self._cache_path_id(remote_path, item["id"]) + self._cache_path_id(remote_path, item["id"], cache=cache) return item["id"] @@ -693,8 +703,9 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): if maxdepth is not None: raise NotImplementedError("Max depth move is not supported") + path1 = posixpath.join(*self._split_mounted_path(path1)).rstrip("/") + path2 = posixpath.join(*self._split_mounted_path(path2)).rstrip("/") src_name = posixpath.basename(path1) - src_parent = self._parent(path1) if self.exists(path2): @@ -716,9 +727,8 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): file1["parents"] = [file2_parent_id] file1.Upload() - if self._is_cached_directory(file1_id): - self.invalidate_cache(path1) - self.invalidate_cache(posixpath.join(dst_parent, dst_name)) + if file1.get("mimeType") == FOLDER_MIME_TYPE: + self._invalidate_paths(path1, posixpath.join(dst_parent, dst_name)) def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): with _translate_not_found(rpath): diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index c430aa1..19bde32 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -64,9 +64,11 @@ def parents(): assert list_query.call_count == 2 -def test_ls_repeated_cached_parent_across_batches(listing_fs, monkeypatch): +def test_ls_repeated_parent_across_batches(listing_fs, monkeypatch): parents = [f"id-{i}" for i in range(51)] - listing_fs._cache_path_id("duplicate", *parents, parents[0]) + monkeypatch.setattr( + listing_fs, "_path_to_item_ids", lambda path: [*parents, parents[0]] + ) batches = [] def list_file(params): @@ -200,6 +202,7 @@ def test_directory_mutation_invalidates_subtree(listing_fs, mocker, operation): delete.assert_called_once_with("first") else: source = mocker.patch.object(fs.client, "CreateFile") + source.return_value.get.return_value = FOLDER_MIME_TYPE fs.mv("root/dir", "root/renamed") source.assert_called_once_with({"id": "first"}) source.return_value.Upload.assert_called_once_with() @@ -252,6 +255,71 @@ def test_invalidating_parent_reloads_mount_on_next_lookup(mocker): assert fs._get_item_id(fs.path) == "replacement" +def test_cache_deduplicates_directory_ids(listing_fs): + listing_fs._cache_path_id("dir", "a", "b", "a") + listing_fs._cache_path_id("dir", "a") + assert listing_fs._get_cached_item_ids("dir", True) == ["a", "b"] + + +def test_empty_path_invalidates_folder_mount(mocker): + fs = GDriveFileSystem( + "FolderID", google_auth=Mock(), skip_instance_cache=True + ) + fs._cache_path_id("dir", "stale") + fs.invalidate_cache(fs._parent("FolderID")) + assert not fs._get_cached_item_ids("dir", True) + + +@pytest.mark.parametrize( + "src,dst", + [ + ("root/dir", "gdrive:///renamed"), + ("root/sub/dir", "gdrive://"), + ], +) +def test_move_directory_to_implicit_root(listing_fs, mocker, src, dst): + fs = listing_fs + _, base = fs.split_path(src) + fs._cache_path_id(base, "moved-id") + mocker.patch.object(fs, "_gdrive_list_ids", return_value=[]) + source = mocker.patch.object(fs.client, "CreateFile").return_value + source.get.return_value = FOLDER_MIME_TYPE + fs.mv(src, dst) + source.Upload.assert_called_once_with() + assert not fs._get_cached_item_ids(base, True) + + +def test_move_invalidates_cached_destination_even_after_source_eviction( + listing_fs, mocker +): + fs = listing_fs + fs._cache_path_id("dir", "moving") + fs._cache_path_id("dst", "destination") + fs._cache_path_id("dst/dir", "sibling") + fs._cache_path_id("dst/dir/child", "nested") + source = mocker.patch.object(fs.client, "CreateFile").return_value + source.Upload.side_effect = lambda: fs.invalidate_cache("root/dir") + source.get.return_value = FOLDER_MIME_TYPE + fs.mv("root/dir", "root/dst") + assert fs._ids_cache["ids"] == {"root": "", "destination": "dst"} + + +@pytest.mark.parametrize("op", ["move", "remove"]) +def test_file_mutations_preserve_directory_cache(listing_fs, mocker, op): + fs = listing_fs + cached = fs._ids_cache + file = {"id": "blob", "name": "file", "mimeType": "text/plain"} + mocker.patch.object(fs, "_gdrive_list_ids", return_value=[file]) + if op == "move": + source = mocker.patch.object(fs.client, "CreateFile").return_value + source.get.return_value = file["mimeType"] + fs.mv("root/file", "root/renamed") + else: + mocker.patch.object(fs, "_gdrive_delete_file") + fs.rm_file("root/file") + assert fs._ids_cache is cached + + def test_failed_removal_preserves_cache(listing_fs, mocker): listing_fs._cache_path_id("dir", "folder") mocker.patch.object( From 3323a4247ea64d1e41928d59be78fc277442d7ce Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 22:58:47 -0800 Subject: [PATCH 05/19] Reuse verified directories and resolve mkdir paths from Drive results --- pydrive2/fs/spec.py | 84 ++++++++++++++++++++++++----------- pydrive2/test/test_fs_unit.py | 81 +++++++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+), 25 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 76162c2..9b7a442 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -8,7 +8,7 @@ from collections import defaultdict from contextlib import contextmanager from itertools import chain -from typing import TypedDict +from typing import NotRequired, TypedDict import appdirs from fsspec.spec import AbstractFileSystem @@ -45,6 +45,7 @@ class _IdsCache(TypedDict): dirs: defaultdict[str, list[str]] ids: dict[str, str] + root_is_directory: NotRequired[bool] class GDriveAuthError(Exception): @@ -322,17 +323,36 @@ def _split_file_path(self, path): def _ids_cache(self) -> _IdsCache: cache: _IdsCache = {"dirs": defaultdict(list), "ids": {}} - base_item_ids = self._path_to_item_ids(self.base, use_cache=False) - if not base_item_ids: + self._cache_path_id( + self.base, *self._mount_directory_ids(), cache=cache + ) + return cache + + def _mount_directory_ids(self): + if not self.base: + return [self.root] + parent, name = posixpath.split(self.base) + parent_ids = self._path_to_item_ids(parent, use_cache=False) + items = self._named_items(parent_ids, name) + if not items: raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), f"Confirm {self.path} exists and you can access it", ) - - self._cache_path_id(self.base, *base_item_ids, cache=cache) - - return cache + return [ + item["id"] + for item in items + if item["mimeType"] == FOLDER_MIME_TYPE + ] + + def _named_items(self, parent_ids, name): + # Drive's name query is case-insensitive. + return [ + item + for item in self._gdrive_list_ids(parent_ids, name=name) + if item["name"] == name + ] def _cache_path_id(self, path, *item_ids, cache=None): cache = cache or self._ids_cache @@ -476,14 +496,15 @@ def _gdrive_create_dir(self, parent_id, name): @wrap_with(threading.RLock()) def _create_dir(self, parent_id, name, remote_path, *, exist_ok=True): - cached = self._ids_cache["dirs"].get(remote_path) + cached = self._get_cached_item_ids(remote_path, use_cache=True) if cached: if not exist_ok: raise FileExistsError(posixpath.join(self.root, remote_path)) return cached[0] + cache = self._ids_cache item = self._gdrive_create_dir(parent_id, name) - self._cache_path_id(remote_path, item["id"]) + self._cache_path_id(remote_path, item["id"], cache=cache) return item["id"] @@ -496,31 +517,44 @@ def makedirs(self, path, exist_ok=False): def _mkdir(self, path, create_parents, exist_ok): root, base = self._split_mounted_path(path) if not base: - if ( - root not in {"root", "appDataFolder"} - and self.info(path)["type"] != "directory" - ): - raise FileExistsError(path) + if root not in {"root", "appDataFolder"}: + cache = self._ids_cache + if not cache.get("root_is_directory"): + if self.info(path)["type"] != "directory": + raise FileExistsError(path) + cache["root_is_directory"] = True if not exist_ok: raise FileExistsError(path) return - parent_ids = [root] - parent = "" - for name in base.split("/"): + cache = self._ids_cache + parent = base + missing = [] + while not ( + parent_ids := self._get_cached_item_ids(parent, use_cache=True) + ): + parent, name = posixpath.split(parent) + missing.append(name) + if not missing and not exist_ok: + raise FileExistsError(path) + + for name in reversed(missing): child = posixpath.join(parent, name) leaf = child == base - dirs = self._get_cached_item_ids(child, use_cache=True) - if not dirs: - items = self._get_remote_item_ids(parent_ids, parent, name) - dirs = self._get_cached_item_ids(child, use_cache=True) - if items and not dirs: - if leaf: - raise FileExistsError(path) - raise NotADirectoryError(posixpath.join(root, child)) + matches = self._named_items(parent_ids, name) + dirs = [ + item["id"] + for item in matches + if item["mimeType"] == FOLDER_MIME_TYPE + ] if dirs: + self._cache_path_id(child, *dirs, cache=cache) if leaf and not exist_ok: raise FileExistsError(path) + elif matches: + if leaf: + raise FileExistsError(path) + raise NotADirectoryError(posixpath.join(root, child)) else: if not leaf and not create_parents: raise FileNotFoundError(posixpath.join(root, child)) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 9efa123..9ef9f61 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -398,3 +398,84 @@ def test_makedirs_rejects_file(mock_drive, path, expected): with pytest.raises(expected): filesystem(drive).makedirs(path, exist_ok=True) assert [req[1] for req in requests] == ["GET"] + + +def test_makedirs_validates_mount_id_once(mock_drive): + drive, requests = mock_drive(response({"mimeType": FOLDER_MIME_TYPE})) + fs = filesystem(drive, "FolderID") + fs.makedirs("FolderID", exist_ok=True) + fs.makedirs("FolderID", exist_ok=True) + with pytest.raises(FileExistsError): + fs.mkdir("FolderID") + assert len(requests) == 1 + + +@pytest.mark.parametrize( + "failure, error", + [ + (response({"mimeType": "text/plain"}), FileExistsError), + (error_response(404, "notFound"), FileNotFoundError), + ], +) +def test_makedirs_rejects_invalid_mount_id(mock_drive, failure, error): + drive, _ = mock_drive(failure) + with pytest.raises(error): + filesystem(drive, "FolderID").makedirs("FolderID", exist_ok=True) + + +def test_makedirs_starts_at_cached_mount(mock_drive): + def folder(name): + return response( + { + "files": [ + {"name": name, "id": name, "mimeType": FOLDER_MIME_TYPE} + ] + } + ) + + drive, requests = mock_drive( + response({"driveId": "shared"}), + folder("a"), + folder("b"), + response({"files": []}), + response({"id": "new"}), + ) + fs = filesystem(drive, "FolderID/a/b") + fs.makedirs("FolderID/a/b/new") + fs.makedirs("FolderID/a/b/new", exist_ok=True) + assert [query(req)["q"][0] for req in requests if "q" in query(req)] == [ + "('FolderID' in parents) and trashed=false and name='a'", + "('a' in parents) and trashed=false and name='b'", + "('b' in parents) and trashed=false and name='new'", + ] + + +def test_makedirs_classifies_drive_results_without_rereading_cache( + mock_drive, mocker +): + same_name = [ + {"name": "sub", "id": "file", "mimeType": "text/plain"}, + {"name": "Sub", "id": "wrong-case", "mimeType": FOLDER_MIME_TYPE}, + {"name": "sub", "id": "folder", "mimeType": FOLDER_MIME_TYPE}, + ] + drive, requests = mock_drive( + response({"files": same_name}), + response({"files": []}), + response({"id": "leaf"}), + ) + fs = filesystem(drive) + # Simulate a folder discovered by this lookup going into an expired cache. + mocker.patch.object(fs, "_cache_path_id") + fs.makedirs("root/sub/leaf") + assert json.loads(requests[-1][2])["parents"] == ["folder"] + + +def test_makedirs_rejects_file_at_nested_mount(mock_drive): + blob = response( + {"files": [{"name": "blob", "id": "F", "mimeType": "text/plain"}]} + ) + drive, requests = mock_drive(blob, blob) + fs = filesystem(drive, "root/blob") + with pytest.raises(NotADirectoryError): + fs.makedirs("root/blob/child") + assert all(req[1] == "GET" for req in requests) From 689eb82466fd44218f493e7f74dbc0edeac2336f Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 22:59:55 -0800 Subject: [PATCH 06/19] Keep directory creation on the cache used to resolve its parent --- pydrive2/fs/spec.py | 10 ++++++---- pydrive2/test/test_fs_listing.py | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 7c4ee2c..d10b9cd 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -520,7 +520,9 @@ def _path_to_item_ids( return item_ids return ( - [self._create_dir(min(parent_ids), name, path)] if create else [] + [self._create_dir(min(parent_ids), name, path, cache=cache)] + if create + else [] ) def _get_item_id(self, path, create=False, use_cache=True): @@ -546,12 +548,12 @@ def _gdrive_create_dir(self, parent_id, name): return item @wrap_with(threading.RLock()) - def _create_dir(self, parent_id, name, remote_path): - cached = self._get_cached_item_ids(remote_path, use_cache=True) + def _create_dir(self, parent_id, name, remote_path, *, cache=None): + cache = self._ids_cache if cache is None else cache + cached = self._get_cached_item_ids(remote_path, True, cache) if cached: return cached[0] - cache = self._ids_cache item = self._gdrive_create_dir(parent_id, name) self._cache_path_id(remote_path, item["id"], cache=cache) diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index 19bde32..95a1679 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -226,6 +226,23 @@ def listing(*args, **kwargs): assert fs._ids_cache["ids"] == {"root": ""} +def test_invalidation_between_parent_lookup_and_create(listing_fs, mocker): + fs = listing_fs + fs._cache_path_id("dir", "old-parent") + + def listing(*args, **kwargs): + fs.invalidate_cache("root/dir") + return [] + + mocker.patch.object(fs, "_gdrive_list_ids", side_effect=listing) + create = mocker.patch.object( + fs, "_gdrive_create_dir", return_value={"id": "child"} + ) + assert fs._get_item_id("root/dir/child", create=True) == "child" + create.assert_called_once_with("old-parent", "child") + assert fs._ids_cache["ids"] == {"root": ""} + + def test_invalidating_parent_reloads_mount_on_next_lookup(mocker): fs = GDriveFileSystem( "root/parent/mount", google_auth=Mock(), skip_instance_cache=True From 89c9518d9720b615f5893262200bfe54cc028459 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 08:49:01 -0800 Subject: [PATCH 07/19] Exercise directory invalidation through filesystem operations and Drive requests --- pydrive2/test/conftest.py | 17 ++- pydrive2/test/test_fs.py | 14 +++ pydrive2/test/test_fs_listing.py | 184 ----------------------------- pydrive2/test/test_fs_unit.py | 197 +++++++++++++++++++++++++++++-- 4 files changed, 215 insertions(+), 197 deletions(-) diff --git a/pydrive2/test/conftest.py b/pydrive2/test/conftest.py index e60be63..de32ee8 100644 --- a/pydrive2/test/conftest.py +++ b/pydrive2/test/conftest.py @@ -6,10 +6,23 @@ from pydrive2.drive import GoogleDrive +class DriveHttpMock(HttpMockSequence): + def __init__(self, responses, on_request): + super().__init__(list(responses)) + self.on_request = on_request + + def request(self, uri, method="GET", body=None, headers=None, **kwargs): + if self.on_request is not None: + self.on_request((uri, method, body, headers)) + return super().request( + uri, method, body=body, headers=headers, **kwargs + ) + + @pytest.fixture def mock_drive(): - def build(*responses): - http = HttpMockSequence(list(responses)) + def build(*responses, on_request=None): + http = DriveHttpMock(responses, on_request) auth = GoogleAuth(settings_file=None) auth.credentials = Credentials("test-token") auth.Authorize() diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index cc444a6..d3f2f92 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -140,6 +140,20 @@ def test_copy_file_to_new_directory(fs, remote_dir): assert fs.cat_file(source) == b"payload" +def test_invalidating_parent_reloads_replaced_mount(fs, remote_dir): + mount = remote_dir + "/mount" + fs.touch(mount + "/before") + reader = GDriveFileSystem( + mount, google_auth=fs.client.auth, skip_instance_cache=True + ) + assert reader.ls(mount) == [mount + "/before"] + + fs.mv(mount, remote_dir + "/original") + fs.touch(mount + "/after") + reader.invalidate_cache(remote_dir) + assert reader.ls(mount) == [mount + "/after"] + + def test_rm(fs, remote_dir): fs.touch(remote_dir + "/a.txt") fs.rm(remote_dir + "/a.txt") diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index 95a1679..8a46b24 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -64,32 +64,6 @@ def parents(): assert list_query.call_count == 2 -def test_ls_repeated_parent_across_batches(listing_fs, monkeypatch): - parents = [f"id-{i}" for i in range(51)] - monkeypatch.setattr( - listing_fs, "_path_to_item_ids", lambda path: [*parents, parents[0]] - ) - batches = [] - - def list_file(params): - batch = re.findall(r"'([^']+)' in parents", params["q"]) - batches.append(batch) - # Distinct children with the same name must all remain in the listing. - children = [ - { - "id": f"child-{parent}", - "name": "file", - "mimeType": "text/plain", - } - for parent in dict.fromkeys(batch) - ] - return iter([children[:1], [], children[1:]]) - - monkeypatch.setattr(listing_fs.client, "ListFile", list_file) - assert listing_fs.ls("root/duplicate") == ["root/duplicate/file"] * 51 - assert batches == [parents[:50], parents[50:]] - - def test_ls_uses_parents_cached_at_start(listing_fs, monkeypatch): parents = [f"id-{i}" for i in range(51)] listing_fs._cache_path_id("dir", *parents) @@ -187,161 +161,3 @@ def list_query(query): } for path, item in files.items() ) - - -@pytest.mark.parametrize("operation", ["trash", "move"]) -def test_directory_mutation_invalidates_subtree(listing_fs, mocker, operation): - fs = listing_fs - fs._cache_path_id("dir", "first", "second") - fs._cache_path_id("dir/nested", "nested") - fs._cache_path_id("directory", "unrelated") - mocker.patch.object(fs, "_gdrive_list_ids", return_value=[]) - if operation == "trash": - delete = mocker.patch.object(fs, "_gdrive_delete_file") - fs.rm_file("root/dir") - delete.assert_called_once_with("first") - else: - source = mocker.patch.object(fs.client, "CreateFile") - source.return_value.get.return_value = FOLDER_MIME_TYPE - fs.mv("root/dir", "root/renamed") - source.assert_called_once_with({"id": "first"}) - source.return_value.Upload.assert_called_once_with() - assert not fs.exists("root/dir/nested") - assert not fs.exists("root/dir") - assert fs.exists("root/directory") - assert set(fs._ids_cache["ids"]) == {"root", "unrelated"} - - -def test_invalidation_during_lookup(listing_fs, monkeypatch): - fs = listing_fs - - def listing(*args, **kwargs): - fs.invalidate_cache("root/dir") - return [{"name": "dir", "id": "stale", "mimeType": FOLDER_MIME_TYPE}] - - monkeypatch.setattr(fs, "_gdrive_list_ids", listing) - assert fs.exists("root/dir") - assert "stale" not in fs._ids_cache["ids"] - fs.invalidate_cache() - assert fs._ids_cache["ids"] == {"root": ""} - - -def test_invalidation_between_parent_lookup_and_create(listing_fs, mocker): - fs = listing_fs - fs._cache_path_id("dir", "old-parent") - - def listing(*args, **kwargs): - fs.invalidate_cache("root/dir") - return [] - - mocker.patch.object(fs, "_gdrive_list_ids", side_effect=listing) - create = mocker.patch.object( - fs, "_gdrive_create_dir", return_value={"id": "child"} - ) - assert fs._get_item_id("root/dir/child", create=True) == "child" - create.assert_called_once_with("old-parent", "child") - assert fs._ids_cache["ids"] == {"root": ""} - - -def test_invalidating_parent_reloads_mount_on_next_lookup(mocker): - fs = GDriveFileSystem( - "root/parent/mount", google_auth=Mock(), skip_instance_cache=True - ) - parent = { - "id": "parent-id", - "name": "parent", - "mimeType": FOLDER_MIME_TYPE, - } - mount = {"id": "original", "name": "mount", "mimeType": FOLDER_MIME_TYPE} - listing = mocker.patch.object( - fs, - "_gdrive_list_ids", - side_effect=[ - [parent], - [mount], - [parent], - [dict(mount, id="replacement")], - ], - ) - - fs.invalidate_cache("root/parent") - listing.assert_not_called() - assert fs._get_item_id(fs.path) == "original" - fs.invalidate_cache("root/parent") - assert listing.call_count == 2 - assert fs._get_item_id(fs.path) == "replacement" - - -def test_cache_deduplicates_directory_ids(listing_fs): - listing_fs._cache_path_id("dir", "a", "b", "a") - listing_fs._cache_path_id("dir", "a") - assert listing_fs._get_cached_item_ids("dir", True) == ["a", "b"] - - -def test_empty_path_invalidates_folder_mount(mocker): - fs = GDriveFileSystem( - "FolderID", google_auth=Mock(), skip_instance_cache=True - ) - fs._cache_path_id("dir", "stale") - fs.invalidate_cache(fs._parent("FolderID")) - assert not fs._get_cached_item_ids("dir", True) - - -@pytest.mark.parametrize( - "src,dst", - [ - ("root/dir", "gdrive:///renamed"), - ("root/sub/dir", "gdrive://"), - ], -) -def test_move_directory_to_implicit_root(listing_fs, mocker, src, dst): - fs = listing_fs - _, base = fs.split_path(src) - fs._cache_path_id(base, "moved-id") - mocker.patch.object(fs, "_gdrive_list_ids", return_value=[]) - source = mocker.patch.object(fs.client, "CreateFile").return_value - source.get.return_value = FOLDER_MIME_TYPE - fs.mv(src, dst) - source.Upload.assert_called_once_with() - assert not fs._get_cached_item_ids(base, True) - - -def test_move_invalidates_cached_destination_even_after_source_eviction( - listing_fs, mocker -): - fs = listing_fs - fs._cache_path_id("dir", "moving") - fs._cache_path_id("dst", "destination") - fs._cache_path_id("dst/dir", "sibling") - fs._cache_path_id("dst/dir/child", "nested") - source = mocker.patch.object(fs.client, "CreateFile").return_value - source.Upload.side_effect = lambda: fs.invalidate_cache("root/dir") - source.get.return_value = FOLDER_MIME_TYPE - fs.mv("root/dir", "root/dst") - assert fs._ids_cache["ids"] == {"root": "", "destination": "dst"} - - -@pytest.mark.parametrize("op", ["move", "remove"]) -def test_file_mutations_preserve_directory_cache(listing_fs, mocker, op): - fs = listing_fs - cached = fs._ids_cache - file = {"id": "blob", "name": "file", "mimeType": "text/plain"} - mocker.patch.object(fs, "_gdrive_list_ids", return_value=[file]) - if op == "move": - source = mocker.patch.object(fs.client, "CreateFile").return_value - source.get.return_value = file["mimeType"] - fs.mv("root/file", "root/renamed") - else: - mocker.patch.object(fs, "_gdrive_delete_file") - fs.rm_file("root/file") - assert fs._ids_cache is cached - - -def test_failed_removal_preserves_cache(listing_fs, mocker): - listing_fs._cache_path_id("dir", "folder") - mocker.patch.object( - listing_fs, "_gdrive_delete_file", side_effect=PermissionError - ) - with pytest.raises(PermissionError): - listing_fs.rm_file("root/dir") - assert listing_fs.exists("root/dir") diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 23ff39d..5f399f3 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -1,4 +1,5 @@ import json +import re import tempfile from urllib.parse import urlsplit @@ -18,6 +19,14 @@ def filesystem(drive, root="root", **kwargs): ) +def folder(name, item_id): + return {"name": name, "id": item_id, "mimeType": FOLDER_MIME_TYPE} + + +def listing(*items): + return response({"files": items}) + + @pytest.mark.parametrize("root", ["root", "appDataFolder"]) def test_find_accepts_canonical_parent_of_root_alias(mock_drive, root): item = { @@ -45,18 +54,24 @@ def test_ls_deduplicates_a_file_shared_across_parent_batches(mock_drive): "size": "1", } other = dict(shared, id="distinct", parents=[parents[-1]], size="2") + folders = [folder("duplicate", item_id) for item_id in parents] drive, requests = mock_drive( - response({"files": [shared]}), response({"files": [shared, other]}) + response({"files": folders, "nextPageToken": "next"}), + listing(folders[0]), + listing(shared), + listing(shared, other), ) fs = filesystem(drive) - fs._cache_path_id("duplicate", *parents) assert [ (item["name"], item["size"]) for item in fs.ls("root/duplicate", detail=True) ] == [("root/duplicate/same", 1), ("root/duplicate/same", 2)] - first, second = requests - assert query(first)["q"][0].count(" in parents") == 50 - assert query(second)["q"][0].count(" in parents") == 1 + _, page, first, second = requests + assert query(page)["pageToken"] == ["next"] + assert [ + re.findall(r"'([^']+)' in parents", query(req)["q"][0]) + for req in (first, second) + ] == [parents[:50], parents[50:]] def test_find_matches_legacy_parent_before_assuming_root(mock_drive): @@ -80,18 +95,178 @@ def test_find_matches_legacy_parent_before_assuming_root(mock_drive): assert fs.find("root") == ["root/sub/child"] +@pytest.mark.parametrize("operation", ["trash", "rename"]) +def test_directory_mutation_evicts_descendants_only(mock_drive, operation): + moved = folder("renamed", "dir-id") + mutation = ( + [listing(), response(moved)] + if operation == "rename" + else [response({})] + ) + drive, requests = mock_drive( + listing(folder("dir", "dir-id")), + listing(folder("child", "child-id")), + listing(folder("directory", "other-id")), + *mutation, + listing(), + ) + fs = filesystem(drive, trash_only=True) + assert fs.exists("root/dir/child") + assert fs.exists("root/directory") + if operation == "rename": + fs.mv("root/dir", "gdrive:///renamed") + else: + fs.rm_file("root/dir") + + assert not fs.exists("root/dir/child") + assert "name='dir'" in query(requests[-1])["q"][0] + assert fs.exists("root/directory") + + +def test_move_directory_to_implicit_root(mock_drive): + moved = folder("dir", "dir-id") + drive, requests = mock_drive( + listing(folder("sub", "sub-id")), + listing(moved), + response({"parents": ["sub-id"]}), + response({"id": "my-drive"}), + response(moved), + listing(), + ) + fs = filesystem(drive) + fs.mv("root/sub/dir", "gdrive://") + assert not fs.exists("root/sub/dir") + (update,) = [r for r in requests if r[1] == "PATCH"] + assert query(update)["addParents"] == ["my-drive"] + assert query(update)["removeParents"] == ["sub-id"] + + +def test_invalidated_lookup_does_not_recache_its_response(mock_drive): + def invalidate(request): + fs.invalidate_cache("root/dir") + + drive, _ = mock_drive( + listing(folder("dir", "old")), listing(), on_request=invalidate + ) + fs = filesystem(drive) + assert fs.exists("root/dir") + assert not fs.exists("root/dir") + + +def test_copy_into_parent_invalidated_during_lookup(mock_drive): + def invalidate(request): + if "name='child'" in query(request).get("q", [""])[0]: + fs.invalidate_cache("root/dir") + + source = {"name": "source", "id": "source", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(folder("dir", "old-parent")), + listing(source), + listing(), + response({"id": "new-child"}), + response({"id": "copy"}), + listing(), + on_request=invalidate, + ) + fs = filesystem(drive) + assert fs.exists("root/dir") + fs.cp_file("root/source", "root/dir/child/copy") + assert not fs.exists("root/dir/child") + assert [ + json.loads(r[2])["parents"] for r in requests if r[1] == "POST" + ] == [["old-parent"], ["new-child"]] + + +def test_move_refreshes_cached_destination_after_source_eviction(mock_drive): + def invalidate(request): + if request[1] == "PATCH": + fs.invalidate_cache("root/dir") + + old = folder("dir", "already-there") + moved = folder("dir", "moved") + drive, requests = mock_drive( + listing(folder("dst", "destination")), + listing(old), + listing(folder("child", "old-child")), + listing(moved), + response({"parents": ["root"]}), + response(moved), + listing(old, moved), + listing(folder("child", "old-child"), folder("child", "new-child")), + listing({"id": "file", "name": "arrived", "mimeType": "text/plain"}), + on_request=invalidate, + ) + fs = filesystem(drive) + assert fs.exists("root/dst/dir/child") + fs.mv("root/dir", "root/dst") + assert fs.ls("root/dst/dir/child") == ["root/dst/dir/child/arrived"] + parents = query(requests[-1])["q"][0] + assert "'old-child' in parents" in parents + assert "'new-child' in parents" in parents + + +def test_invalidating_an_unopened_mount_needs_no_drive_request(mock_drive): + drive, requests = mock_drive() + filesystem(drive, "root/parent/mount").invalidate_cache("root/parent") + assert requests == [] + + +def test_rediscovered_directory_id_leaves_its_old_path(mock_drive): + drive, _ = mock_drive( + listing(folder("old", "same-id")), + listing(folder("new", "same-id")), + listing(), + ) + fs = filesystem(drive) + assert fs.exists("root/old") + assert fs.exists("root/new") + assert not fs.exists("root/old") + + +def test_empty_root_marker_refreshes_a_folder_id_mount(mock_drive): + drive, _ = mock_drive( + response({"driveId": "shared"}), + listing(folder("dir", "old")), + listing(), + ) + fs = filesystem(drive, "FolderID") + assert fs.exists("FolderID/dir") + fs.invalidate_cache("") + assert not fs.exists("FolderID/dir") + + +@pytest.mark.parametrize("operation", ["rename", "delete"]) +def test_file_mutation_reuses_cached_parent(mock_drive, operation): + file = {"name": "file", "id": "blob", "mimeType": "text/plain"} + mutation = ( + [listing(), listing(file), response(file)] + if operation == "rename" + else [listing(file), response({})] + ) + drive, requests = mock_drive(listing(folder("dir", "parent")), *mutation) + fs = filesystem(drive) + assert fs.exists("root/dir") + if operation == "rename": + fs.mv("root/dir/file", "root/dir/renamed") + else: + fs.rm_file("root/dir/file") + before = len(requests) + assert fs.exists("root/dir") + assert len(requests) == before + + @pytest.mark.parametrize("trash_only", [False, True]) def test_shared_drive_delete_permission_error(mock_drive, trash_only): - file = {"id": "file", "name": "note", "mimeType": "text/plain"} - drive, _ = mock_drive( + drive, requests = mock_drive( response({"driveId": "shared"}), - response({"files": [file]}), + listing(folder("dir", "folder-id")), error_response(403, "insufficientFilePermissions"), ) + fs = filesystem(drive, "shared", trash_only=trash_only) with pytest.raises(PermissionError, match="Manager"): - filesystem(drive, "shared", trash_only=trash_only).rm_file( - "shared/note" - ) + fs.rm_file("shared/dir") + assert fs.exists("shared/dir") + assert len(requests) == 3 def test_copy_creates_missing_directories_and_copies_on_drive(mock_drive): From adb4a5cac8b6fb2611e927855fbbb622b9618bc7 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 08:50:37 -0800 Subject: [PATCH 08/19] Test mkdir races at the Drive request boundary --- pydrive2/test/test_fs_unit.py | 53 +++++++++++++---------------------- 1 file changed, 19 insertions(+), 34 deletions(-) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 6714ebc..9aef589 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -606,20 +606,11 @@ def test_makedirs_bare_root_is_independent_of_named_mount(mock_drive): def test_makedirs_starts_at_cached_mount(mock_drive): - def folder(name): - return response( - { - "files": [ - {"name": name, "id": name, "mimeType": FOLDER_MIME_TYPE} - ] - } - ) - drive, requests = mock_drive( response({"driveId": "shared"}), - folder("a"), - folder("b"), - response({"files": []}), + listing(folder("a", "a")), + listing(folder("b", "b")), + listing(), response({"id": "new"}), ) fs = filesystem(drive, "FolderID/a/b") @@ -632,33 +623,27 @@ def folder(name): ] -def test_makedirs_classifies_drive_results_without_rereading_cache( - mock_drive, mocker -): - same_name = [ - {"name": "sub", "id": "file", "mimeType": "text/plain"}, - {"name": "Sub", "id": "wrong-case", "mimeType": FOLDER_MIME_TYPE}, - {"name": "sub", "id": "folder", "mimeType": FOLDER_MIME_TYPE}, - ] +def test_makedirs_uses_the_matching_folder_during_invalidation(mock_drive): + def invalidate(request): + if "name='sub'" in query(request).get("q", [""])[0]: + fs.invalidate_cache("root/sub") + drive, requests = mock_drive( - response({"files": same_name}), - response({"files": []}), + listing( + {"name": "sub", "id": "file", "mimeType": "text/plain"}, + folder("Sub", "wrong-case"), + folder("sub", "folder"), + ), + listing(), response({"id": "leaf"}), + listing(), + on_request=invalidate, ) fs = filesystem(drive) - cache_path = fs._cache_path_id - - def cache_then_invalidate(path, *ids, **kwargs): - cache_path(path, *ids, **kwargs) - if path == "sub": - fs.invalidate_cache("root/sub") - - mocker.patch.object( - fs, "_cache_path_id", side_effect=cache_then_invalidate - ) fs.makedirs("root/sub/leaf") - assert json.loads(requests[-1][2])["parents"] == ["folder"] - assert fs._ids_cache["ids"] == {"root": ""} + (create,) = [r for r in requests if r[1] == "POST"] + assert json.loads(create[2])["parents"] == ["folder"] + assert not fs.exists("root/sub/leaf") def test_makedirs_rejects_file_at_nested_mount(mock_drive): From 93a7ea870de12bb76fab575bae366fe9a40f08c4 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 09:06:09 -0800 Subject: [PATCH 09/19] Verify directory cache reuse through public lookups and Drive listings --- pydrive2/test/test_fs.py | 41 ------------ pydrive2/test/test_fs_listing.py | 53 --------------- pydrive2/test/test_fs_registration.py | 4 +- pydrive2/test/test_fs_unit.py | 95 +++++++++++++++++++++++++++ 4 files changed, 97 insertions(+), 96 deletions(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index d3f2f92..57e11be 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -193,47 +193,6 @@ def by_name(details): assert dirs == expected -def test_basic_ops_caching(fs_factory, remote_dir, mocker): - # Internally we have to derefence names into IDs to call GDrive APIs - # we are trying hard to cache those and make sure that operations like - # exists, ls, find, etc. don't hit the API more than once per path - - # ListFile (_gdrive_list) is the main operation that we use to retieve file - # metadata in all operations like find/ls/exist - etc. It should be fine as - # a basic benchmark to count those. - # Note: we can't count direct API calls since we have retries, also can't - # count even direct calls to the GDrive client - for the same reason - fs, _ = fs_factory() - spy = mocker.spy(fs, "_gdrive_list") - - dir_path = remote_dir + "/a/b/c/" - file_path = dir_path + "test.txt" - fs.touch(file_path) - - assert spy.call_count == 5 - spy.reset_mock() - - fs.exists(file_path) - assert spy.call_count == 1 - spy.reset_mock() - - fs.ls(remote_dir) - assert spy.call_count == 1 - spy.reset_mock() - - fs.ls(dir_path) - assert spy.call_count == 1 - spy.reset_mock() - - fs.find(dir_path) - assert spy.call_count == 1 - spy.reset_mock() - - fs.find(remote_dir) - assert spy.call_count == 1 - spy.reset_mock() - - def test_ops_work_with_duplicate_names(fs_factory, remote_dir): fs, base_item = fs_factory() diff --git a/pydrive2/test/test_fs_listing.py b/pydrive2/test/test_fs_listing.py index 8a46b24..5cd70cd 100644 --- a/pydrive2/test/test_fs_listing.py +++ b/pydrive2/test/test_fs_listing.py @@ -64,59 +64,6 @@ def parents(): assert list_query.call_count == 2 -def test_ls_uses_parents_cached_at_start(listing_fs, monkeypatch): - parents = [f"id-{i}" for i in range(51)] - listing_fs._cache_path_id("dir", *parents) - - def list_query(query): - if "'id-0' in parents" in query: - # Simulate another caller caching a parent during the first batch. - listing_fs._cache_path_id("dir", "late-parent") - if "'late-parent' in parents" in query: - return [ - { - "id": "late-file", - "name": "late-file", - "mimeType": "text/plain", - } - ] - return [] - - monkeypatch.setattr(listing_fs, "_gdrive_list", list_query) - assert listing_fs.ls("root/dir") == [] - assert listing_fs.ls("root/dir") == ["root/dir/late-file"] - - -def test_path_lookup_batches_duplicate_folder_names(listing_fs, monkeypatch): - parents = [f"id-{i}" for i in range(51)] - listing_fs._cache_path_id("duplicate", *parents) - name = r"File's\name" - batches = [] - - def list_file(params): - query = params["q"] - batch = re.findall(r"'([^']+)' in parents", query) - assert 0 < len(batch) <= 50 - assert r"name='File\'s\\name'" in query - assert "trashed=false" in query - batches.append(batch) - if parents[-1] in batch: - item_id, item_name = "found", name - else: - item_id, item_name = "wrong-case", name.lower() - item = { - "id": item_id, - "name": item_name, - "mimeType": FOLDER_MIME_TYPE, - } - return iter([[item]]) - - monkeypatch.setattr(listing_fs.client, "ListFile", list_file) - assert listing_fs.exists(f"root/duplicate/{name}") - assert listing_fs._ids_cache["dirs"][f"duplicate/{name}"] == ["found"] - assert batches == [parents[:50], parents[50:]] - - @pytest.mark.parametrize("detail", [False, True]) def test_find_wide_directory(listing_fs, monkeypatch, detail): folders = [f"folder-{index}" for index in range(251)] diff --git a/pydrive2/test/test_fs_registration.py b/pydrive2/test/test_fs_registration.py index ac30d55..1dc1a8e 100644 --- a/pydrive2/test/test_fs_registration.py +++ b/pydrive2/test/test_fs_registration.py @@ -72,11 +72,11 @@ def entry(name, item_id, mime_type="text/plain"): first, second = fsspec.open_files( [prefix + "/a", prefix + "/b"], **options ) - assert fsspec.open(prefix + "/b", **options).fs is first.fs is second.fs + reopened = fsspec.open(prefix + "/b", **options) assert not requests with first as a, second as b: assert (a.read(), b.read()) == (b"one", b"two") - assert first.fs.ls(prefix) == [] + assert reopened.fs.ls(prefix) == [] shared, sub, a_lookup, _, b_lookup, _, listing = requests assert urlsplit(shared[0]).path.endswith("/FoLdEr") assert "'FoLdEr' in parents" in query(sub)["q"][0] diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 5f399f3..fd87717 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -74,6 +74,101 @@ def test_ls_deduplicates_a_file_shared_across_parent_batches(mock_drive): ] == [parents[:50], parents[50:]] +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") + child = {"id": "child", "name": "last-file", "mimeType": "text/plain"} + + def discover_rename(request): + if "'id-0' in parents" in query(request)["q"][0]: + assert fs.exists("root/renamed") + + drive, requests = mock_drive( + listing(*parents), + listing(renamed), + listing(), + listing(child), + listing(), + on_request=discover_rename, + ) + fs = filesystem(drive) + assert fs.exists("root/dir") + assert fs.ls("root/dir") == ["root/dir/last-file"] + assert "'id-50' in parents" in query(requests[-1])["q"][0] + assert fs.ls("root/dir") == [] + assert "'id-50' in parents" not in query(requests[-1])["q"][0] + + +def test_ls_reuses_exact_case_folder_across_parent_batches(mock_drive): + parents = [folder("duplicate", f"id-{i}") for i in range(51)] + name = r"File's\name" + child = {"id": "child", "name": "contents", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(*parents), + listing(folder(name.lower(), "wrong-case")), + listing(folder(name, "exact")), + listing(child), + ) + fs = filesystem(drive) + path = f"root/duplicate/{name}" + assert fs.exists(path) + assert fs.ls(path) == [path + "/contents"] + + _, first, second, children = requests + for req, batch in ((first, parents[:50]), (second, parents[50:])): + q = query(req)["q"][0] + assert r"name='File\'s\\name'" in q + assert "trashed=false" in q + assert re.findall(r"'([^']+)' in parents", q) == [ + p["id"] for p in batch + ] + assert re.findall(r"'([^']+)' in parents", query(children)["q"][0]) == [ + "exact" + ] + + +def test_nested_file_operations_reuse_resolved_directories(mock_drive): + sub = dict(folder("b", "B"), parents=["A"]) + file = { + "name": "data", + "id": "file", + "mimeType": "text/plain", + "parents": ["B"], + } + drive, requests = mock_drive( + listing(folder("mount", "M")), + listing(), + response({"id": "A"}), + listing(), + response({"id": "B"}), + ({"status": "200", "location": "https://example.test/upload"}, ""), + response({"id": "file"}), + listing(file), + listing(sub), + listing(file), + listing(file), + listing(sub, file), + ) + fs = filesystem(drive, "root/mount") + parent = "root/mount/a" + leaf = parent + "/b" + path = leaf + "/data" + fs.touch(path) + assert sum("q" in query(req) for req in requests) == 3 + + for operation, target, expected in ( + (fs.exists, path, True), + (fs.ls, parent, [leaf + "/"]), + (fs.ls, leaf, [path]), + (fs.find, leaf, [path]), + (fs.find, parent, [path]), + ): + before = len(requests) + assert operation(target) == expected + (request,) = requests[before:] + assert "q" in query(request) + + def test_find_matches_legacy_parent_before_assuming_root(mock_drive): folder = { "id": "dir", From a79d3a8f1ebb9c671332ab119351bbe653c275ac Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 09:06:31 -0800 Subject: [PATCH 10/19] Set up the listing test through makedirs --- pydrive2/test/test_fs.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index ad1724a..3c48536 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -177,8 +177,7 @@ def test_rm(fs, remote_dir): def test_ls(fs, remote_dir): - _, base = fs.split_path(remote_dir + "/dir/") - fs._path_to_item_ids(base, create=True) + fs.makedirs(remote_dir + "/dir") assert fs.ls(remote_dir + "/dir/") == [] files = set() From a76d0e89875dcde87521908c08ec87d9ed2acb85 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 09:48:27 -0800 Subject: [PATCH 11/19] Share root metadata across directory validation and Drive listings --- pydrive2/fs/spec.py | 81 ++++++++++++++++------------------- pydrive2/test/test_fs_unit.py | 57 ++++++++++++++++++++++-- 2 files changed, 91 insertions(+), 47 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ce02863..dec9a27 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -7,12 +7,11 @@ import threading from contextlib import contextmanager from itertools import chain -from typing import NotRequired, TypedDict +from typing import TypedDict import appdirs from fsspec.spec import AbstractFileSystem from funcy import ( - cached_property, chunks, distinct, retry, @@ -43,7 +42,6 @@ class _IdsCache(TypedDict): dirs: dict[str, list[str]] ids: dict[str, str] - root_is_directory: NotRequired[bool] def _in_subtrees(path: str, roots: tuple[str, ...]) -> bool: @@ -63,7 +61,7 @@ def _without_subtrees(cache: _IdsCache, roots: tuple[str, ...]) -> _IdsCache: paths_by_id = { item_id: path for path, ids in dirs.items() for item_id in ids } - return {**cache, "dirs": dirs, "ids": paths_by_id} + return {"dirs": dirs, "ids": paths_by_id} class GDriveAuthError(Exception): @@ -275,6 +273,7 @@ def __init__( super().__init__(**kwargs) self._cache_lock = threading.RLock() self._directory_ids: _IdsCache | None = None + self._root_metadata: dict = {} self.path = path self.root, self.base = self.split_path(self.path) @@ -401,6 +400,8 @@ def _invalidate_paths(self, *paths): for path in paths: super().invalidate_cache(path) with self._cache_lock: + if "" in subtrees: + self._root_metadata = {} if _in_subtrees(self.base, subtrees): self._directory_ids = None elif self._directory_ids is not None: @@ -411,43 +412,41 @@ def _invalidate_paths(self, *paths): def _is_cached_directory(self, item_id): with self._cache_lock: cache = self._directory_ids - return cache is not None and ( - item_id == self.root or item_id in cache["ids"] - ) + return cache is not None and item_id in cache["ids"] - @cached_property + @property def _list_params(self): params = {"corpora": "user"} if self.root == "appDataFolder": params["spaces"] = "appDataFolder" elif self.root != "root": - drive_id = self._gdrive_shared_drive_id(self.root) + try: + drive_id = self._get_root_metadata().get("driveId") + except FileNotFoundError as exc: + raise PermissionError from exc if drive_id: - logger.debug( - f"GDrive remote '{self.path}' is using shared drive id '{drive_id}'." - ) - params["driveId"] = drive_id - params["corpora"] = "drive" + params.update(driveId=drive_id, corpora="drive") return params @_gdrive_retry - def _gdrive_shared_drive_id(self, item_id): - from pydrive2.files import ApiRequestError - - param = {"id": item_id} - # it does not create a file on the remote - item = self.client.CreateFile(param) - # ID of the shared drive the item resides in. - # Only populated for items in shared drives. - try: - item.FetchMetadata("driveId") - except ApiRequestError as exc: - error_code = exc.error.get("code", 0) - if error_code == 404: - raise PermissionError from exc - raise - - return item.get("driveId", None) + def _get_root_metadata(self): + with self._cache_lock: + # A root invalidation during the request replaces this dictionary. + metadata = self._root_metadata + if not metadata: + item = self.client.CreateFile({"id": self.root}) + with _translate_not_found(self.root): + item.FetchMetadata("driveId,mimeType,trashed") + if item.get("trashed"): + return item.metadata + metadata.update(item.metadata) + if drive_id := metadata.get("driveId"): + logger.debug( + "GDrive remote %r is using shared drive id %r.", + self.path, + drive_id, + ) + return metadata def _gdrive_list(self, query): param = { @@ -585,17 +584,13 @@ def _mkdir(self, path, create_parents, exist_ok): root, base = self._split_mounted_path(path) if not base: if root not in {"root", "appDataFolder"}: - # Checking the root should not resolve a nested mount. - root_cache = ( - self._directory_ids if self.base else self._ids_cache - ) - if root_cache is None or not root_cache.get( - "root_is_directory" - ): - if self.info(path)["type"] != "directory": - raise FileExistsError(path) - if root_cache is not None: - root_cache["root_is_directory"] = True + metadata = self._get_root_metadata() + if metadata.get("trashed"): + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), path + ) + if metadata.get("mimeType") != FOLDER_MIME_TYPE: + raise FileExistsError(path) if not exist_ok: raise FileExistsError(path) return @@ -870,7 +865,7 @@ def _gdrive_open_file(self, item_id, block_size=None): def rm_file(self, path): item_id = self._get_item_id(path) self._gdrive_delete_file(item_id) - if self._is_cached_directory(item_id): + if item_id == self.root or self._is_cached_directory(item_id): self.invalidate_cache(path) @_gdrive_retry diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index e7bf04a..a8f7a05 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -319,15 +319,17 @@ def test_rediscovered_directory_id_leaves_its_old_path(mock_drive): def test_empty_root_marker_refreshes_a_folder_id_mount(mock_drive): - drive, _ = mock_drive( + drive, requests = mock_drive( response({"driveId": "shared"}), listing(folder("dir", "old")), + response({"driveId": "new-drive"}), listing(), ) fs = filesystem(drive, "FolderID") assert fs.exists("FolderID/dir") fs.invalidate_cache("") assert not fs.exists("FolderID/dir") + assert query(requests[-1])["driveId"] == ["new-drive"] @pytest.mark.parametrize("operation", ["rename", "delete"]) @@ -670,14 +672,61 @@ def test_makedirs_rejects_file(mock_drive, path, expected): assert [req[1] for req in requests] == ["GET"] -def test_makedirs_validates_mount_id_once(mock_drive): - drive, requests = mock_drive(response({"mimeType": FOLDER_MIME_TYPE})) +@pytest.mark.parametrize("list_first", [False, True]) +def test_makedirs_and_ls_share_mount_metadata(mock_drive, list_first): + drive, requests = mock_drive( + response({"driveId": "shared", "mimeType": FOLDER_MIME_TYPE}), + listing(), + ) fs = filesystem(drive, "FolderID") + if list_first: + assert fs.ls("FolderID") == [] fs.makedirs("FolderID", exist_ok=True) + fs.invalidate_cache("FolderID/sub") + if not list_first: + assert fs.ls("FolderID") == [] fs.makedirs("FolderID", exist_ok=True) with pytest.raises(FileExistsError): fs.mkdir("FolderID") - assert len(requests) == 1 + stat, children = requests + assert set(query(stat)["fields"][0].split(",")) == { + "driveId", + "mimeType", + "trashed", + } + assert query(children)["driveId"] == ["shared"] + + +def test_invalidating_root_during_stat_discards_its_result(mock_drive): + def invalidate(request): + fs.invalidate_cache("FolderID") + + root = {"mimeType": FOLDER_MIME_TYPE} + drive, _ = mock_drive( + response(root), + response(dict(root, trashed=True)), + on_request=invalidate, + ) + fs = filesystem(drive, "FolderID") + fs.makedirs("FolderID", exist_ok=True) + with pytest.raises(FileNotFoundError): + fs.makedirs("FolderID", exist_ok=True) + + +def test_makedirs_after_trashing_and_restoring_the_mount(mock_drive): + root = {"mimeType": FOLDER_MIME_TYPE} + drive, _ = mock_drive( + response(root), + response({"trashed": True}), + response(dict(root, trashed=True)), + response(root), + ) + fs = filesystem(drive, "FolderID", trash_only=True) + fs.makedirs("FolderID", exist_ok=True) + fs.rm_file("FolderID") + with pytest.raises(FileNotFoundError): + fs.makedirs("FolderID", exist_ok=True) + fs.makedirs("FolderID", exist_ok=True) @pytest.mark.parametrize( From 784b180d79f985ca11953dd69ad9c47f42863bc8 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 18:08:18 -0800 Subject: [PATCH 12/19] Guard the original deep-path Drive call budgets live and offline --- pydrive2/test/test_fs.py | 21 +++++++++++++ pydrive2/test/test_fs_unit.py | 55 +++++++++++++++++++++++++---------- 2 files changed, 61 insertions(+), 15 deletions(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 57e11be..90c41b5 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -193,6 +193,27 @@ 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") + leaf = remote_dir + "/a/b/c" + path = leaf + "/test.txt" + fs.touch(path) + assert lists.call_count == 5 + + for operation, target, expected in ( + (fs.exists, path, True), + (fs.ls, remote_dir, [remote_dir + "/a/"]), + (fs.ls, leaf, [path]), + (fs.find, leaf, [path]), + (fs.find, remote_dir, [path]), + ): + before = lists.call_count + assert operation(target) == expected + assert lists.call_count - before == 1, (operation.__name__, target) + + def test_ops_work_with_duplicate_names(fs_factory, remote_dir): fs, base_item = fs_factory() diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index fd87717..c4eacee 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -128,37 +128,51 @@ def test_ls_reuses_exact_case_folder_across_parent_batches(mock_drive): def test_nested_file_operations_reuse_resolved_directories(mock_drive): - sub = dict(folder("b", "B"), parents=["A"]) + a = dict(folder("a", "A"), parents=["run"]) + b = dict(folder("b", "B"), parents=["A"]) + c = dict(folder("c", "C"), parents=["B"]) file = { - "name": "data", + "name": "test.txt", "id": "file", "mimeType": "text/plain", - "parents": ["B"], + "parents": ["C"], } drive, requests = mock_drive( listing(folder("mount", "M")), listing(), - response({"id": "A"}), + response({"id": "run"}), listing(), - response({"id": "B"}), + response(a), + listing(), + response(b), + listing(), + response(c), ({"status": "200", "location": "https://example.test/upload"}, ""), response({"id": "file"}), listing(file), - listing(sub), + listing(a), listing(file), listing(file), - listing(sub, file), + listing(a, b, c, file), ) fs = filesystem(drive, "root/mount") - parent = "root/mount/a" - leaf = parent + "/b" - path = leaf + "/data" + parent = "root/mount/run" + leaf = parent + "/a/b/c" + path = leaf + "/test.txt" fs.touch(path) - assert sum("q" in query(req) for req in requests) == 3 + assert [r[1] for r in requests] == [ + "GET", + *(["GET", "POST"] * 4), + "POST", + "PUT", + ] + assert [ + query(r)["q"][0].split("name=")[-1] for r in requests if r[1] == "GET" + ] == ["'mount'", "'run'", "'a'", "'b'", "'c'"] for operation, target, expected in ( (fs.exists, path, True), - (fs.ls, parent, [leaf + "/"]), + (fs.ls, parent, [parent + "/a/"]), (fs.ls, leaf, [path]), (fs.find, leaf, [path]), (fs.find, parent, [path]), @@ -166,7 +180,7 @@ def test_nested_file_operations_reuse_resolved_directories(mock_drive): before = len(requests) assert operation(target) == expected (request,) = requests[before:] - assert "q" in query(request) + assert request[1] == "GET" and "q" in query(request) def test_find_matches_legacy_parent_before_assuming_root(mock_drive): @@ -208,14 +222,20 @@ def test_directory_mutation_evicts_descendants_only(mock_drive, operation): fs = filesystem(drive, trash_only=True) assert fs.exists("root/dir/child") assert fs.exists("root/directory") + before = len(requests) if operation == "rename": fs.mv("root/dir", "gdrive:///renamed") + assert [r[1] for r in requests[before:]] == ["GET", "PATCH"] + assert "name='renamed'" in query(requests[before])["q"][0] else: fs.rm_file("root/dir") + assert [r[1] for r in requests[before:]] == ["PATCH"] assert not fs.exists("root/dir/child") assert "name='dir'" in query(requests[-1])["q"][0] + before = len(requests) assert fs.exists("root/directory") + assert len(requests) == before def test_move_directory_to_implicit_root(mock_drive): @@ -330,7 +350,7 @@ def test_empty_root_marker_refreshes_a_folder_id_mount(mock_drive): assert not fs.exists("FolderID/dir") -@pytest.mark.parametrize("operation", ["rename", "delete"]) +@pytest.mark.parametrize("operation", ["rename", "trash", "delete"]) def test_file_mutation_reuses_cached_parent(mock_drive, operation): file = {"name": "file", "id": "blob", "mimeType": "text/plain"} mutation = ( @@ -339,12 +359,17 @@ def test_file_mutation_reuses_cached_parent(mock_drive, operation): else [listing(file), response({})] ) drive, requests = mock_drive(listing(folder("dir", "parent")), *mutation) - fs = filesystem(drive) + fs = filesystem(drive, trash_only=operation == "trash") assert fs.exists("root/dir") + before = len(requests) if operation == "rename": fs.mv("root/dir/file", "root/dir/renamed") + assert [r[1] for r in requests[before:]] == ["GET", "GET", "PATCH"] else: fs.rm_file("root/dir/file") + method = "PATCH" if operation == "trash" else "DELETE" + assert [r[1] for r in requests[before:]] == ["GET", method] + assert all("q" in query(r) for r in requests[before:-1]) before = len(requests) assert fs.exists("root/dir") assert len(requests) == before From 1ec813e199665fdf49092dca9c48f897e1336b8d Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 18:11:55 -0800 Subject: [PATCH 13/19] Reuse the mount lookup and enforce mkdir request budgets --- pydrive2/fs/spec.py | 71 +++++++++++++++++++---------------- pydrive2/test/test_fs_unit.py | 26 ++++++++++++- 2 files changed, 63 insertions(+), 34 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index dec9a27..14afdf9 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -339,36 +339,36 @@ def _split_file_path(self, path): @property def _ids_cache(self) -> _IdsCache: - with self._cache_lock: - if self._directory_ids is None: - self._directory_ids = self._load_directory_ids() - return self._directory_ids - - def _load_directory_ids(self) -> _IdsCache: - cache: _IdsCache = {"dirs": {}, "ids": {}} - - self._cache_path_id( - self.base, *self._mount_directory_ids(), cache=cache - ) - return cache + return self._directory_cache_and_mount_items()[0] - def _mount_directory_ids(self): - if not self.base: - return [self.root] - parent, name = posixpath.split(self.base) - parent_ids = self._path_to_item_ids(parent, use_cache=False) - items = list(self._named_items(parent_ids, name)) - if not items: - raise FileNotFoundError( - errno.ENOENT, - os.strerror(errno.ENOENT), - f"Confirm {self.path} exists and you can access it", - ) - return [ - item["id"] - for item in items - if item["mimeType"] == FOLDER_MIME_TYPE - ] + def _directory_cache_and_mount_items(self): + """Return the cache and any mount listing fetched by this call.""" + with self._cache_lock: + if self._directory_ids is not None: + return self._directory_ids, None + + cache: _IdsCache = {"dirs": {}, "ids": {}} + items = None + if self.base: + parent, name = posixpath.split(self.base) + parents = self._path_to_item_ids(parent, cache=cache) + items = list(self._named_items(parents, name)) + if not items: + raise FileNotFoundError( + errno.ENOENT, + os.strerror(errno.ENOENT), + f"Confirm {self.path} exists and you can access it", + ) + directories = [ + item["id"] + for item in items + if item["mimeType"] == FOLDER_MIME_TYPE + ] + else: + directories = [self.root] + self._cache_path_id(self.base, *directories, cache=cache) + self._directory_ids = cache + return cache, items def _named_items(self, parent_ids, name): # Drive's name query is case-insensitive. @@ -514,11 +514,14 @@ def _path_to_item_ids( ): if not path: return [self.root] + mount_items = None if use_cache and cache is None: - cache = self._ids_cache + cache, mount_items = self._directory_cache_and_mount_items() item_ids = self._get_cached_item_ids(path, use_cache, cache) if item_ids: return item_ids + if path == self.base and mount_items is not None: + return [item["id"] for item in mount_items] parent_path, name = posixpath.split(path) parent_ids = self._path_to_item_ids( @@ -595,7 +598,7 @@ def _mkdir(self, path, create_parents, exist_ok): raise FileExistsError(path) return - cache = self._ids_cache + cache, mount_items = self._directory_cache_and_mount_items() parent = base missing = [] while not ( @@ -609,7 +612,11 @@ def _mkdir(self, path, create_parents, exist_ok): for name in reversed(missing): child = posixpath.join(parent, name) leaf = child == base - matches = list(self._named_items(parent_ids, name)) + matches = ( + mount_items + if child == self.base and mount_items is not None + else list(self._named_items(parent_ids, name)) + ) dirs = [ item["id"] for item in matches diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 898cff8..cbf2fb8 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -661,10 +661,15 @@ def test_makedirs_creates_empty_drive_folders(mock_drive): ) fs = filesystem(drive, "shared") fs.makedirs("gdrive://shared/parent/leaf") + assert [r[1] for r in requests] == ["GET", "GET", "POST", "GET", "POST"] + cold_requests = len(requests) assert fs.exists("shared/parent/leaf") fs.makedirs("shared/parent/leaf", exist_ok=True) with pytest.raises(FileExistsError): fs.makedirs("shared/parent/leaf") + with pytest.raises(FileExistsError): + fs.mkdir("shared/parent/leaf") + assert len(requests) == cold_requests assert [json.loads(req[2]) for req in requests if req[1] == "POST"] == [ { "name": "parent", @@ -682,6 +687,22 @@ def test_mkdir_without_missing_parents(mock_drive): assert [req[1] for req in requests] == ["GET"] +def test_mkdir_in_existing_parent(mock_drive): + drive, requests = mock_drive( + listing(folder("parent", "P")), listing(), response({"id": "leaf"}) + ) + fs = filesystem(drive) + assert fs.exists("root/parent") + before = len(requests) + fs.mkdir("root/parent/leaf", create_parents=False) + lookup, create = requests[before:] + assert "'P' in parents" in query(lookup)["q"][0] + assert create[1] == "POST" and json.loads(create[2])["parents"] == ["P"] + before = len(requests) + fs.makedirs("root/parent/leaf", exist_ok=True) + assert len(requests) == before + + @pytest.mark.parametrize( "path,expected", [("root/blob", FileExistsError), ("root/blob/sub", NotADirectoryError)], @@ -819,8 +840,9 @@ def test_makedirs_rejects_file_at_nested_mount(mock_drive): blob = response( {"files": [{"name": "blob", "id": "F", "mimeType": "text/plain"}]} ) - drive, requests = mock_drive(blob, blob) + drive, requests = mock_drive(blob) fs = filesystem(drive, "root/blob") with pytest.raises(NotADirectoryError): fs.makedirs("root/blob/child") - assert all(req[1] == "GET" for req in requests) + (lookup,) = requests + assert "name='blob'" in query(lookup)["q"][0] From ef9ef3fa576112f87b781346f21a984f9a12797a Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Mon, 23 Nov 2026 16:04:48 -0800 Subject: [PATCH 14/19] Resolve paths once and evict stale descendants on folder rediscovery --- pydrive2/fs/spec.py | 339 +++++++++++++++++----------------- pydrive2/test/test_fs_unit.py | 77 +++++++- 2 files changed, 244 insertions(+), 172 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index d10b9cd..01d49b4 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -6,8 +6,8 @@ import tempfile import threading from contextlib import contextmanager +from dataclasses import dataclass, field from itertools import chain -from typing import TypedDict import appdirs from fsspec.spec import AbstractFileSystem @@ -40,9 +40,29 @@ } -class _IdsCache(TypedDict): - dirs: dict[str, list[str]] - ids: dict[str, str] +@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] + files: list[dict] = field(default_factory=list) + + @property + def ids(self): + return self.folders + [item["id"] for item in self.files] def _in_subtrees(path: str, roots: tuple[str, ...]) -> bool: @@ -52,19 +72,6 @@ def _in_subtrees(path: str, roots: tuple[str, ...]) -> bool: ) -def _without_subtrees(cache: _IdsCache, roots: tuple[str, ...]) -> _IdsCache: - # In-flight lookups can still append to the old lists. - dirs = { - path: ids.copy() - for path, ids in cache["dirs"].items() - if not _in_subtrees(path, roots) - } - paths_by_id = { - item_id: path for path, ids in dirs.items() for item_id in ids - } - return {"dirs": dirs, "ids": paths_by_id} - - class GDriveAuthError(Exception): pass @@ -273,7 +280,7 @@ def __init__( """ super().__init__(**kwargs) self._cache_lock = threading.RLock() - self._directory_ids: _IdsCache | None = None + self._directory_ids = _DirectoryCache() self.path = path self.root, self.base = self.split_path(self.path) @@ -337,41 +344,44 @@ def _split_file_path(self, path): parent, name = posixpath.split(base) return posixpath.join(root, parent), name - @property - def _ids_cache(self) -> _IdsCache: + def _directory_cache(self): with self._cache_lock: - if self._directory_ids is None: - self._directory_ids = self._load_directory_ids() - return self._directory_ids - - def _load_directory_ids(self) -> _IdsCache: - cache: _IdsCache = {"dirs": {}, "ids": {}} - - base_item_ids = self._path_to_item_ids(self.base, use_cache=False) - if not base_item_ids: - raise FileNotFoundError( - errno.ENOENT, - os.strerror(errno.ENOENT), - f"Confirm {self.path} exists and you can access it", - ) - - self._cache_path_id(self.base, *base_item_ids, cache=cache) - - return cache + cache = self._directory_ids + if cache.mount_checked: + return cache, None + mount = self._resolve_path(self.base, cache) + if not mount.ids: + raise FileNotFoundError( + errno.ENOENT, + os.strerror(errno.ENOENT), + f"Confirm {self.path} exists and you can access it", + ) + cache.mount_checked = True + return cache, mount - def _cache_path_id(self, path, *item_ids, cache=None): + def _cache_path_id(self, cache, path, *item_ids): with self._cache_lock: - cache = self._ids_cache if cache is None else cache for item_id in item_ids: - old_path = cache["ids"].get(item_id) + old_path = cache.by_id.get(item_id) if old_path == path: continue if old_path is not None: - cache["dirs"][old_path].remove(item_id) - if not cache["dirs"][old_path]: - del cache["dirs"][old_path] - cache["ids"][item_id] = path - cache["dirs"].setdefault(path, []).append(item_id) + # 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 def invalidate_cache(self, path=None): self._invalidate_paths(path) @@ -384,18 +394,16 @@ def _invalidate_paths(self, *paths): super().invalidate_cache(path) with self._cache_lock: if _in_subtrees(self.base, subtrees): - self._directory_ids = None - elif self._directory_ids is not None: - self._directory_ids = _without_subtrees( - self._directory_ids, subtrees + self._directory_ids = _DirectoryCache() + else: + self._directory_ids = self._directory_ids.without_subtrees( + subtrees ) def _is_cached_directory(self, item_id): with self._cache_lock: cache = self._directory_ids - return cache is not None and ( - item_id == self.root or item_id in cache["ids"] - ) + return item_id == self.root or item_id in cache.by_id @cached_property def _list_params(self): @@ -465,74 +473,56 @@ def _gdrive_list_ids(self, query_ids, *, name=None): seen_ids.add(file_id) yield item - def _get_remote_item_ids( - self, parent_ids, parent_path, name, use_cache=True, cache=None - ): - if not parent_ids: - return None - if use_cache and cache is None: - cache = self._ids_cache - res = [] - for item in self._gdrive_list_ids(parent_ids, name=name): - # GDrive list API is case insensitive, we need to compare - # all results and pick the ones with the right name - if item["name"] == name: - res.append(item["id"]) - - if item["mimeType"] == FOLDER_MIME_TYPE and use_cache: - self._cache_path_id( - posixpath.join(parent_path, item["name"]), - item["id"], - cache=cache, - ) - - return res + def _resolve_path( + self, path, cache, mount=None, *, create=False + ) -> _PathMatch: + # Start at the deepest cached folder and only fetch unknown components. + 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] + match = _PathMatch(folders) + for name in reversed(remaining): + parent = posixpath.join(parent, name) + if parent == self.base and mount is not None: + match = mount + else: + match = _PathMatch([]) + for item in self._gdrive_list_ids(folders, name=name): + # Drive matches case-insensitively. + if item["name"] != name: + continue + if item["mimeType"] == FOLDER_MIME_TYPE: + match.folders.append(item["id"]) + else: + match.files.append(item) + cache = self._cache_path_id(cache, parent, *match.folders) + if create and not match.folders: + if match.files: + raise NotADirectoryError(posixpath.join(self.root, parent)) + match = _PathMatch( + [self._create_dir(cache, min(folders), name, parent)] + ) + if not match.folders and parent != path: + return _PathMatch([]) + folders = match.folders + return match - def _get_cached_item_ids(self, path, use_cache, cache=None): - if not path: - return [self.root] - if use_cache: - # Another caller can add parents while a batched lookup is running. - with self._cache_lock: - cache = self._ids_cache if cache is None else cache - return cache["dirs"].get(path, []).copy() - return [] - - def _path_to_item_ids( - self, path, create=False, use_cache=True, cache=None - ): + def _path_to_item_ids(self, path, create=False): if not path: return [self.root] - if use_cache and cache is None: - cache = self._ids_cache - item_ids = self._get_cached_item_ids(path, use_cache, cache) - if item_ids: - return item_ids - - parent_path, name = posixpath.split(path) - parent_ids = self._path_to_item_ids( - parent_path, create, use_cache, cache - ) - item_ids = self._get_remote_item_ids( - parent_ids, parent_path, name, use_cache, cache - ) - if item_ids: - return item_ids - - return ( - [self._create_dir(min(parent_ids), name, path, cache=cache)] - if create - else [] - ) + return self._resolve_path( + path, *self._directory_cache(), create=create + ).ids - def _get_item_id(self, path, create=False, use_cache=True): + def _get_item_id(self, path, create=False): _, base = self._split_mounted_path(path) - - item_ids = self._path_to_item_ids(base, create, use_cache) - if item_ids: - return min(item_ids) - - assert not create + ids = self._path_to_item_ids(base, create=create) + if ids: + return min(ids) raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path) @_gdrive_retry @@ -548,14 +538,12 @@ def _gdrive_create_dir(self, parent_id, name): return item @wrap_with(threading.RLock()) - def _create_dir(self, parent_id, name, remote_path, *, cache=None): - cache = self._ids_cache if cache is None else cache - cached = self._get_cached_item_ids(remote_path, True, cache) - if cached: - return cached[0] - + def _create_dir(self, cache, parent_id, name, remote_path): + with self._cache_lock: + if cached := cache.by_path.get(remote_path): + return cached[0] item = self._gdrive_create_dir(parent_id, name) - self._cache_path_id(remote_path, item["id"], cache=cache) + self._cache_path_id(cache, remote_path, item["id"]) return item["id"] @@ -609,58 +597,67 @@ def ls(self, path, detail=False): else: return [content["name"] for content in contents] - def find(self, path, detail=False, **kwargs): - bucket, base = self._split_mounted_path(path) - - # Make sure the base path is cached and dir_ids below has some - # dirs revelant to this call - cache = self._ids_cache - self._path_to_item_ids(base, cache=cache) - + def _walk_folders(self, base, start_ids, cache): + # Cache entries are hints about which parents can share a request. + # Build paths only from the parent links in the current Drive listing. + frontier = dict.fromkeys(start_ids, base) with self._cache_lock: - dir_ids = [cache["ids"].copy()] - seen_paths: set[str] = set() - contents = [] - while dir_ids: - query_ids = { - dir_id: dir_name - for dir_id, dir_name in dir_ids.pop().items() - if posixpath.commonpath([base, dir_name]) == base - if dir_id not in seen_paths - } - if not query_ids: - continue - - seen_paths |= query_ids.keys() - - new_query_ids: dict[str, str] = {} - dir_ids.append(new_query_ids) - for item in self._gdrive_list_ids(query_ids): - # A root alias in the query is returned as its canonical ID. - parent_id = next( - (p for p in item.get("parents", ()) if p in query_ids), - None, - ) - if parent_id is None: - if ( - self.root not in {"root", "appDataFolder"} - or self.root not in query_ids - ): - continue - parent_id = self.root - item_path = posixpath.join(query_ids[parent_id], item["name"]) - if item["mimeType"] == FOLDER_MIME_TYPE: - new_query_ids[item["id"]] = item_path - self._cache_path_id(item_path, item["id"], cache=cache) - continue - contents.append( - _file_entry(posixpath.join(bucket, item_path), item) + to_list = dict.fromkeys(frontier) + to_list.update( + { + item_id: None + for item_id, path in cache.by_id.items() + if _in_subtrees(path, (base,)) + } + ) + children: dict[str, list[dict]] = {} + visited: set[str] = set() + while frontier: + 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) + + 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"] + cache = self._cache_path_id(cache, path, item_id) + if item_id not in visited: + following[item_id] = path + yield path, item + frontier = following + to_list = { + item_id: None + for item_id in frontier + if item_id not in children + } + def find(self, path, detail=False, **kwargs): + root, base = self._split_mounted_path(path) + cache, mount = self._directory_cache() + dirs = self._resolve_path(base, cache, mount).folders + contents = [ + _file_entry(posixpath.join(root, name), item) + for name, item in self._walk_folders(base, dirs, cache) + if item["mimeType"] != FOLDER_MIME_TYPE + ] if detail: - return {content["name"]: content for content in contents} - else: - return [content["name"] for content in contents] + return {entry["name"]: entry for entry in contents} + return [entry["name"] for entry in contents] def upload_fobj(self, stream, rpath, callback=None, **kwargs): parent, name = self._split_file_path(rpath) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index c4eacee..0c44a6e 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -197,7 +197,7 @@ def test_find_matches_legacy_parent_before_assuming_root(mock_drive): "parents": ["elsewhere", "dir"], } drive, _ = mock_drive( - response({"files": [folder]}), response({"files": [file]}) + response({"files": [folder]}), response({"files": [file, folder]}) ) fs = filesystem(drive) assert fs.exists("root/sub") @@ -338,6 +338,81 @@ def test_rediscovered_directory_id_leaves_its_old_path(mock_drive): assert not fs.exists("root/old") +@pytest.mark.parametrize("duplicate", [False, True]) +def test_rediscovered_directory_evicts_old_descendants(mock_drive, duplicate): + old = [folder("old", "moved")] + if duplicate: + old.append(folder("old", "stays")) + child = folder("child", "C") + drive, requests = mock_drive( + listing(*old), + listing(child), + listing(folder("sibling", "S")), + listing(folder("new", "moved")), + listing(), + listing(child), + ) + fs = filesystem(drive) + assert fs.exists("root/old/child") + assert fs.exists("root/sibling") + assert fs.exists("root/new") + before = len(requests) + assert not fs.exists("root/old/child") + (lookup,) = requests[before:] + expected = "'stays' in parents" if duplicate else "name='old'" + assert expected in query(lookup)["q"][0] + assert fs.exists("root/new/child") + before = len(requests) + assert fs.exists("root/sibling") + assert len(requests) == before + + +def test_old_child_lookup_cannot_repopulate_a_rediscovered_directory( + mock_drive, +): + def rediscover(request): + if "name='child'" in query(request)["q"][0]: + assert fs.exists("root/new") + + drive, _ = mock_drive( + listing(folder("old", "D")), + listing(folder("new", "D")), + listing(folder("child", "C")), + listing(), + on_request=rediscover, + ) + fs = filesystem(drive) + assert fs.exists("root/old/child") + assert not fs.exists("root/old/child") + + +@pytest.mark.parametrize("children_first", [False, True]) +def test_find_uses_current_parent_links_after_a_rename( + mock_drive, children_first +): + old = dict(folder("old", "D"), parents=["root"]) + child = dict(folder("child", "C"), parents=["D"]) + file = { + "id": "F", + "name": "note", + "mimeType": "text/plain", + "parents": ["C"], + } + rows = [dict(old, name="new"), child, file] + drive, requests = mock_drive( + listing(old), + listing(child), + listing(*(reversed(rows) if children_first else rows)), + listing(), + ) + fs = filesystem(drive) + assert fs.exists("root/old/child") + before = len(requests) + assert fs.find("root") == ["root/new/child/note"] + assert len(requests) == before + 1 + assert not fs.exists("root/old/child") + + def test_empty_root_marker_refreshes_a_folder_id_mount(mock_drive): drive, _ = mock_drive( response({"driveId": "shared"}), From 4f78e2f1e65f443ab6c24fa7f3218a90436e2ebe Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Tue, 24 Nov 2026 16:29:07 -0800 Subject: [PATCH 15/19] Separate lookup from creation and coordinate creates per Drive parent and name --- pydrive2/fs/spec.py | 112 +++++++++++++++++++++++----------- pydrive2/test/test_fs_unit.py | 43 +++++++++++++ 2 files changed, 118 insertions(+), 37 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 01d49b4..0559ea6 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -8,6 +8,7 @@ from contextlib import contextmanager from dataclasses import dataclass, field from itertools import chain +from weakref import WeakValueDictionary import appdirs from fsspec.spec import AbstractFileSystem @@ -16,7 +17,6 @@ chunks, distinct, retry, - wrap_with, ) from tqdm.utils import CallbackIOWrapper @@ -281,6 +281,8 @@ def __init__( super().__init__(**kwargs) self._cache_lock = threading.RLock() self._directory_ids = _DirectoryCache() + self._mount_lock = threading.RLock() + self._creation_locks: WeakValueDictionary = WeakValueDictionary() self.path = path self.root, self.base = self.split_path(self.path) @@ -349,6 +351,11 @@ def _directory_cache(self): cache = self._directory_ids if cache.mount_checked: return cache, None + with self._mount_lock: + with self._cache_lock: + cache = self._directory_ids + if cache.mount_checked: + return cache, None mount = self._resolve_path(self.base, cache) if not mount.ids: raise FileNotFoundError( @@ -356,7 +363,8 @@ def _directory_cache(self): os.strerror(errno.ENOENT), f"Confirm {self.path} exists and you can access it", ) - cache.mount_checked = True + with self._cache_lock: + cache.mount_checked = True return cache, mount def _cache_path_id(self, cache, path, *item_ids): @@ -473,10 +481,21 @@ def _gdrive_list_ids(self, query_ids, *, name=None): seen_ids.add(file_id) yield item - def _resolve_path( - self, path, cache, mount=None, *, create=False - ) -> _PathMatch: - # Start at the deepest cached folder and only fetch unknown components. + def _match_child(self, cache, parent_ids, path, name, mount=None): + if path == self.base and mount is not None: + return mount, cache + 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 _resolve_prefix(self, path, cache, mount=None): + """Return the deepest existing component, its matches and lookup cache.""" parent = path remaining = [] with self._cache_lock: @@ -486,37 +505,51 @@ def _resolve_path( folders = cache.by_path[parent].copy() if parent else [self.root] match = _PathMatch(folders) for name in reversed(remaining): + child = posixpath.join(parent, name) + found, cache = self._match_child( + cache, 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 + + def _resolve_path(self, path, cache, mount=None) -> _PathMatch: + prefix, match, _ = self._resolve_prefix(path, cache, mount) + return match if prefix == path else _PathMatch([]) + + def _create_missing_dirs(self, path, parent, folders, cache): + # The prefix lookup already established that the first child is missing. + names = path[len(parent) :].lstrip("/").split("/") + for index, name in enumerate(names): parent = posixpath.join(parent, name) - if parent == self.base and mount is not None: - match = mount - else: - match = _PathMatch([]) - for item in self._gdrive_list_ids(folders, name=name): - # Drive matches case-insensitively. - if item["name"] != name: - continue - if item["mimeType"] == FOLDER_MIME_TYPE: - match.folders.append(item["id"]) - else: - match.files.append(item) - cache = self._cache_path_id(cache, parent, *match.folders) - if create and not match.folders: + if index: + match, cache = self._match_child(cache, folders, parent, name) + if match.folders: + folders = match.folders + continue if match.files: raise NotADirectoryError(posixpath.join(self.root, parent)) - match = _PathMatch( - [self._create_dir(cache, min(folders), name, parent)] - ) - if not match.folders and parent != path: - return _PathMatch([]) - folders = match.folders - return match + folders = [self._create_dir(cache, min(folders), name, parent)] + return folders def _path_to_item_ids(self, path, create=False): if not path: return [self.root] - return self._resolve_path( - path, *self._directory_cache(), create=create - ).ids + prefix, match, cache = self._resolve_prefix( + path, *self._directory_cache() + ) + if create: + if not match.folders: + raise NotADirectoryError(posixpath.join(self.root, prefix)) + if prefix != path: + return self._create_missing_dirs( + path, prefix, match.folders, cache + ) + return match.folders + return match.ids if prefix == path else [] def _get_item_id(self, path, create=False): _, base = self._split_mounted_path(path) @@ -537,15 +570,20 @@ def _gdrive_create_dir(self, parent_id, name): item.Upload() return item - @wrap_with(threading.RLock()) def _create_dir(self, cache, parent_id, name, remote_path): + # Wait only for creates of the same name in the same Drive parent. + key = (parent_id, name) with self._cache_lock: - if cached := cache.by_path.get(remote_path): - return cached[0] - item = self._gdrive_create_dir(parent_id, name) - self._cache_path_id(cache, remote_path, item["id"]) - - return item["id"] + lock = self._creation_locks.get(key) + if lock is None: + lock = self._creation_locks[key] = threading.RLock() + with lock: + with self._cache_lock: + if cached := cache.by_path.get(remote_path): + return cached[0] + item = self._gdrive_create_dir(parent_id, name) + self._cache_path_id(cache, remote_path, item["id"]) + return item["id"] def exists(self, path): root, base = self._split_mounted_path(path) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 0c44a6e..2c92e86 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -1,6 +1,8 @@ import json import re import tempfile +from concurrent.futures import ThreadPoolExecutor +from threading import Event from urllib.parse import urlsplit import pytest @@ -320,6 +322,47 @@ def invalidate(request): assert "'new-child' in parents" in parents +@pytest.mark.parametrize("other_instance", [True, False]) +def test_unrelated_folder_creates_can_overlap(mock_drive, other_instance): + first_create, release = Event(), Event() + source = {"id": "src", "name": "src", "mimeType": "text/plain"} + + def hold_first(request): + if request[1] == "POST" and not request[0].split("?")[0].endswith( + "/copy" + ): + first_create.set() + assert release.wait(10) + + def setup(name, hook=None): + drive, _ = mock_drive( + listing(source), + listing(), + response({"id": name}), + response({"id": "copied"}), + on_request=hook, + ) + return filesystem(drive), drive.auth.thread_local.http + + first, first_http = setup("one", hold_first) + other, other_http = setup("two") + + def copy(fs, http, name): + fs.client.auth.thread_local.http = http + fs.cp_file("root/src", f"root/{name}/copy") + + with ThreadPoolExecutor(max_workers=2) as pool: + pending = pool.submit(copy, first, first_http, "one") + try: + assert first_create.wait(5) + pool.submit( + copy, other if other_instance else first, other_http, "two" + ).result(timeout=5) + finally: + release.set() + pending.result(timeout=5) + + def test_invalidating_an_unopened_mount_needs_no_drive_request(mock_drive): drive, requests = mock_drive() filesystem(drive, "root/parent/mount").invalidate_cache("root/parent") From 156e028a92657f242f2edeee01f85ecc10f02bb7 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Tue, 24 Nov 2026 18:32:59 -0800 Subject: [PATCH 16/19] Serialize folder lookup and creation across cache invalidation --- pydrive2/fs/spec.py | 66 +++++++++++++++++------------------ pydrive2/test/test_fs_unit.py | 58 ++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+), 33 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 0559ea6..c820006 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -494,8 +494,7 @@ def _match_child(self, cache, parent_ids, path, name, mount=None): match.files.append(item) return match, self._cache_path_id(cache, path, *match.folders) - def _resolve_prefix(self, path, cache, mount=None): - """Return the deepest existing component, its matches and lookup cache.""" + def _cached_prefix(self, path, cache): parent = path remaining = [] with self._cache_lock: @@ -503,8 +502,13 @@ def _resolve_prefix(self, path, cache, mount=None): 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) match = _PathMatch(folders) - for name in reversed(remaining): + for name in remaining: child = posixpath.join(parent, name) found, cache = self._match_child( cache, match.folders, child, name, mount @@ -520,36 +524,26 @@ def _resolve_path(self, path, cache, mount=None) -> _PathMatch: prefix, match, _ = self._resolve_prefix(path, cache, mount) return match if prefix == path else _PathMatch([]) - def _create_missing_dirs(self, path, parent, folders, cache): - # The prefix lookup already established that the first child is missing. - names = path[len(parent) :].lstrip("/").split("/") - for index, name in enumerate(names): + def _ensure_dirs(self, path, cache, mount=None): + parent, folders, remaining = self._cached_prefix(path, cache) + for name in remaining: parent = posixpath.join(parent, name) - if index: - match, cache = self._match_child(cache, folders, parent, name) - if match.folders: - folders = match.folders - continue - if match.files: - raise NotADirectoryError(posixpath.join(self.root, parent)) - folders = [self._create_dir(cache, min(folders), name, parent)] - return folders + match, cache = self._get_or_create_child( + cache, folders, parent, name, mount + ) + if not match.folders: + raise NotADirectoryError(posixpath.join(self.root, parent)) + folders = match.folders + return folders, cache def _path_to_item_ids(self, path, create=False): if not path: return [self.root] - prefix, match, cache = self._resolve_prefix( - path, *self._directory_cache() - ) + cache, mount = self._directory_cache() if create: - if not match.folders: - raise NotADirectoryError(posixpath.join(self.root, prefix)) - if prefix != path: - return self._create_missing_dirs( - path, prefix, match.folders, cache - ) - return match.folders - return match.ids if prefix == path else [] + folders, _ = self._ensure_dirs(path, cache, mount) + return folders + return self._resolve_path(path, cache, mount).ids def _get_item_id(self, path, create=False): _, base = self._split_mounted_path(path) @@ -570,8 +564,8 @@ def _gdrive_create_dir(self, parent_id, name): item.Upload() return item - def _create_dir(self, cache, parent_id, name, remote_path): - # Wait only for creates of the same name in the same Drive parent. + def _get_or_create_child(self, cache, parents, path, name, mount=None): + parent_id = min(parents) key = (parent_id, name) with self._cache_lock: lock = self._creation_locks.get(key) @@ -579,11 +573,17 @@ def _create_dir(self, cache, parent_id, name, remote_path): lock = self._creation_locks[key] = threading.RLock() with lock: with self._cache_lock: - if cached := cache.by_path.get(remote_path): - return cached[0] + if cached := cache.by_path.get(path): + return _PathMatch(cached.copy()), cache + # 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) + if match.folders or match.files: + return match, cache item = self._gdrive_create_dir(parent_id, name) - self._cache_path_id(cache, remote_path, item["id"]) - return item["id"] + return _PathMatch([item["id"]]), self._cache_path_id( + cache, path, item["id"] + ) def exists(self, path): root, base = self._split_mounted_path(path) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 2c92e86..6ef1c0b 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -363,6 +363,64 @@ def copy(fs, http, name): pending.result(timeout=5) +def test_concurrent_copies_share_a_folder_after_unrelated_invalidation( + mock_drive, +): + creating, release = Event(), Event() + second_started, second_lookup = Event(), Event() + source = {"id": "src", "name": "src", "mimeType": "text/plain"} + + def pause_create(request): + if request[1] == "POST" and json.loads(request[2]).get("mimeType"): + creating.set() + assert release.wait(5) + + def observe_lookup(request): + q = query(request).get("q", [""])[0] + if "name='src'" in q: + second_started.set() + if "name='ab'" in q: + second_lookup.set() + + first, first_requests = mock_drive( + listing(source), + listing(), + response({"id": "AB"}), + response({"id": "first-copy"}), + on_request=pause_create, + ) + second, second_requests = mock_drive( + listing(source), + listing(folder("ab", "AB")), + response({"id": "second-copy"}), + on_request=observe_lookup, + ) + fs = filesystem(first) + + def copy(http, name): + fs.client.auth.thread_local.http = http + fs.cp_file("root/src", f"root/ab/{name}") + + with ThreadPoolExecutor(max_workers=2) as pool: + one = pool.submit(copy, first.auth.thread_local.http, "one") + try: + assert creating.wait(5) + 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. + assert not second_lookup.wait(0.1) + finally: + release.set() + one.result(timeout=5) + two.result(timeout=5) + + 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"] + + def test_invalidating_an_unopened_mount_needs_no_drive_request(mock_drive): drive, requests = mock_drive() filesystem(drive, "root/parent/mount").invalidate_cache("root/parent") From a7ab4b2d97655225ad81328642abb19b2408674a Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 25 Nov 2026 13:23:08 -0800 Subject: [PATCH 17/19] Invalidate rediscovered folder paths and keep traversal lookups warm --- pydrive2/fs/spec.py | 38 ++++++++++++++++-------- pydrive2/test/test_fs_unit.py | 56 +++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 13 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index c820006..dd2c8a4 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -356,7 +356,7 @@ def _directory_cache(self): cache = self._directory_ids if cache.mount_checked: return cache, None - mount = self._resolve_path(self.base, cache) + mount, cache = self._resolve_path(self.base, cache) if not mount.ids: raise FileNotFoundError( errno.ENOENT, @@ -408,10 +408,15 @@ def _invalidate_paths(self, *paths): subtrees ) - def _is_cached_directory(self, item_id): + def _invalidate_folder(self, item_id, *paths, known_folder=False): with self._cache_lock: - cache = self._directory_ids - return item_id == self.root or item_id in cache.by_id + # 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)) @cached_property def _list_params(self): @@ -520,9 +525,11 @@ def _resolve_prefix(self, path, cache, mount=None): break return parent, match, cache - def _resolve_path(self, path, cache, mount=None) -> _PathMatch: - prefix, match, _ = self._resolve_prefix(path, cache, mount) - return match if prefix == path else _PathMatch([]) + 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 _ensure_dirs(self, path, cache, mount=None): parent, folders, remaining = self._cached_prefix(path, cache) @@ -543,7 +550,8 @@ def _path_to_item_ids(self, path, create=False): if create: folders, _ = self._ensure_dirs(path, cache, mount) return folders - return self._resolve_path(path, cache, mount).ids + match, _ = self._resolve_path(path, cache, mount) + return match.ids def _get_item_id(self, path, create=False): _, base = self._split_mounted_path(path) @@ -687,10 +695,10 @@ def _walk_folders(self, base, start_ids, cache): def find(self, path, detail=False, **kwargs): root, base = self._split_mounted_path(path) cache, mount = self._directory_cache() - dirs = self._resolve_path(base, cache, mount).folders + match, cache = self._resolve_path(base, cache, mount) contents = [ _file_entry(posixpath.join(root, name), item) - for name, item in self._walk_folders(base, dirs, cache) + for name, item in self._walk_folders(base, match.folders, cache) if item["mimeType"] != FOLDER_MIME_TYPE ] if detail: @@ -765,7 +773,12 @@ def mv(self, path1, path2, maxdepth=None, **kwargs): file1.Upload() if file1.get("mimeType") == FOLDER_MIME_TYPE: - self._invalidate_paths(path1, posixpath.join(dst_parent, dst_name)) + self._invalidate_folder( + file1_id, + path1, + posixpath.join(dst_parent, dst_name), + known_folder=True, + ) def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): with _translate_not_found(rpath): @@ -823,8 +836,7 @@ def _gdrive_open_file(self, item_id, block_size=None): def rm_file(self, path): item_id = self._get_item_id(path) self._gdrive_delete_file(item_id) - if self._is_cached_directory(item_id): - self.invalidate_cache(path) + self._invalidate_folder(item_id, path) @_gdrive_retry def _gdrive_delete_file(self, item_id): diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 6ef1c0b..f208663 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -439,6 +439,62 @@ def test_rediscovered_directory_id_leaves_its_old_path(mock_drive): assert not fs.exists("root/old") +@pytest.mark.parametrize("operation", ["move", "trash", "delete"]) +def test_folder_mutation_forgets_a_name_discovered_during_the_request( + mock_drive, operation +): + def rediscover(request): + if request[1] in {"PATCH", "DELETE"}: + assert fs.exists("root/other/child") + + drive, requests = mock_drive( + listing(folder("old", "D")), + *([listing()] if operation == "move" else []), + listing(folder("other", "D")), + listing(folder("child", "C")), + response(folder("new", "D")), + listing(), + on_request=rediscover, + ) + fs = filesystem(drive, trash_only=operation != "delete") + assert fs.exists("root/old") + if operation == "move": + fs.mv("root/old", "root/new") + else: + fs.rm_file("root/old") + assert not fs.exists("root/other/child") + assert "name='other'" in query(requests[-1])["q"][0] + + +def test_find_warms_descendants_when_it_rediscovers_a_renamed_folder( + mock_drive, +): + child = dict(folder("child", "C"), parents=["D"]) + note = { + "id": "F", + "name": "note", + "mimeType": "text/plain", + "parents": ["C"], + } + drive, requests = mock_drive( + listing(folder("old", "D")), + listing(folder("new", "D")), + listing(child), + listing(note), + listing(child, note), + ) + fs = filesystem(drive) + assert fs.exists("root/old") + assert fs.find("root/new") == ["root/new/child/note"] + before = len(requests) + assert fs.find("root/new") == ["root/new/child/note"] + (warm,) = requests[before:] + assert set(re.findall(r"'([^']+)' in parents", query(warm)["q"][0])) == { + "D", + "C", + } + + @pytest.mark.parametrize("duplicate", [False, True]) def test_rediscovered_directory_evicts_old_descendants(mock_drive, duplicate): old = [folder("old", "moved")] From f858c9d5ddb7d29453876274434ae5178d63c73c Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 25 Nov 2026 13:23:08 -0800 Subject: [PATCH 18/19] Validate Drive ID mounts before creating descendants --- pydrive2/fs/spec.py | 28 +++++++++++++++------------- pydrive2/test/test_fs_unit.py | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 47 insertions(+), 15 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 933e42c..6adc2b1 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -615,25 +615,27 @@ def makedirs(self, path, exist_ok=False): def _mkdir(self, path, create_parents, exist_ok): root, base = self._split_mounted_path(path) - if not base: - if root not in {"root", "appDataFolder"}: - metadata = self._get_root_metadata(fresh=True) - if metadata.get("trashed"): - raise FileNotFoundError( - errno.ENOENT, os.strerror(errno.ENOENT), path + with self._cache_lock: + cache = self._directory_ids + cached = cache.mount_checked and base in cache.by_path + if not cached and root not in {"root", "appDataFolder"}: + metadata = self._get_root_metadata(fresh=True) + if metadata.get("trashed"): + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), root + ) + if metadata.get("mimeType") != FOLDER_MIME_TYPE: + if base: + raise NotADirectoryError( + errno.ENOTDIR, os.strerror(errno.ENOTDIR), root ) - if metadata.get("mimeType") != FOLDER_MIME_TYPE: - raise FileExistsError(path) + raise FileExistsError(path) + if not base or cached: if not exist_ok: raise FileExistsError(path) return cache, mount = self._directory_cache() - with self._cache_lock: - if base in cache.by_path: - if not exist_ok: - raise FileExistsError(path) - return parent, name = posixpath.split(base) if create_parents: folders, cache = self._ensure_dirs(parent, cache, mount) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 1c20778..7939a89 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -829,7 +829,7 @@ def test_large_write_after_close_does_not_open_a_tempfile(mock_drive, mocker): def test_makedirs_creates_empty_drive_folders(mock_drive): drive, requests = mock_drive( - response({"driveId": "shared"}), + response({"driveId": "shared", "mimeType": FOLDER_MIME_TYPE}), response({"files": []}), response({"id": "A"}), response({"files": []}), @@ -970,6 +970,36 @@ def test_makedirs_rejects_invalid_mount_id(mock_drive, failure, error): filesystem(drive, "FolderID").makedirs("FolderID", exist_ok=True) +@pytest.mark.parametrize( + "metadata,error", + [ + ({"mimeType": "text/plain"}, NotADirectoryError), + ({"mimeType": FOLDER_MIME_TYPE, "trashed": True}, FileNotFoundError), + ], +) +def test_makedirs_rejects_invalid_parent_id_before_creation( + mock_drive, metadata, error +): + drive, requests = mock_drive( + response(metadata), listing(), response({"id": "sub"}) + ) + with pytest.raises(error): + filesystem(drive, "DriveID").makedirs("DriveID/sub") + assert [request[1] for request in requests] == ["GET"] + + +def test_makedirs_checks_a_previously_valid_mount_before_creating(mock_drive): + root = {"mimeType": FOLDER_MIME_TYPE} + drive, requests = mock_drive( + response(root), response(dict(root, trashed=True)) + ) + fs = filesystem(drive, "FolderID") + fs.makedirs("FolderID", exist_ok=True) + with pytest.raises(FileNotFoundError): + fs.makedirs("FolderID/sub") + assert [request[1] for request in requests] == ["GET", "GET"] + + def test_makedirs_bare_root_is_independent_of_named_mount(mock_drive): drive, requests = mock_drive(response({"mimeType": FOLDER_MIME_TYPE})) filesystem(drive, "FolderID/missing").makedirs("FolderID", exist_ok=True) @@ -979,7 +1009,7 @@ def test_makedirs_bare_root_is_independent_of_named_mount(mock_drive): def test_makedirs_starts_at_cached_mount(mock_drive): drive, requests = mock_drive( - response({"driveId": "shared"}), + response({"driveId": "shared", "mimeType": FOLDER_MIME_TYPE}), listing(folder("a", "a")), listing(folder("b", "b")), listing(), From 4063afab87ee631405521117462ec3a1468a0a47 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 25 Nov 2026 20:17:19 -0800 Subject: [PATCH 19/19] Forget cached descendants when a Drive mount disappears --- pydrive2/fs/spec.py | 36 +++++++++++++++++++---------------- pydrive2/test/test_fs_unit.py | 33 ++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 16 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index d6caf84..1370199 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -445,7 +445,9 @@ def _list_params(self): return params @_gdrive_retry - def _get_root_metadata(self, *, fresh=False): + def _get_root_metadata( + self, *, fresh=False, fields="driveId,mimeType,trashed" + ): cached = self._root_metadata if cached and not fresh: return cached @@ -456,23 +458,21 @@ def _get_root_metadata(self, *, fresh=False): item = self.client.CreateFile({"id": self.root}) try: with _translate_not_found(self.root): - item.FetchMetadata("driveId,mimeType,trashed") + item.FetchMetadata(fields) except FileNotFoundError: with self._cache_lock: if self._root_metadata is cached: - self._root_metadata = {} + self.invalidate_cache(self.root) raise with self._cache_lock: if self._root_metadata is cached: - # Trash status is only valid for the request that observed it. - self._root_metadata = ( - {} - if item.get("trashed") - else { + if item.get("trashed"): + self.invalidate_cache(self.root) + else: + self._root_metadata = { "driveId": item.get("driveId"), "mimeType": item.get("mimeType"), } - ) return item.metadata def _gdrive_list(self, query): @@ -685,14 +685,18 @@ def exists(self, path): else: return True - @_gdrive_retry def info(self, path): - bucket, base = self.split_path(path) - with _translate_not_found(path): - item_id = self._get_item_id(path) - gdrive_file = self.client.CreateFile({"id": item_id}) - fields = _INFO_FIELDS if base else f"{_INFO_FIELDS},trashed" - gdrive_file.FetchMetadata(fields=fields) + bucket, base = self._split_mounted_path(path) + if not base and bucket not in {"root", "appDataFolder"}: + gdrive_file = self._get_root_metadata( + fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}" + ) + else: + with _translate_not_found(path): + item_id = self._get_item_id(path) + gdrive_file = self.client.CreateFile({"id": item_id}) + fields = _INFO_FIELDS if base else f"{_INFO_FIELDS},trashed" + _gdrive_retry(gdrive_file.FetchMetadata)(fields=fields) if not base and gdrive_file.get("trashed"): raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), path diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index fc23a85..542b8b9 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -1089,6 +1089,39 @@ def invalidate(request): fs.makedirs("FolderID", exist_ok=True) +@pytest.mark.parametrize("operation", ["makedirs", "exists"]) +@pytest.mark.parametrize( + "missing", + [ + response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}), + error_response(404, "notFound"), + ], + ids=["trashed", "deleted"], +) +def test_missing_mount_discards_cached_children( + mock_drive, operation, missing +): + drive, requests = mock_drive( + response({"mimeType": FOLDER_MIME_TYPE}), + listing(folder("sub", "S")), + missing, + missing, + ) + fs = filesystem(drive, "FolderID") + fs.makedirs("FolderID/sub", exist_ok=True) + fs.makedirs("FolderID/sub", exist_ok=True) + assert len(requests) == 2 + if operation == "exists": + assert not fs.exists("FolderID") + else: + with pytest.raises(FileNotFoundError): + fs.makedirs("FolderID", exist_ok=True) + with pytest.raises(FileNotFoundError): + fs.makedirs("FolderID/sub", exist_ok=True) + assert len(requests) == 4 + assert all("q" not in query(req) for req in requests[2:]) + + def test_makedirs_after_trashing_and_restoring_the_mount(mock_drive): root = {"mimeType": FOLDER_MIME_TYPE} drive, _ = mock_drive(