Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
800bbf3
Invalidate cached directory IDs after moves and removals
shcheklein Nov 22, 2026
ae0d857
Create Drive directories in mkdir and makedirs
shcheklein Nov 22, 2026
61d2506
Make the directory cache lifecycle explicit
shcheklein Nov 22, 2026
5c8e21d
Invalidate both moved directory paths using Drive metadata
shcheklein Nov 22, 2026
3323a42
Reuse verified directories and resolve mkdir paths from Drive results
shcheklein Nov 22, 2026
689eb82
Keep directory creation on the cache used to resolve its parent
shcheklein Nov 22, 2026
ad9e0e2
Integrate mkdir with directory cache invalidation
shcheklein Nov 22, 2026
89c9518
Exercise directory invalidation through filesystem operations and Dri…
shcheklein Nov 22, 2026
7a95a64
Merge branch 'fix/fs-directory-cache-invalidation' into fix/fs-create…
shcheklein Nov 22, 2026
adb4a5c
Test mkdir races at the Drive request boundary
shcheklein Nov 22, 2026
93a7ea8
Verify directory cache reuse through public lookups and Drive listings
shcheklein Nov 22, 2026
5c60771
Merge branch 'fix/fs-directory-cache-invalidation' into fix/fs-create…
shcheklein Nov 22, 2026
a79d3a8
Set up the listing test through makedirs
shcheklein Nov 22, 2026
a76d0e8
Share root metadata across directory validation and Drive listings
shcheklein Nov 22, 2026
784b180
Guard the original deep-path Drive call budgets live and offline
shcheklein Nov 23, 2026
6a90a88
Merge branch 'fix/fs-directory-cache-invalidation' into fix/fs-create…
shcheklein Nov 23, 2026
1ec813e
Reuse the mount lookup and enforce mkdir request budgets
shcheklein Nov 23, 2026
ef9ef3f
Resolve paths once and evict stale descendants on folder rediscovery
shcheklein Nov 24, 2026
9d7a895
Build mkdir and makedirs on the shared path resolver
shcheklein Nov 24, 2026
4f78e2f
Separate lookup from creation and coordinate creates per Drive parent…
shcheklein Nov 25, 2026
936c89e
Apply mkdir errors only to its target and refresh bare folder status
shcheklein Nov 25, 2026
156e028
Serialize folder lookup and creation across cache invalidation
shcheklein Nov 25, 2026
1187d61
Merge #408 and coordinate mkdir with concurrent uploads
shcheklein Nov 25, 2026
d8cc6d1
Merge main into #408 to pick up latest main
shcheklein Nov 25, 2026
eca73e7
Merge #408 into #409 to pick up latest main
shcheklein Nov 25, 2026
a7ab4b2
Invalidate rediscovered folder paths and keep traversal lookups warm
shcheklein Nov 25, 2026
f858c9d
Validate Drive ID mounts before creating descendants
shcheklein Nov 25, 2026
a8f6127
Merge the cache race fixes from #408
shcheklein Nov 25, 2026
33482d3
Merge main after #408 landed
shcheklein Nov 26, 2026
4063afa
Forget cached descendants when a Drive mount disappears
shcheklein Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 109 additions & 38 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import appdirs
from fsspec.spec import AbstractFileSystem
from funcy import (
cached_property,
chunks,
distinct,
retry,
Expand Down Expand Up @@ -289,6 +288,8 @@ def __init__(
self._cache_lock = threading.RLock()
self._directory_ids = _DirectoryCache()
self._mount_lock = threading.RLock()
self._root_lock = threading.RLock()
self._root_metadata: dict = {}
self._creation_locks: WeakValueDictionary = WeakValueDictionary()
self.path = path
self.root, self.base = self.split_path(self.path)
Expand Down Expand Up @@ -410,6 +411,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 = _DirectoryCache()
else:
Expand All @@ -427,39 +430,50 @@ def _invalidate_folder(self, item_id, *paths, known_folder=False):
return
self._invalidate_paths(*dict.fromkeys(paths))

@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, *, fresh=False, fields="driveId,mimeType,trashed"
):
cached = self._root_metadata
if cached and not fresh:
return cached
with self._root_lock:
cached = self._root_metadata
if cached and not fresh:
return cached
item = self.client.CreateFile({"id": self.root})
try:
with _translate_not_found(self.root):
item.FetchMetadata(fields)
except FileNotFoundError:
with self._cache_lock:
if self._root_metadata is cached:
self.invalidate_cache(self.root)
raise
with self._cache_lock:
if self._root_metadata is cached:
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):
param = {
Expand Down Expand Up @@ -584,7 +598,9 @@ def _gdrive_create_dir(self, parent_id, name):
item.Upload()
return item

def _get_or_create_child(self, cache, parents, path, name, mount=None):
def _get_or_create_child(
self, cache, parents, path, name, mount=None, *, exist_ok=True
):
parent_id = min(parents)
key = (parent_id, name)
with self._cache_lock:
Expand All @@ -593,18 +609,69 @@ def _get_or_create_child(self, cache, parents, path, name, mount=None):
lock = self._creation_locks[key] = threading.RLock()
with lock:
with self._cache_lock:
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)
folders = cache.by_path.get(path, []).copy()
if folders:
match = _PathMatch(folders)
else:
# An invalidation can give two writers different caches. Check
# Drive under the same name lock as the create.
match, cache = self._match_child(
cache, parents, path, name, mount
)
if match.folders or match.files:
if not exist_ok:
raise FileExistsError(posixpath.join(self.root, path))
return match, cache
item = self._gdrive_create_dir(parent_id, name)
return _PathMatch([item["id"]]), self._cache_path_id(
cache, path, 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)
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
)
raise FileExistsError(path)
if not base or cached:
if not exist_ok:
raise FileExistsError(path)
return

cache, mount = self._directory_cache()
parent, name = posixpath.split(base)
if create_parents:
folders, cache = self._ensure_dirs(parent, cache, mount)
else:
prefix, match, cache = self._resolve_prefix(parent, cache, mount)
if not match.folders:
raise NotADirectoryError(posixpath.join(root, prefix))
if prefix != parent:
raise FileNotFoundError(posixpath.join(root, parent))
folders = match.folders
leaf, _ = self._get_or_create_child(
cache, folders, base, name, mount, exist_ok=exist_ok
)
if not leaf.folders:
raise FileExistsError(path)

def exists(self, path):
root, base = self._split_mounted_path(path)
try:
Expand All @@ -618,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
Expand Down
13 changes: 10 additions & 3 deletions pydrive2/test/test_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -169,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()
Expand Down Expand Up @@ -279,7 +286,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)
Expand Down
Loading
Loading