From e13365ffe344bdd262f9533fc3940fc18ab2a4aa Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:29:42 -0800 Subject: [PATCH 1/9] Replace the content of an existing file on a write A write to the path of an existing file added a second file with the same name, and reads then picked one of the two by ID. pipe_file(), put_file() and open(path, "wb") now replace the content of that file, which keeps its ID and sharing. With several files of the name, the one that reads return is replaced. A write to the path of a folder raises IsADirectoryError. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 6 ++- docs/upgrading.rst | 5 ++ pydrive2/fs/spec.py | 30 ++++++++++- pydrive2/test/test_fs.py | 93 +++++++++++++++++++++++++++++++++++ pydrive2/test/test_fs_unit.py | 28 +++++------ 5 files changed, 144 insertions(+), 18 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..74a40e44 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -65,8 +65,10 @@ A filesystem instance is scoped to one root. Use URLs under the same folder ID or root alias in a single ``fsspec.open_files`` call. Sibling URLs reuse the filesystem and its directory ID cache. Reads by file ID skip name lookups. Reads are sequential. To create a file, use a folder ID or root -alias followed by a filename. As with the direct PyDrive2 filesystem, -a write creates a Drive item even when a sibling has the same name. All +alias followed by a filename. Writing to the path of an existing file +replaces its content and keeps the file, with its ID and sharing. When +several files share the name, the write replaces the one that reads +return. Writing to the path of a folder raises ``IsADirectoryError``. All reads require credentials, including files shared by link. Listings diff --git a/docs/upgrading.rst b/docs/upgrading.rst index 9f28692a..d249b587 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -65,6 +65,11 @@ Filesystem directories Both raise ``FileExistsError`` if the folder already exists. Use ``fs.makedirs(path, exist_ok=True)`` when repeating a setup step. +Writing to the path of an existing file, with ``pipe_file()``, +``put_file()`` or ``open(path, "wb")``, now replaces that file's content. +It used to add a second file with the same name. Writing to the path of a +folder raises ``IsADirectoryError``. + The :doc:`fsspec filesystem ` now caches folders returned by ``ls()``. Later calls such as ``exists("root/data")`` can reuse those IDs. If another client moves or removes a folder, list its parent again or diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ac47994b..0c570bea 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1218,15 +1218,43 @@ def find( return contents def upload_fobj(self, stream, rpath, callback=None, **kwargs): + """Write a file. A file already at the path gets the new content.""" parent, name = self._split_file_path(rpath) parent_id = self._get_item_id(parent, create=True) + existing = self._file_to_replace(rpath, parent_id, name) if callback: stream = _ReadProgress(stream, callback.relative_update) with _unwrap_not_retried(): - item = self._gdrive_upload_fobj(name, parent_id, stream) + if existing is None: + item = self._gdrive_upload_fobj(name, parent_id, stream) + else: + item = self._gdrive_replace_content(existing, stream) self._dirs.file_added(parent_id, name) return item + def _file_to_replace(self, path, parent_id, name): + """The ID of the file a write to the path replaces, if there is one.""" + _, base = self._split_mounted_path(path) + match, _ = self._resolver().child( + [parent_id], base, name, folders_only=False + ) + if match.folders: + raise IsADirectoryError( + errno.EISDIR, os.strerror(errno.EISDIR), path + ) + # Reads of a name that several files share use the lowest ID. + return min((file.id for file in match.files), default=None) + + def _gdrive_replace_content(self, file_id, stream): + def send(): + item = self.client.CreateFile({"id": file_id}) + item.content = stream + item.Upload() + return item + + # Sending the same content to the same file again changes nothing. + return _gdrive_retry_repeatable(send)() + def put_file(self, lpath, rpath, callback=None, **kwargs): if os.path.isdir(lpath): self.makedirs(rpath, exist_ok=True) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 1e853a3a..2c209ec9 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -734,3 +734,96 @@ def test_cp_file_of_a_shortcut_after_the_answer_was_lost_leaves_one_copy( fs.cp_file(f"root/{workspace_files}-link", remote_dir + "/copy") assert len(lost) == 1 assert items_below(fs_factory()[0], remote_dir) == ["copy"] + + +@pytest.fixture +def files_in_base(service_auth, fs_factory, base_remote_dir): + """Create files under the base folder with the core API; return IDs.""" + _, base = fs_factory() + drive = GoogleDrive(service_auth) + + def create(name, content): + file = drive.CreateFile({"name": name, "parents": [base["id"]]}) + file.SetContentString(content) + pydrive_retry(file.Upload) + return file["id"] + + return create + + +def content_on_drive(service_auth, file_id): + file = GoogleDrive(service_auth).CreateFile({"id": file_id}) + return b"".join(pydrive_retry(file.GetContentIOBuffer)) + + +def pipe(fs, path, data, tmp_path): + fs.pipe_file(path, data) + + +def put(fs, path, data, tmp_path): + source = tmp_path / "source" + source.write_bytes(data) + fs.put_file(str(source), path) + + +def write_through_open(fs, path, data, tmp_path): + with fs.open(path, "wb") as stream: + stream.write(data) + + +@pytest.mark.parametrize( + ("write", "data"), + [ + (pipe, b"new"), + (write_through_open, b"new"), + # Larger than one request, so the upload is resumable. + (put, os.urandom(2 * 1024 * 1024)), + ], + ids=["pipe_file", "open", "put_file-2MiB"], +) +def test_write_to_a_file_path_replaces_the_content_and_keeps_the_file( + service_auth, + fs, + fs_factory, + base_remote_dir, + files_in_base, + tmp_path, + write, + data, +): + name = uuid.uuid4().hex + path = f"{base_remote_dir}/{name}" + file_id = files_in_base(name, "old") + + write(fs, path, data, tmp_path) + + assert content_on_drive(service_auth, file_id) == data + listed = fs_factory()[0].ls(base_remote_dir) + assert listed.count(path) == 1 + + +def test_write_to_a_path_two_files_share_replaces_the_one_reads_return( + service_auth, fs, fs_factory, base_remote_dir, files_in_base +): + name = uuid.uuid4().hex + path = f"{base_remote_dir}/{name}" + files = { + files_in_base(name, "one"): b"one", + files_in_base(name, "two"): b"two", + } + read_id, other_id = sorted(files) + + fs.pipe_file(path, b"new") + + assert fs_factory()[0].cat_file(path) == b"new" + assert content_on_drive(service_auth, read_id) == b"new" + assert content_on_drive(service_auth, other_id) == files[other_id] + + +def test_write_to_a_folder_path_raises_and_creates_no_file( + fs, fs_factory, remote_dir +): + fs.makedirs(remote_dir + "/dir") + with pytest.raises(IsADirectoryError): + fs.pipe_file(remote_dir + "/dir", b"data") + assert fs_factory()[0].ls(remote_dir) == [remote_dir + "/dir/"] diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index d9492b21..64e93024 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -889,6 +889,7 @@ def test_warm_calls_below_a_folder_with_a_same_name_file_reuse_its_id( listing(sub), listing(note), listing(note), + listing(), # No file of that name yet. response({"id": "uploaded"}), ) fs = filesystem(drive, mount) @@ -901,7 +902,7 @@ def test_warm_calls_below_a_folder_with_a_same_name_file_reuse_its_id( ["('S' in parents) and trashed=false and name='note'"] ] fs.touch("root/data/uploaded") - assert [req[1] for req in requests[before + 1 :]] == ["POST"] + assert [req[1] for req in requests[before + 1 :]] == ["GET", "POST"] def test_find_caches_only_the_new_path_for_a_folder_moved_between_batches( @@ -1124,11 +1125,6 @@ def list_after_lookup_starts(request): @pytest.mark.parametrize( ("write", "responses"), [ - pytest.param( - lambda fs: fs.touch("root/dest/item"), - [response(WRITTEN_FILE)], - id="touch", - ), pytest.param( lambda fs: fs.cp_file("root/source", "root/dest/item"), [ @@ -1446,6 +1442,7 @@ def test_nested_file_operations_reuse_resolved_directories(mock_drive): response(b), listing(), response(c), + listing(), # No file of that name yet. response({"id": "file"}), listing(file), listing(a), @@ -1458,14 +1455,10 @@ def test_nested_file_operations_reuse_resolved_directories(mock_drive): leaf = parent + "/a/b/c" path = leaf + "/test.txt" fs.touch(path) - assert [r[1] for r in requests] == [ - "GET", - *(["GET", "POST"] * 4), - "POST", - ] + assert [r[1] for r in requests] == ["GET", *(["GET", "POST"] * 5)] assert [ query(r)["q"][0].split("name=")[-1] for r in requests if r[1] == "GET" - ] == ["'mount'", "'run'", "'a'", "'b'", "'c'"] + ] == ["'mount'", "'run'", "'a'", "'b'", "'c'", "'test.txt'"] for operation, target, expected in ( (fs.exists, path, True), @@ -2218,6 +2211,7 @@ def pause_create(request): listing(), response(directory), on_request=pause_create ) drive, requests = mock_drive( + listing(), # The folder has not been created yet. response(file), listing(file, directory), ({"status": "200", "content-length": "1"}, b"x"), @@ -2970,7 +2964,10 @@ def send(request): "", ) drive, _ = mock_drive( - *[session] * attempts, response({"id": "file"}), on_request=send + listing(), + *[session] * attempts, + response({"id": "file"}), + on_request=send, ) progress = ProgressSteps() filesystem(drive).put_file(str(source), "root/source", callback=progress) @@ -3001,6 +2998,7 @@ def test_recursive_put_uploads_files_and_creates_empty_folders( listing(), listing(), response({"id": "U"}), + listing(), # No a.txt in the new folder. response({"id": "A"}), listing(), response({"id": "E"}), @@ -3957,7 +3955,7 @@ def fail(size, value): reports.append(value) raise TimeoutError("The progress report timed out") - drive, requests = mock_drive() + drive, requests = mock_drive(listing()) with pytest.raises(TimeoutError, match="progress report"): filesystem(drive).upload_fobj( io.BytesIO(b"data"), @@ -3965,7 +3963,7 @@ def fail(size, value): callback=Callback(hooks={"f": fail}), ) assert reports == [4] - assert requests == [] + assert [r[1] for r in requests] == ["GET"] sleep.assert_not_called() From e085164a7cd801e483223ec6a5f1f39eb0542446 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:29:56 -0800 Subject: [PATCH 2/9] Count the file name lookup in the request count of a write Co-Authored-By: Claude Opus 5.5 --- pydrive2/test/test_fs.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 2c209ec9..a417cc1a 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -238,7 +238,8 @@ def record_listing(request, *args, **kwargs): leaf = remote_dir + "/a/b/c" path = leaf + "/test.txt" fs.touch(path) - assert len(queries) == 5 + # One lookup for each missing folder, and one for the file name. + assert len(queries) == 6 for operation, target, expected in ( (fs.exists, path, True), From f0a6896468b4db1d3faf2e2a01b61620357a7062 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 11:07:33 -0800 Subject: [PATCH 3/9] Find the file to replace under every same-name parent, one write at a time A write looks for an existing file under all folders that share the parent path, as reads do. Threads of one filesystem that write the same path take turns, so they no longer create two files. A replace keeps the file's type, and a write onto a Google Docs file or a shortcut raises PermissionError before sending anything. A file deleted between the lookup and the replace raises FileNotFoundError. The live tests work in their own folder and cover an empty write, a lost answer to a replace, and two same-name parent folders. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 12 ++- docs/upgrading.rst | 3 +- pydrive2/fs/spec.py | 71 ++++++++++++----- pydrive2/test/test_fs.py | 144 +++++++++++++++++++++++++--------- pydrive2/test/test_fs_unit.py | 98 ++++++++++++++++------- 5 files changed, 238 insertions(+), 90 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 74a40e44..a90e2f49 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -66,10 +66,14 @@ ID or root alias in a single ``fsspec.open_files`` call. Sibling URLs reuse the filesystem and its directory ID cache. Reads by file ID skip name lookups. Reads are sequential. To create a file, use a folder ID or root alias followed by a filename. Writing to the path of an existing file -replaces its content and keeps the file, with its ID and sharing. When -several files share the name, the write replaces the one that reads -return. Writing to the path of a folder raises ``IsADirectoryError``. All -reads require credentials, including files shared by link. +replaces its content and keeps the file, with its ID, type and sharing. +When several files share the path, the write replaces the one that reads +return. Writing to the path of a folder raises ``IsADirectoryError``, and +to the path of a Google Docs file or a shortcut ``PermissionError``. +Threads that write one path through the same filesystem instance take +turns. Other instances and other clients do not wait, so two of them can +still create two files with the same name. All reads require credentials, +including files shared by link. Listings -------- diff --git a/docs/upgrading.rst b/docs/upgrading.rst index d249b587..967d4fba 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -68,7 +68,8 @@ Both raise ``FileExistsError`` if the folder already exists. Use Writing to the path of an existing file, with ``pipe_file()``, ``put_file()`` or ``open(path, "wb")``, now replaces that file's content. It used to add a second file with the same name. Writing to the path of a -folder raises ``IsADirectoryError``. +folder raises ``IsADirectoryError``, and to the path of a Google Docs file +or a shortcut ``PermissionError``. The :doc:`fsspec filesystem ` now caches folders returned by ``ls()``. Later calls such as ``exists("root/data")`` can reuse those IDs. diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 0c570bea..d61a5b55 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -50,6 +50,8 @@ _LIST_FIELDS = ( f"nextPageToken,incompleteSearch,files(id,name,parents,{_INFO_FIELDS})" ) +# Folders, Google Docs, Sheets and the like, and shortcuts. +_WORKSPACE_TYPE_PREFIX = "application/vnd.google-apps." _NAME_FIELDS = "nextPageToken,incompleteSearch,files(id,name,parents,mimeType)" _MAX_QUERY_TERMS = 50 _CONNECTION_RETRIES = 3 @@ -86,7 +88,7 @@ class _ListedChild: id: str parent: str | None name: str - is_folder: bool + mime_type: str ambiguous: bool size: int | None checksum: str | None @@ -98,12 +100,17 @@ def from_drive(cls, parent, item): id=item["id"], parent=parent, name=item["name"], - is_folder=item["mimeType"] == FOLDER_MIME_TYPE, + # Listed items share a few types, so they share the strings. + mime_type=sys.intern(item["mimeType"]), ambiguous=len(item.get("parents", ())) > 1, size=int(size) if size is not None else None, checksum=item.get("md5Checksum"), ) + @property + def is_folder(self): + return self.mime_type == FOLDER_MIME_TYPE + def entry(self, name, detail=True): if not detail: return name @@ -1219,35 +1226,57 @@ def find( def upload_fobj(self, stream, rpath, callback=None, **kwargs): """Write a file. A file already at the path gets the new content.""" + _, base = self._split_mounted_path(rpath) parent, name = self._split_file_path(rpath) - parent_id = self._get_item_id(parent, create=True) - existing = self._file_to_replace(rpath, parent_id, name) + _, parent_base = self._split_mounted_path(parent) + resolver = self._resolver() + parents = ( + resolver.directory(parent_base, create=True).folders + if parent_base + else [self.root] + ) + parent_id = min(parents) if callback: stream = _ReadProgress(stream, callback.relative_update) - with _unwrap_not_retried(): - if existing is None: - item = self._gdrive_upload_fobj(name, parent_id, stream) - else: - item = self._gdrive_replace_content(existing, stream) - self._dirs.file_added(parent_id, name) - return item - - def _file_to_replace(self, path, parent_id, name): - """The ID of the file a write to the path replaces, if there is one.""" - _, base = self._split_mounted_path(path) - match, _ = self._resolver().child( - [parent_id], base, name, folders_only=False - ) + # Threads of this filesystem that write the same path take turns. + with self._creation_lock(parent_id, name): + existing = self._file_to_replace( + resolver, rpath, base, parents, name + ) + with _unwrap_not_retried(): + if existing is None: + item = self._gdrive_upload_fobj(name, parent_id, stream) + self._dirs.file_added(parent_id, name) + return item + with _translate_not_found(rpath): + return self._gdrive_replace_content(existing, stream) + + def _file_to_replace(self, resolver, path, base, parents, name): + """The file a write to the path replaces, as reads find it.""" + match, _ = resolver.child(parents, base, name, folders_only=False) if match.folders: raise IsADirectoryError( errno.EISDIR, os.strerror(errno.EISDIR), path ) + if not match.files: + return None # Reads of a name that several files share use the lowest ID. - return min((file.id for file in match.files), default=None) + existing = min(match.files, key=attrgetter("id")) + if existing.mime_type.startswith(_WORKSPACE_TYPE_PREFIX): + raise PermissionError( + errno.EPERM, + "Drive cannot replace a Google Workspace file or a " + "shortcut with bytes", + path, + ) + return existing - def _gdrive_replace_content(self, file_id, stream): + def _gdrive_replace_content(self, existing, stream): def send(): - item = self.client.CreateFile({"id": file_id}) + # Without the type, Drive sets it from the uploaded content. + item = self.client.CreateFile( + {"id": existing.id, "mimeType": existing.mime_type} + ) item.content = stream item.Upload() return item diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index a417cc1a..194d7931 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -13,6 +13,7 @@ from googleapiclient.http import HttpRequest from pydrive2.drive import GoogleDrive +from pydrive2.files import FOLDER_MIME_TYPE from pydrive2.fs import GDriveFileSystem from pydrive2.test.test_util import ( GDRIVE_USER_CREDENTIALS_DATA, @@ -737,19 +738,25 @@ def test_cp_file_of_a_shortcut_after_the_answer_was_lost_leaves_one_copy( assert items_below(fs_factory()[0], remote_dir) == ["copy"] -@pytest.fixture -def files_in_base(service_auth, fs_factory, base_remote_dir): - """Create files under the base folder with the core API; return IDs.""" - _, base = fs_factory() - drive = GoogleDrive(service_auth) - - def create(name, content): - file = drive.CreateFile({"name": name, "parents": [base["id"]]}) +def create_on_drive(service_auth, parent_id, name, content=None, **extra): + """Create a file, or a folder without content, as another client would.""" + metadata = {"name": name, "parents": [parent_id], **extra} + if content is None: + metadata["mimeType"] = FOLDER_MIME_TYPE + file = GoogleDrive(service_auth).CreateFile(metadata) + if content is not None: file.SetContentString(content) - pydrive_retry(file.Upload) - return file["id"] + pydrive_retry(file.Upload) + return file["id"] - return create + +@pytest.fixture +def remote_dir_id(service_auth, fs_factory, remote_dir): + """Create remote_dir with the core API and return its ID.""" + _, base = fs_factory() + return create_on_drive( + service_auth, base["id"], posixpath.basename(remote_dir) + ) def content_on_drive(service_auth, file_id): @@ -757,6 +764,18 @@ def content_on_drive(service_auth, file_id): return b"".join(pydrive_retry(file.GetContentIOBuffer)) +def metadata_on_drive(service_auth, file_id, fields): + file = GoogleDrive(service_auth).CreateFile({"id": file_id}) + pydrive_retry(file.FetchMetadata, fields=fields) + return file + + +def ids_in(service_auth, folder_id): + query = f"'{folder_id}' in parents and trashed=false" + listing = GoogleDrive(service_auth).ListFile({"q": query}) + return [item["id"] for item in pydrive_retry(listing.GetList)] + + def pipe(fs, path, data, tmp_path): fs.pipe_file(path, data) @@ -773,54 +792,99 @@ def write_through_open(fs, path, data, tmp_path): @pytest.mark.parametrize( - ("write", "data"), + ("write", "size"), [ - (pipe, b"new"), - (write_through_open, b"new"), + (pipe, 3), + (write_through_open, 3), # Larger than one request, so the upload is resumable. - (put, os.urandom(2 * 1024 * 1024)), + (put, 2 * 1024 * 1024), ], ids=["pipe_file", "open", "put_file-2MiB"], ) def test_write_to_a_file_path_replaces_the_content_and_keeps_the_file( - service_auth, - fs, - fs_factory, - base_remote_dir, - files_in_base, - tmp_path, - write, - data, + service_auth, fs, remote_dir, remote_dir_id, tmp_path, write, size ): - name = uuid.uuid4().hex - path = f"{base_remote_dir}/{name}" - file_id = files_in_base(name, "old") + data = (b"0123456789abcdef" * (size // 16 + 1))[:size] + file_id = create_on_drive( + service_auth, + remote_dir_id, + "a.json", + "{}", + mimeType="application/json", + ) - write(fs, path, data, tmp_path) + write(fs, remote_dir + "/a.json", data, tmp_path) + assert ids_in(service_auth, remote_dir_id) == [file_id] assert content_on_drive(service_auth, file_id) == data - listed = fs_factory()[0].ls(base_remote_dir) - assert listed.count(path) == 1 + kept = metadata_on_drive(service_auth, file_id, "mimeType") + assert kept["mimeType"] == "application/json" + + +@pytest.mark.parametrize( + "write", + [ + lambda fs, path: fs.touch(path), + lambda fs, path: fs.pipe_file(path, b""), + ], + ids=["touch", "pipe_file"], +) +def test_empty_write_to_a_file_path_empties_the_file( + service_auth, fs, remote_dir, remote_dir_id, write +): + file_id = create_on_drive(service_auth, remote_dir_id, "file", "old") + + write(fs, remote_dir + "/file") + + assert ids_in(service_auth, remote_dir_id) == [file_id] + assert content_on_drive(service_auth, file_id) == b"" def test_write_to_a_path_two_files_share_replaces_the_one_reads_return( - service_auth, fs, fs_factory, base_remote_dir, files_in_base + service_auth, fs, fs_factory, remote_dir, remote_dir_id ): - name = uuid.uuid4().hex - path = f"{base_remote_dir}/{name}" files = { - files_in_base(name, "one"): b"one", - files_in_base(name, "two"): b"two", + create_on_drive(service_auth, remote_dir_id, "file", "one"): b"one", + create_on_drive(service_auth, remote_dir_id, "file", "two"): b"two", } read_id, other_id = sorted(files) - fs.pipe_file(path, b"new") + fs.pipe_file(remote_dir + "/file", b"new") - assert fs_factory()[0].cat_file(path) == b"new" + assert fs_factory()[0].cat_file(remote_dir + "/file") == b"new" assert content_on_drive(service_auth, read_id) == b"new" assert content_on_drive(service_auth, other_id) == files[other_id] +def test_write_below_two_folders_with_one_name_replaces_the_file_in_either( + service_auth, fs, remote_dir, remote_dir_id +): + folders = sorted( + create_on_drive(service_auth, remote_dir_id, "dup") for _ in range(2) + ) + # Writes would create a new file in the folder with the lower ID. + file_id = create_on_drive(service_auth, folders[1], "file", "old") + + fs.pipe_file(remote_dir + "/dup/file", b"new") + + assert ids_in(service_auth, folders[0]) == [] + assert ids_in(service_auth, folders[1]) == [file_id] + assert content_on_drive(service_auth, file_id) == b"new" + + +def test_replace_after_drive_did_it_and_the_answer_was_lost_keeps_one_file( + service_auth, fs, remote_dir, remote_dir_id, lose_answers +): + file_id = create_on_drive(service_auth, remote_dir_id, "file", "old") + lost = lose_answers("PATCH", "") + + fs.pipe_file(remote_dir + "/file", b"new") + + assert len(lost) == 1 + assert ids_in(service_auth, remote_dir_id) == [file_id] + assert content_on_drive(service_auth, file_id) == b"new" + + def test_write_to_a_folder_path_raises_and_creates_no_file( fs, fs_factory, remote_dir ): @@ -828,3 +892,11 @@ def test_write_to_a_folder_path_raises_and_creates_no_file( with pytest.raises(IsADirectoryError): fs.pipe_file(remote_dir + "/dir", b"data") assert fs_factory()[0].ls(remote_dir) == [remote_dir + "/dir/"] + + +@pytest.mark.parametrize("suffix", ["", "-link"], ids=["doc", "shortcut"]) +def test_write_to_a_google_doc_or_shortcut_path_raises_permission_error( + fs, workspace_files, suffix +): + with pytest.raises(PermissionError): + fs.pipe_file(f"root/{workspace_files}{suffix}", b"data") diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 64e93024..b82a687f 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -7,6 +7,7 @@ import ssl import sys import tempfile +import time import tracemalloc from concurrent.futures import ThreadPoolExecutor from http.client import IncompleteRead @@ -2195,46 +2196,87 @@ def test_rmdir_checks_emptiness_again_after_transient_failure(mock_drive): assert [r[1] for r in requests] == ["GET", "GET", "DELETE", "GET"] -def test_upload_while_mkdir_is_waiting_for_drive_keeps_both_matches( - mock_drive, -): +def reporting(http, on_request): + """A mock connection that reports each request before answering it.""" + http.on_request = on_request + return http + + +def run_while_paused(first, second, pause_method): + """Start second while first waits for Drive's answer to pause_method. + + Return the methods second sent before first was answered. + """ started, release = Event(), Event() + early = [] - def pause_create(request): - if request[1] == "POST": + def pause(request): + if request[1] == pause_method: started.set() assert release.wait(5) - directory = folder("item", "Z") - file = {"id": "A", "name": "item", "mimeType": "text/plain"} - creator, _ = mock_drive( - listing(), response(directory), on_request=pause_create - ) - drive, requests = mock_drive( - listing(), # The folder has not been created yet. - response(file), - listing(file, directory), - ({"status": "200", "content-length": "1"}, b"x"), - ) - fs = filesystem(drive) - http = creator.auth.thread_local.http + def record(request): + if not release.is_set(): + early.append(request[1]) - def create(): - drive.auth.thread_local.http = http - fs.mkdir("root/item") - - with ThreadPoolExecutor(max_workers=1) as pool: - pending = pool.submit(create) + with ThreadPoolExecutor(max_workers=2) as pool: + pending = pool.submit(first, pause) try: assert started.wait(5) - fs.touch("root/item") + later = pool.submit(second, record) + # Give the second thread time to send a request if it can. + time.sleep(0.2) finally: release.set() pending.result(timeout=5) + return early, later - with fs.open("root/item", "rb") as stream: - assert stream.read() == b"x" - assert urlsplit(requests[-1][0]).path.endswith("/files/A") + +def test_write_waits_for_mkdir_of_the_same_name_and_raises_is_a_directory_error( + mock_drive, +): + creator, _ = mock_drive(listing(), response(folder("item", "Z"))) + writer, _ = mock_drive() + fs = filesystem(creator) + threads = creator.auth.thread_local + creator_http = creator.auth.thread_local.http + writer_http = writer.auth.thread_local.http + + def make_folder(on_request): + threads.http = reporting(creator_http, on_request) + fs.mkdir("root/item") + + def write(on_request): + threads.http = reporting(writer_http, on_request) + fs.touch("root/item") + + early, later = run_while_paused(make_folder, write, "POST") + assert early == [] + with pytest.raises(IsADirectoryError): + later.result(timeout=5) + + +def test_two_threads_writing_one_new_path_create_one_file(mock_drive): + file = {"id": "A", "name": "new", "mimeType": "text/plain"} + first, _ = mock_drive(listing(), response(file)) + second, second_requests = mock_drive(listing(file), response(file)) + fs = filesystem(first) + threads = first.auth.thread_local + first_http = first.auth.thread_local.http + second_http = second.auth.thread_local.http + + def write_first(on_request): + threads.http = reporting(first_http, on_request) + fs.pipe_file("root/new", b"one") + + def write_second(on_request): + threads.http = reporting(second_http, on_request) + fs.pipe_file("root/new", b"two") + + early, later = run_while_paused(write_first, write_second, "POST") + later.result(timeout=5) + assert early == [] + assert [r[1] for r in second_requests] == ["GET", "PATCH"] def overlap_requests( From 9d7553317fa4c4746eb46b8fc8ab67f6ff8ed066 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 4 Dec 2026 12:29:39 -0800 Subject: [PATCH 4/9] Replace only files the filesystem knows, without a lookup per write A write no longer looks the name up on Drive. It replaces a file this filesystem wrote, copied or found by its path (exists, info, a read), and otherwise creates a new file in one request, as before. The filesystem keeps the latest 10,000 such files, about 350 bytes each; listings add none. If the known file was deleted, trashed, moved or renamed by another client, the write creates a new file at the path. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 34 +++++--- docs/upgrading.rst | 13 +-- pydrive2/fs/cache.py | 43 +++++++++- pydrive2/fs/spec.py | 109 ++++++++++++++++--------- pydrive2/test/test_fs.py | 146 +++++++++++++++++++++++++++++++--- pydrive2/test/test_fs_unit.py | 47 +++++++---- 6 files changed, 315 insertions(+), 77 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index a90e2f49..b4aa34f4 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -65,15 +65,29 @@ A filesystem instance is scoped to one root. Use URLs under the same folder ID or root alias in a single ``fsspec.open_files`` call. Sibling URLs reuse the filesystem and its directory ID cache. Reads by file ID skip name lookups. Reads are sequential. To create a file, use a folder ID or root -alias followed by a filename. Writing to the path of an existing file -replaces its content and keeps the file, with its ID, type and sharing. -When several files share the path, the write replaces the one that reads -return. Writing to the path of a folder raises ``IsADirectoryError``, and -to the path of a Google Docs file or a shortcut ``PermissionError``. -Threads that write one path through the same filesystem instance take +alias followed by a filename. All reads require credentials, including +files shared by link. + +.. _fsspec-writing-files: + +Writing files +------------- + +A write replaces the content of a file at that path that the filesystem +knows, and keeps the file, with its ID, type and sharing. The filesystem +knows the latest 10,000 files it wrote or copied, or found by their path, +for example with ``exists()``, ``info()`` or a read. Listings do not count. +Any other write creates a new file without asking Drive first, even if a +file with that name exists. To replace a file that another client or an +earlier process wrote, call ``fs.exists(path)`` before writing. + +Writing to the path of a known folder raises ``IsADirectoryError``, and to +the path of a known Google Docs file or shortcut ``PermissionError``. If +another client has removed, trashed, moved or renamed the known file, the +write sends the new content to that file and then creates a new file at the +path. Threads that write one path through the same filesystem instance take turns. Other instances and other clients do not wait, so two of them can -still create two files with the same name. All reads require credentials, -including files shared by link. +still create two files with the same name. Listings -------- @@ -101,7 +115,9 @@ client moves, trashes, or deletes a folder, call The next lookup checks Drive for all folders with that name, including any same-name folder that still exists. -Only folder IDs are cached between calls. Both ``ls()`` and ``find()`` +Between calls the filesystem keeps folder IDs and the files that writes +can replace (see `Writing files`_), about 350 bytes for each file. +``invalidate_cache()`` forgets those files. Both ``ls()`` and ``find()`` build their results in memory, so larger listings use more memory during the call. diff --git a/docs/upgrading.rst b/docs/upgrading.rst index 967d4fba..653b42c7 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -65,11 +65,14 @@ Filesystem directories Both raise ``FileExistsError`` if the folder already exists. Use ``fs.makedirs(path, exist_ok=True)`` when repeating a setup step. -Writing to the path of an existing file, with ``pipe_file()``, -``put_file()`` or ``open(path, "wb")``, now replaces that file's content. -It used to add a second file with the same name. Writing to the path of a -folder raises ``IsADirectoryError``, and to the path of a Google Docs file -or a shortcut ``PermissionError``. +Writing with ``pipe_file()``, ``put_file()`` or ``open(path, "wb")`` to +the path of a file that the filesystem wrote, copied or found by that path +now replaces that file's content. It used to add a second file with the +same name. Other writes still create a file without asking Drive first, so +call ``fs.exists(path)`` before writing to replace a file that another +client or an earlier process wrote. Writing to the path of a known folder +raises ``IsADirectoryError``, and to the path of a known Google Docs file +or shortcut ``PermissionError``. See :ref:`fsspec-writing-files`. The :doc:`fsspec filesystem ` now caches folders returned by ``ls()``. Later calls such as ``exists("root/data")`` can reuse those IDs. diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index bff5af79..ddd68d04 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -1,9 +1,9 @@ """Directory edges learned from Drive queries, scoped to one filesystem.""" -from collections import defaultdict +from collections import OrderedDict, defaultdict from contextlib import contextmanager from itertools import count -from threading import RLock +from threading import Lock, RLock from typing import NamedTuple @@ -432,3 +432,42 @@ def _relink(self, groups, revision): for (parent, name), leaving in moved.items(): self._unlink(parent, name, leaving) return True + + +class KnownFiles: + """The latest files written or found by path, by parent ID and name.""" + + def __init__(self, limit: int): + self.limit = limit + self._lock = Lock() + self._files: OrderedDict[tuple[str, str], tuple[str, str | None]] = ( + OrderedDict() + ) + + def add(self, parent, name, file_id, mime_type): + key = (parent, name) + with self._lock: + self._files[key] = (file_id, mime_type) + self._files.move_to_end(key) + if len(self._files) > self.limit: + self._files.popitem(last=False) + + def get(self, parents, name): + """Return (ID, type, parent) of the lowest known ID, as reads pick.""" + found: list[tuple[str, str | None, str]] = [] + with self._lock: + for parent in parents: + key = (parent, name) + if key in self._files: + self._files.move_to_end(key) + file_id, mime_type = self._files[key] + found.append((file_id, mime_type, parent)) + return min(found, default=None) + + def discard(self, parent, name): + with self._lock: + self._files.pop((parent, name), None) + + def clear(self): + with self._lock: + self._files.clear() diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 794d3d1d..239e1430 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -40,7 +40,7 @@ ApiRequestError, _FileMetadataPages, ) -from pydrive2.fs.cache import DirectoryCache +from pydrive2.fs.cache import DirectoryCache, KnownFiles from pydrive2.fs.utils import IterStream from pydrive2.settings import InvalidConfigError @@ -57,6 +57,8 @@ _CONNECTION_RETRIES = 3 # One request for IDs covers this many new files and folders. _NEW_ID_BATCH = 100 +# Writes replace only these latest files, about 350 bytes each. +_KNOWN_FILES_LIMIT = 10_000 _CONNECTION_ERRORS = ( TimeoutError, ConnectionError, @@ -615,6 +617,7 @@ def __init__( self._root_lock = threading.RLock() self._root_metadata: dict = {} self._creation_locks: WeakValueDictionary = WeakValueDictionary() + self._known_files = KnownFiles(_KNOWN_FILES_LIMIT) self._forget_new_ids() if not google_auth: @@ -701,6 +704,7 @@ def _resolver(self): def invalidate_cache(self, path=None): base = self._split_mounted_path(path)[1] if path else "" super().invalidate_cache(path) + self._known_files.clear() with self._dirs.lock: if not base: self._root_metadata = {} @@ -864,6 +868,12 @@ def _lookup_path(self, path, *, folders_only=False): return _PathMatch([self.root]), self._dirs.generation resolver = self._resolver() match = resolver.resolve(path, folders_only=folders_only) + # Add the lowest ID under each parent last, so it is the one kept. + for item in sorted(match.files, key=attrgetter("id"), reverse=True): + if item.parent is not None and not item.ambiguous: + self._known_files.add( + item.parent, item.name, item.id, item.mime_type + ) return match, resolver.generation def _get_item_id(self, path, create=False): @@ -1223,13 +1233,12 @@ def find( return contents def upload_fobj(self, stream, rpath, callback=None, **kwargs): - """Write a file. A file already at the path gets the new content.""" + """Write a file, replacing one this filesystem knows at the path.""" _, base = self._split_mounted_path(rpath) parent, name = self._split_file_path(rpath) _, parent_base = self._split_mounted_path(parent) - resolver = self._resolver() parents = ( - resolver.directory(parent_base, create=True).folders + self._resolver().directory(parent_base, create=True).folders if parent_base else [self.root] ) @@ -1238,49 +1247,65 @@ def upload_fobj(self, stream, rpath, callback=None, **kwargs): stream = _ReadProgress(stream, callback.relative_update) # Threads of this filesystem that write the same path take turns. with self._creation_lock(parent_id, name): - existing = self._file_to_replace( - resolver, rpath, base, parents, name - ) + if self._dirs.has_directory(base, self.base): + raise IsADirectoryError( + errno.EISDIR, os.strerror(errno.EISDIR), rpath + ) + known = self._known_files.get(parents, name) with _unwrap_not_retried(): - if existing is None: - item = self._gdrive_upload_fobj(name, parent_id, stream) - self._dirs.file_added(parent_id, name) - return item - with _translate_not_found(rpath): - return self._gdrive_replace_content(existing, stream) - - def _file_to_replace(self, resolver, path, base, parents, name): - """The file a write to the path replaces, as reads find it.""" - match, _ = resolver.child(parents, base, name, folders_only=False) - if match.folders: - raise IsADirectoryError( - errno.EISDIR, os.strerror(errno.EISDIR), path + if known is not None: + item = self._gdrive_replace_known( + rpath, name, known, stream + ) + if item is not None: + return item + item = self._gdrive_upload_fobj(name, parent_id, stream) + self._dirs.file_added(parent_id, name) + self._known_files.add( + parent_id, name, item["id"], item.get("mimeType") ) - if not match.files: - return None - # Reads of a name that several files share use the lowest ID. - existing = min(match.files, key=attrgetter("id")) - if existing.mime_type.startswith(_WORKSPACE_TYPE_PREFIX): + return item + + def _gdrive_replace_known(self, path, name, known, stream): + """Replace a known file's content, or return None if it has left.""" + file_id, mime_type, parent = known + if (mime_type or "").startswith(_WORKSPACE_TYPE_PREFIX): raise PermissionError( errno.EPERM, "Drive cannot replace a Google Workspace file or a " "shortcut with bytes", path, ) - return existing - def _gdrive_replace_content(self, existing, stream): + metadata = {"id": file_id} + if mime_type: + # Drive would otherwise set the type from the uploaded content. + metadata["mimeType"] = mime_type + def send(): - # Without the type, Drive sets it from the uploaded content. - item = self.client.CreateFile( - {"id": existing.id, "mimeType": existing.mime_type} - ) + item = self.client.CreateFile(metadata) item.content = stream item.Upload() return item - # Sending the same content to the same file again changes nothing. - return _gdrive_retry_repeatable(send)() + try: + # Sending the same content to the same file again changes nothing. + item = _gdrive_retry_repeatable(send)() + except ApiRequestError as exc: + if not _is_not_found(exc): + raise + item = None + if ( + item is not None + and not item.get("trashed") + and item.get("name") == name + # Drive reports the real ID of a root alias, which is unknown here. + and (parent in _ROOT_ALIASES or parent in item.get("parents", ())) + ): + return item + # Another client deleted, trashed, moved or renamed the file. + self._known_files.discard(parent, name) + return None def put_file(self, lpath, rpath, callback=None, **kwargs): if os.path.isdir(lpath): @@ -1311,14 +1336,17 @@ def cp_file(self, lpath, rpath, **kwargs): return parent, name = self._split_file_path(rpath) parent_id = self._get_item_id(parent, create=True) - self._gdrive_copy_file(source_id, parent_id, name) + item = self._gdrive_copy_file(source_id, parent_id, name) self._dirs.file_added(parent_id, name) + self._known_files.add( + parent_id, name, item["id"], item.get("mimeType") + ) def _gdrive_copy_file(self, source_id, parent_id, name): source = self.client.CreateFile({"id": source_id}) - self._gdrive_create( + return self._gdrive_create( lambda new_id: source._Copy( - {"id": parent_id}, name, {"fields": "id"}, new_id + {"id": parent_id}, name, {"fields": "id,mimeType"}, new_id ) ) @@ -1401,6 +1429,12 @@ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs): self._dirs.file_added( destination_parent, dst_name, parent_path=parent_path ) + moved = next(item for item in match.files if item.id == file1_id) + self._known_files.discard(moved.parent, moved.name) + if destination_parent is not None: + self._known_files.add( + destination_parent, dst_name, file1_id, moved.mime_type + ) def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): with _translate_not_found(rpath): @@ -1558,6 +1592,9 @@ def rm_file(self, path): item_id = _select_item_id(path, match.ids) known_folder = item_id in match.folders self._gdrive_delete_file(item_id) + for item in match.files: + if item.id == item_id: + self._known_files.discard(item.parent, item.name) self._invalidate_folder(item_id, path, known_folder=known_folder) def _gdrive_delete_file(self, item_id, *, empty_directory=None): diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 194d7931..6e4f1801 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -239,8 +239,7 @@ def record_listing(request, *args, **kwargs): leaf = remote_dir + "/a/b/c" path = leaf + "/test.txt" fs.touch(path) - # One lookup for each missing folder, and one for the file name. - assert len(queries) == 6 + assert len(queries) == 5 for operation, target, expected in ( (fs.exists, path, True), @@ -770,12 +769,28 @@ def metadata_on_drive(service_auth, file_id, fields): return file -def ids_in(service_auth, folder_id): +def ids_in(service_auth, folder_id, name=None): query = f"'{folder_id}' in parents and trashed=false" + if name is not None: + query += f" and name='{name}'" listing = GoogleDrive(service_auth).ListFile({"q": query}) return [item["id"] for item in pydrive_retry(listing.GetList)] +@pytest.fixture +def drive_methods(monkeypatch): + """The Drive API methods of the requests sent from here on.""" + sent = [] + execute = HttpRequest.execute + + def record(request, *args, **kwargs): + sent.append(request.methodId) + return execute(request, *args, **kwargs) + + monkeypatch.setattr(HttpRequest, "execute", record) + return sent + + def pipe(fs, path, data, tmp_path): fs.pipe_file(path, data) @@ -791,6 +806,43 @@ def write_through_open(fs, path, data, tmp_path): stream.write(data) +def test_write_after_makedirs_of_the_parent_creates_the_file_in_one_request( + fs, remote_dir, drive_methods +): + fs.makedirs(remote_dir) + drive_methods.clear() + + fs.pipe_file(remote_dir + "/file", b"data") + + assert drive_methods == ["drive.files.create"] + + +def test_write_after_a_write_to_the_path_replaces_the_file_in_one_request( + fs, fs_factory, remote_dir, drive_methods +): + path = remote_dir + "/file" + fs.pipe_file(path, b"old") + drive_methods.clear() + + fs.pipe_file(path, b"new") + + assert drive_methods == ["drive.files.update"] + other, _ = fs_factory() + assert items_below(other, remote_dir) == ["file"] + assert other.cat_file(path) == b"new" + + +def test_write_after_another_client_made_the_file_adds_a_second_file( + service_auth, fs, remote_dir, remote_dir_id +): + file_id = create_on_drive(service_auth, remote_dir_id, "file", "old") + + fs.pipe_file(remote_dir + "/file", b"new") + + assert len(ids_in(service_auth, remote_dir_id, "file")) == 2 + assert content_on_drive(service_auth, file_id) == b"old" + + @pytest.mark.parametrize( ("write", "size"), [ @@ -801,7 +853,7 @@ def write_through_open(fs, path, data, tmp_path): ], ids=["pipe_file", "open", "put_file-2MiB"], ) -def test_write_to_a_file_path_replaces_the_content_and_keeps_the_file( +def test_write_after_exists_found_the_file_replaces_it_and_keeps_its_type( service_auth, fs, remote_dir, remote_dir_id, tmp_path, write, size ): data = (b"0123456789abcdef" * (size // 16 + 1))[:size] @@ -812,6 +864,7 @@ def test_write_to_a_file_path_replaces_the_content_and_keeps_the_file( "{}", mimeType="application/json", ) + assert fs.exists(remote_dir + "/a.json") write(fs, remote_dir + "/a.json", data, tmp_path) @@ -829,10 +882,11 @@ def test_write_to_a_file_path_replaces_the_content_and_keeps_the_file( ], ids=["touch", "pipe_file"], ) -def test_empty_write_to_a_file_path_empties_the_file( +def test_empty_write_after_exists_found_the_file_empties_it( service_auth, fs, remote_dir, remote_dir_id, write ): file_id = create_on_drive(service_auth, remote_dir_id, "file", "old") + assert fs.exists(remote_dir + "/file") write(fs, remote_dir + "/file") @@ -840,7 +894,7 @@ def test_empty_write_to_a_file_path_empties_the_file( assert content_on_drive(service_auth, file_id) == b"" -def test_write_to_a_path_two_files_share_replaces_the_one_reads_return( +def test_write_after_exists_found_two_files_replaces_the_one_reads_return( service_auth, fs, fs_factory, remote_dir, remote_dir_id ): files = { @@ -848,6 +902,7 @@ def test_write_to_a_path_two_files_share_replaces_the_one_reads_return( create_on_drive(service_auth, remote_dir_id, "file", "two"): b"two", } read_id, other_id = sorted(files) + assert fs.exists(remote_dir + "/file") fs.pipe_file(remote_dir + "/file", b"new") @@ -856,7 +911,7 @@ def test_write_to_a_path_two_files_share_replaces_the_one_reads_return( assert content_on_drive(service_auth, other_id) == files[other_id] -def test_write_below_two_folders_with_one_name_replaces_the_file_in_either( +def test_write_after_exists_found_the_file_below_two_same_name_folders_replaces_it( service_auth, fs, remote_dir, remote_dir_id ): folders = sorted( @@ -864,6 +919,7 @@ def test_write_below_two_folders_with_one_name_replaces_the_file_in_either( ) # Writes would create a new file in the folder with the lower ID. file_id = create_on_drive(service_auth, folders[1], "file", "old") + assert fs.exists(remote_dir + "/dup/file") fs.pipe_file(remote_dir + "/dup/file", b"new") @@ -876,6 +932,7 @@ def test_replace_after_drive_did_it_and_the_answer_was_lost_keeps_one_file( service_auth, fs, remote_dir, remote_dir_id, lose_answers ): file_id = create_on_drive(service_auth, remote_dir_id, "file", "old") + assert fs.exists(remote_dir + "/file") lost = lose_answers("PATCH", "") fs.pipe_file(remote_dir + "/file", b"new") @@ -885,7 +942,74 @@ def test_replace_after_drive_did_it_and_the_answer_was_lost_keeps_one_file( assert content_on_drive(service_auth, file_id) == b"new" -def test_write_to_a_folder_path_raises_and_creates_no_file( +def trash(service_auth, file_id, folder_id): + pydrive_retry(GoogleDrive(service_auth).CreateFile({"id": file_id}).Trash) + + +def delete(service_auth, file_id, folder_id): + pydrive_retry(GoogleDrive(service_auth).CreateFile({"id": file_id}).Delete) + + +def rename(service_auth, file_id, folder_id): + file = GoogleDrive(service_auth).CreateFile({"id": file_id}) + file["name"] = "renamed" + pydrive_retry(file.Upload) + + +def move_to_a_subfolder(service_auth, file_id, folder_id): + file = GoogleDrive(service_auth).CreateFile({"id": file_id}) + file["parents"] = [create_on_drive(service_auth, folder_id, "elsewhere")] + pydrive_retry(file.Upload) + + +@pytest.mark.parametrize( + "change", [trash, delete, rename, move_to_a_subfolder] +) +def test_write_after_another_client_changed_the_known_file_creates_a_new_one( + service_auth, fs, remote_dir, remote_dir_id, change +): + path = remote_dir + "/file" + fs.pipe_file(path, b"old") + [old_id] = ids_in(service_auth, remote_dir_id) + change(service_auth, old_id, remote_dir_id) + + fs.pipe_file(path, b"new") + + [new_id] = ids_in(service_auth, remote_dir_id, "file") + assert new_id != old_id + assert content_on_drive(service_auth, new_id) == b"new" + + +def test_write_after_rm_file_of_the_path_creates_a_file_in_one_request( + fs, fs_factory, remote_dir, drive_methods +): + path = remote_dir + "/file" + fs.pipe_file(path, b"old") + fs.rm_file(path) + drive_methods.clear() + + fs.pipe_file(path, b"new") + + assert drive_methods == ["drive.files.create"] + assert fs_factory()[0].cat_file(path) == b"new" + + +def test_write_after_mv_to_the_path_replaces_the_moved_file( + fs, fs_factory, remote_dir, drive_methods +): + fs.pipe_file(remote_dir + "/source", b"old") + fs.mv(remote_dir + "/source", remote_dir + "/target") + drive_methods.clear() + + fs.pipe_file(remote_dir + "/target", b"new") + + assert drive_methods == ["drive.files.update"] + other, _ = fs_factory() + assert items_below(other, remote_dir) == ["target"] + assert other.cat_file(remote_dir + "/target") == b"new" + + +def test_write_after_makedirs_of_the_path_raises_and_creates_no_file( fs, fs_factory, remote_dir ): fs.makedirs(remote_dir + "/dir") @@ -895,8 +1019,10 @@ def test_write_to_a_folder_path_raises_and_creates_no_file( @pytest.mark.parametrize("suffix", ["", "-link"], ids=["doc", "shortcut"]) -def test_write_to_a_google_doc_or_shortcut_path_raises_permission_error( +def test_write_after_exists_found_a_doc_or_shortcut_raises_permission_error( fs, workspace_files, suffix ): + path = f"root/{workspace_files}{suffix}" + assert fs.exists(path) with pytest.raises(PermissionError): - fs.pipe_file(f"root/{workspace_files}{suffix}", b"data") + fs.pipe_file(path, b"data") diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index b82a687f..73f7bc40 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -890,7 +890,6 @@ def test_warm_calls_below_a_folder_with_a_same_name_file_reuse_its_id( listing(sub), listing(note), listing(note), - listing(), # No file of that name yet. response({"id": "uploaded"}), ) fs = filesystem(drive, mount) @@ -903,7 +902,7 @@ def test_warm_calls_below_a_folder_with_a_same_name_file_reuse_its_id( ["('S' in parents) and trashed=false and name='note'"] ] fs.touch("root/data/uploaded") - assert [req[1] for req in requests[before + 1 :]] == ["GET", "POST"] + assert [req[1] for req in requests[before + 1 :]] == ["POST"] def test_find_caches_only_the_new_path_for_a_folder_moved_between_batches( @@ -1443,7 +1442,6 @@ def test_nested_file_operations_reuse_resolved_directories(mock_drive): response(b), listing(), response(c), - listing(), # No file of that name yet. response({"id": "file"}), listing(file), listing(a), @@ -1456,10 +1454,14 @@ def test_nested_file_operations_reuse_resolved_directories(mock_drive): leaf = parent + "/a/b/c" path = leaf + "/test.txt" fs.touch(path) - assert [r[1] for r in requests] == ["GET", *(["GET", "POST"] * 5)] + assert [r[1] for r in requests] == [ + "GET", + *(["GET", "POST"] * 4), + "POST", + ] assert [ query(r)["q"][0].split("name=")[-1] for r in requests if r[1] == "GET" - ] == ["'mount'", "'run'", "'a'", "'b'", "'c'", "'test.txt'"] + ] == ["'mount'", "'run'", "'a'", "'b'", "'c'"] for operation, target, expected in ( (fs.exists, path, True), @@ -2258,8 +2260,8 @@ def write(on_request): def test_two_threads_writing_one_new_path_create_one_file(mock_drive): file = {"id": "A", "name": "new", "mimeType": "text/plain"} - first, _ = mock_drive(listing(), response(file)) - second, second_requests = mock_drive(listing(file), response(file)) + first, _ = mock_drive(response(file)) + second, second_requests = mock_drive(response(file)) fs = filesystem(first) threads = first.auth.thread_local first_http = first.auth.thread_local.http @@ -2276,7 +2278,26 @@ def write_second(on_request): early, later = run_while_paused(write_first, write_second, "POST") later.result(timeout=5) assert early == [] - assert [r[1] for r in second_requests] == ["GET", "PATCH"] + assert [r[1] for r in second_requests] == ["PATCH"] + + +def test_write_after_10000_writes_to_other_paths_creates_a_second_file( + mock_drive, +): + others = 10_000 + drive, requests = mock_drive( + *( + response({"id": f"F{i}", "name": f"f{i}"}) + for i in range(others + 2) + ) + ) + fs = filesystem(drive) + for i in range(others + 1): + fs.pipe_file(f"root/f{i}", b"") + + fs.pipe_file("root/f0", b"") + + assert requests[-1][1] == "POST" def overlap_requests( @@ -3006,10 +3027,7 @@ def send(request): "", ) drive, _ = mock_drive( - listing(), - *[session] * attempts, - response({"id": "file"}), - on_request=send, + *[session] * attempts, response({"id": "file"}), on_request=send ) progress = ProgressSteps() filesystem(drive).put_file(str(source), "root/source", callback=progress) @@ -3040,7 +3058,6 @@ def test_recursive_put_uploads_files_and_creates_empty_folders( listing(), listing(), response({"id": "U"}), - listing(), # No a.txt in the new folder. response({"id": "A"}), listing(), response({"id": "E"}), @@ -3997,7 +4014,7 @@ def fail(size, value): reports.append(value) raise TimeoutError("The progress report timed out") - drive, requests = mock_drive(listing()) + drive, requests = mock_drive() with pytest.raises(TimeoutError, match="progress report"): filesystem(drive).upload_fobj( io.BytesIO(b"data"), @@ -4005,7 +4022,7 @@ def fail(size, value): callback=Callback(hooks={"f": fail}), ) assert reports == [4] - assert [r[1] for r in requests] == ["GET"] + assert requests == [] sleep.assert_not_called() From 5fbcc8ee12229b336e007bacf5f32d1ebaeaead9 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 4 Dec 2026 12:39:31 -0800 Subject: [PATCH 5/9] Keep the file reads return, and check moves under a root alias A copy, move or upload no longer displaces a known file with a lower ID, so the next write replaces the file that reads return. A lookup that invalidate_cache() or another change overtook no longer records its files. A replace under a root alias checks the parent against the alias's real ID, learned from an upload there or read once per filesystem, so a file moved out of the root is noticed. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/cache.py | 7 +++-- pydrive2/fs/spec.py | 35 ++++++++++++++++----- pydrive2/test/test_fs.py | 21 +++++++++++++ pydrive2/test/test_fs_unit.py | 57 ++++++++++++++++++++++++++++++++++- 4 files changed, 110 insertions(+), 10 deletions(-) diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index ddd68d04..405c6934 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -444,10 +444,13 @@ def __init__(self, limit: int): OrderedDict() ) - def add(self, parent, name, file_id, mime_type): + def add(self, parent, name, file_id, mime_type, *, looked_up=False): + """Remember a file; a created one does not displace a lower ID.""" key = (parent, name) with self._lock: - self._files[key] = (file_id, mime_type) + known = self._files.get(key) + if looked_up or known is None or file_id < known[0]: + self._files[key] = (file_id, mime_type) self._files.move_to_end(key) if len(self._files) > self.limit: self._files.popitem(last=False) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 239e1430..1088be02 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -618,6 +618,7 @@ def __init__( self._root_metadata: dict = {} self._creation_locks: WeakValueDictionary = WeakValueDictionary() self._known_files = KnownFiles(_KNOWN_FILES_LIMIT) + self._alias_ids: dict[str, str] = {} self._forget_new_ids() if not google_auth: @@ -869,13 +870,32 @@ def _lookup_path(self, path, *, folders_only=False): resolver = self._resolver() match = resolver.resolve(path, folders_only=folders_only) # Add the lowest ID under each parent last, so it is the one kept. - for item in sorted(match.files, key=attrgetter("id"), reverse=True): - if item.parent is not None and not item.ambiguous: - self._known_files.add( - item.parent, item.name, item.id, item.mime_type - ) + items = sorted(match.files, key=attrgetter("id"), reverse=True) + with self._dirs.lock: + # A lookup that a change overtook must not bring back old files. + if resolver.generation != self._dirs.generation: + items = [] + for item in items: + if item.parent is not None and not item.ambiguous: + self._known_files.add( + item.parent, + item.name, + item.id, + item.mime_type, + looked_up=True, + ) return match, resolver.generation + def _canonical_id(self, folder_id): + """Return the ID that Drive reports as the parent for a root alias.""" + if folder_id not in _ROOT_ALIASES: + return folder_id + if folder_id not in self._alias_ids: + item = self.client.CreateFile({"id": folder_id}) + _gdrive_retry_repeatable(item.FetchMetadata)(fields="id") + self._alias_ids[folder_id] = item["id"] + return self._alias_ids[folder_id] + def _get_item_id(self, path, create=False): _, base = self._split_mounted_path(path) if create and base: @@ -1261,6 +1281,8 @@ def upload_fobj(self, stream, rpath, callback=None, **kwargs): return item item = self._gdrive_upload_fobj(name, parent_id, stream) self._dirs.file_added(parent_id, name) + if parent_id in _ROOT_ALIASES and item.get("parents"): + self._alias_ids.setdefault(parent_id, item["parents"][0]) self._known_files.add( parent_id, name, item["id"], item.get("mimeType") ) @@ -1299,8 +1321,7 @@ def send(): item is not None and not item.get("trashed") and item.get("name") == name - # Drive reports the real ID of a root alias, which is unknown here. - and (parent in _ROOT_ALIASES or parent in item.get("parents", ())) + and self._canonical_id(parent) in item.get("parents", ()) ): return item # Another client deleted, trashed, moved or renamed the file. diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 6e4f1801..832541d5 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -980,6 +980,27 @@ def test_write_after_another_client_changed_the_known_file_creates_a_new_one( assert content_on_drive(service_auth, new_id) == b"new" +def test_write_after_another_client_moved_a_known_root_file_creates_a_new_one( + service_auth, fs, remote_dir_id, request +): + name = uuid.uuid4().hex + request.addfinalizer( + lambda: [ + delete(service_auth, file_id, "root") + for file_id in ids_in(service_auth, "root", name) + ] + ) + fs.pipe_file(f"root/{name}", b"old") + [old_id] = ids_in(service_auth, "root", name) + move_to_a_subfolder(service_auth, old_id, remote_dir_id) + + fs.pipe_file(f"root/{name}", b"new") + + [new_id] = ids_in(service_auth, "root", name) + assert new_id != old_id + assert content_on_drive(service_auth, new_id) == b"new" + + def test_write_after_rm_file_of_the_path_creates_a_file_in_one_request( fs, fs_factory, remote_dir, drive_methods ): diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 73f7bc40..2ecc9026 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -2259,7 +2259,12 @@ def write(on_request): def test_two_threads_writing_one_new_path_create_one_file(mock_drive): - file = {"id": "A", "name": "new", "mimeType": "text/plain"} + file = { + "id": "A", + "name": "new", + "mimeType": "text/plain", + "parents": ["RealRoot"], + } first, _ = mock_drive(response(file)) second, second_requests = mock_drive(response(file)) fs = filesystem(first) @@ -2281,6 +2286,56 @@ def write_second(on_request): assert [r[1] for r in second_requests] == ["PATCH"] +def test_write_after_invalidate_cache_during_a_lookup_creates_a_file( + mock_drive, +): + found = {"id": "A", "name": "item", "mimeType": "text/plain"} + finder, _ = mock_drive(listing(found)) + writer, writer_requests = mock_drive(response(dict(found, id="B"))) + fs = filesystem(finder) + threads = finder.auth.thread_local + finder_http = finder.auth.thread_local.http + writer_http = writer.auth.thread_local.http + + def look_up(on_request): + threads.http = reporting(finder_http, on_request) + assert fs.exists("root/item") + + def invalidate(on_request): + fs.invalidate_cache() + + _, later = run_while_paused(look_up, invalidate, "GET") + later.result(timeout=5) + threads.http = writer_http + + fs.pipe_file("root/item", b"new") + + assert [r[1] for r in writer_requests] == ["POST"] + + +def test_write_after_cp_file_onto_a_found_file_replaces_the_one_reads_return( + mock_drive, +): + found = {"id": "A", "name": "item", "mimeType": "text/plain"} + drive, requests = mock_drive( + listing(found), + listing(dict(found, id="S", name="source")), + response(dict(found, id="B")), + response(dict(found, parents=["RealRoot"])), + response({"id": "RealRoot"}), + ) + fs = filesystem(drive) + assert fs.exists("root/item") + fs.cp_file("root/source", "root/item") + + fs.pipe_file("root/item", b"new") + + assert [ + (method, urlsplit(uri).path.rsplit("/", 1)[-1]) + for uri, method, *_ in requests[3:] + ] == [("PATCH", "A"), ("GET", "root")] + + def test_write_after_10000_writes_to_other_paths_creates_a_second_file( mock_drive, ): From 4fe00e786ab398ff9bccef7714ca6f19dd4a374c Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Fri, 4 Dec 2026 12:45:42 -0800 Subject: [PATCH 6/9] Forget known files that a later lookup no longer finds A lookup now replaces what the filesystem knew under each parent it read, so a file that another client removed is no longer picked over the one the lookup found. invalidate_cache() clears the known files under the directory-cache lock, so a lookup cannot record its files in between. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 12 +++++++++--- pydrive2/test/test_fs_unit.py | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 1088be02..00ae89e5 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -125,6 +125,8 @@ def entry(self, name, detail=True): class _PathMatch: folders: list[str] files: list[_ListedChild] = field(default_factory=list) + # The parents whose items of this name a listing has just read. + searched: list[str] = field(default_factory=list) def __bool__(self): return bool(self.folders or self.files) @@ -160,7 +162,7 @@ def child(self, parents, path, name, *, folders_only, create=False): if folders: return _PathMatch(folders), False - match = _PathMatch([]) + match = _PathMatch([], searched=list(parents)) with cache.listing(self.generation, parents, name=name) as listing: for item in self.fs._list_children(listing): if item.is_folder: @@ -705,8 +707,8 @@ def _resolver(self): def invalidate_cache(self, path=None): base = self._split_mounted_path(path)[1] if path else "" super().invalidate_cache(path) - self._known_files.clear() with self._dirs.lock: + self._known_files.clear() if not base: self._root_metadata = {} self._dirs.invalidate(base) @@ -869,12 +871,16 @@ def _lookup_path(self, path, *, folders_only=False): return _PathMatch([self.root]), self._dirs.generation resolver = self._resolver() match = resolver.resolve(path, folders_only=folders_only) + name = posixpath.basename(path) # Add the lowest ID under each parent last, so it is the one kept. items = sorted(match.files, key=attrgetter("id"), reverse=True) with self._dirs.lock: # A lookup that a change overtook must not bring back old files. if resolver.generation != self._dirs.generation: - items = [] + return match, resolver.generation + # What the listing found replaces what was known under each parent. + for parent in match.searched: + self._known_files.discard(parent, name) for item in items: if item.parent is not None and not item.ambiguous: self._known_files.add( diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 2ecc9026..355fb0af 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -2313,6 +2313,28 @@ def invalidate(on_request): assert [r[1] for r in writer_requests] == ["POST"] +def test_write_after_exists_no_longer_finds_a_known_file_replaces_the_other( + mock_drive, +): + first = {"id": "A", "name": "file", "mimeType": "text/plain"} + second = dict(first, id="B") + drive, requests = mock_drive( + listing(folder("dup", "P"), folder("dup", "Q")), + listing(dict(first, parents=["P"]), dict(second, parents=["Q"])), + listing(dict(second, parents=["Q"])), + response(dict(second, parents=["Q"])), + ) + fs = filesystem(drive) + assert fs.exists("root/dup/file") + # Another client has removed A since. + assert fs.exists("root/dup/file") + + fs.pipe_file("root/dup/file", b"new") + + assert requests[-1][1] == "PATCH" + assert urlsplit(requests[-1][0]).path.endswith("/files/B") + + def test_write_after_cp_file_onto_a_found_file_replaces_the_one_reads_return( mock_drive, ): From 9069468bcf6937de20a95bafc28b6da675261cdd Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 5 Dec 2026 16:13:04 -0800 Subject: [PATCH 7/9] Keep files written during a lookup, and remember two-parent files A lookup now forgets or replaces only known files stored before it started, so a file another thread wrote meanwhile stays known. A found file with two parents is remembered under the parent it was listed in, as reads pick it. A write to the path of a folder this filesystem moved there raises IsADirectoryError. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/cache.py | 46 ++++++++++++++++++++++++++--------- pydrive2/fs/spec.py | 10 ++++---- pydrive2/test/test_fs.py | 10 ++++++++ pydrive2/test/test_fs_unit.py | 24 ++++++++++++++++++ 4 files changed, 74 insertions(+), 16 deletions(-) diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index 405c6934..bf4be215 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -208,6 +208,13 @@ def has_directory(self, path, mount): for parent in parents ) + def has_child_folder(self, parents, name): + """Whether a folder of this name is known under one of these parents.""" + with self.lock: + return any( + self.children.get(parent, {}).get(name) for parent in parents + ) + def _parents_of_path(self, path): parent, _, name = path.rpartition("/") return self._known_folder_ids(parent), name @@ -440,17 +447,28 @@ class KnownFiles: def __init__(self, limit: int): self.limit = limit self._lock = Lock() - self._files: OrderedDict[tuple[str, str], tuple[str, str | None]] = ( - OrderedDict() - ) - - def add(self, parent, name, file_id, mime_type, *, looked_up=False): - """Remember a file; a created one does not displace a lower ID.""" + # Counts stored entries, so a lookup can tell which ones are newer. + self.revision = 0 + self._files: OrderedDict[ + tuple[str, str], tuple[str, str | None, int] + ] = OrderedDict() + + def add(self, parent, name, file_id, mime_type, *, found_at=None): + """Remember a file; a created one does not displace a lower ID. + + A file found by a lookup that started at revision found_at also + replaces an entry stored before that lookup. + """ key = (parent, name) with self._lock: known = self._files.get(key) - if looked_up or known is None or file_id < known[0]: - self._files[key] = (file_id, mime_type) + if ( + known is None + or file_id < known[0] + or (found_at is not None and known[2] <= found_at) + ): + self.revision += 1 + self._files[key] = (file_id, mime_type, self.revision) self._files.move_to_end(key) if len(self._files) > self.limit: self._files.popitem(last=False) @@ -463,13 +481,19 @@ def get(self, parents, name): key = (parent, name) if key in self._files: self._files.move_to_end(key) - file_id, mime_type = self._files[key] + file_id, mime_type, _ = self._files[key] found.append((file_id, mime_type, parent)) return min(found, default=None) - def discard(self, parent, name): + def discard(self, parent, name, *, found_at=None): + """Forget a file, or with found_at only one stored before that lookup.""" + key = (parent, name) with self._lock: - self._files.pop((parent, name), None) + known = self._files.get(key) + if known is not None and ( + found_at is None or known[2] <= found_at + ): + del self._files[key] def clear(self): with self._lock: diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index cd0e861d..44904c49 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -882,6 +882,7 @@ def _creation_lock(self, parent_id, name): def _lookup_path(self, path, *, folders_only=False): if not path: return _PathMatch([self.root]), self._dirs.generation + found_at = self._known_files.revision resolver = self._resolver() match = resolver.resolve(path, folders_only=folders_only) name = posixpath.basename(path) @@ -893,15 +894,15 @@ def _lookup_path(self, path, *, folders_only=False): return match, resolver.generation # What the listing found replaces what was known under each parent. for parent in match.searched: - self._known_files.discard(parent, name) + self._known_files.discard(parent, name, found_at=found_at) for item in items: - if item.parent is not None and not item.ambiguous: + if item.parent is not None: self._known_files.add( item.parent, item.name, item.id, item.mime_type, - looked_up=True, + found_at=found_at, ) return match, resolver.generation @@ -1262,7 +1263,6 @@ def find( def upload_fobj(self, stream, rpath, callback=None, **kwargs): """Write a file, replacing one this filesystem knows at the path.""" - _, base = self._split_mounted_path(rpath) parent, name = self._split_file_path(rpath) _, parent_base = self._split_mounted_path(parent) parents = ( @@ -1275,7 +1275,7 @@ def upload_fobj(self, stream, rpath, callback=None, **kwargs): stream = _ReadProgress(stream, callback.relative_update) # Threads of this filesystem that write the same path take turns. with self._creation_lock(parent_id, name): - if self._dirs.has_directory(base, self.base): + if self._dirs.has_child_folder(parents, name): raise IsADirectoryError( errno.EISDIR, os.strerror(errno.EISDIR), rpath ) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 10acf330..2f574612 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -1112,6 +1112,16 @@ def test_write_after_makedirs_of_the_path_raises_and_creates_no_file( assert fs_factory()[0].ls(remote_dir) == [remote_dir + "/dir/"] +def test_write_after_mv_of_a_folder_to_the_path_raises_and_creates_no_file( + fs, fs_factory, remote_dir +): + fs.makedirs(remote_dir + "/old") + fs.mv(remote_dir + "/old", remote_dir + "/dir") + with pytest.raises(IsADirectoryError): + fs.pipe_file(remote_dir + "/dir", b"data") + assert fs_factory()[0].ls(remote_dir) == [remote_dir + "/dir/"] + + @pytest.mark.parametrize("suffix", ["", "-link"], ids=["doc", "shortcut"]) def test_write_after_exists_found_a_doc_or_shortcut_raises_permission_error( fs, workspace_files, suffix diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index ee2ba691..23b75182 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -2373,6 +2373,30 @@ def test_write_after_exists_no_longer_finds_a_known_file_replaces_the_other( assert urlsplit(requests[-1][0]).path.endswith("/files/B") +def test_write_after_exists_found_a_lower_id_file_with_two_parents_replaces_it( + mock_drive, +): + first = { + "id": "A", + "name": "file", + "mimeType": "text/plain", + "parents": ["P", "X"], + } + second = dict(first, id="B", parents=["P"]) + drive, requests = mock_drive( + listing(folder("dir", "P")), + listing(first, second), + response(first), + ) + fs = filesystem(drive) + assert fs.exists("root/dir/file") + + fs.pipe_file("root/dir/file", b"new") + + assert requests[-1][1] == "PATCH" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + def test_write_after_cp_file_onto_a_found_file_replaces_the_one_reads_return( mock_drive, ): From d5eae9f7a35e8bca558bc5910214bf43650d1ca2 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 5 Dec 2026 16:35:22 -0800 Subject: [PATCH 8/9] Record a lookup's files in one step, and not from ls() A lookup now hands its answer to KnownFiles in one locked call, so a writer never sees a name between the old entry's removal and the new one. A folder lookup, as ls() makes, no longer makes the file it meets replaceable, as the docs say of listings. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/cache.py | 50 +++++++++++++++++++++------------------- pydrive2/fs/spec.py | 32 +++++++++++-------------- pydrive2/test/test_fs.py | 8 ++++++- 3 files changed, 47 insertions(+), 43 deletions(-) diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index bf4be215..58df897d 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -453,25 +453,33 @@ def __init__(self, limit: int): tuple[str, str], tuple[str, str | None, int] ] = OrderedDict() - def add(self, parent, name, file_id, mime_type, *, found_at=None): - """Remember a file; a created one does not displace a lower ID. + def add(self, parent, name, file_id, mime_type): + """Remember a file; it does not displace a lower ID, as reads pick.""" + with self._lock: + self._add((parent, name), file_id, mime_type) + + def found(self, parents, name, files, revision): + """Record a lookup's answer in one step, so readers see all or none. - A file found by a lookup that started at revision found_at also - replaces an entry stored before that lookup. + It replaces what was known under each parent it read, except files + stored after the lookup started at this revision. """ - key = (parent, name) with self._lock: - known = self._files.get(key) - if ( - known is None - or file_id < known[0] - or (found_at is not None and known[2] <= found_at) - ): - self.revision += 1 - self._files[key] = (file_id, mime_type, self.revision) - self._files.move_to_end(key) - if len(self._files) > self.limit: - self._files.popitem(last=False) + for parent in parents: + known = self._files.get((parent, name)) + if known is not None and known[2] <= revision: + del self._files[parent, name] + for parent, file_id, mime_type in files: + self._add((parent, name), file_id, mime_type) + + def _add(self, key, file_id, mime_type): + known = self._files.get(key) + if known is None or file_id < known[0]: + self.revision += 1 + self._files[key] = (file_id, mime_type, self.revision) + self._files.move_to_end(key) + if len(self._files) > self.limit: + self._files.popitem(last=False) def get(self, parents, name): """Return (ID, type, parent) of the lowest known ID, as reads pick.""" @@ -485,15 +493,9 @@ def get(self, parents, name): found.append((file_id, mime_type, parent)) return min(found, default=None) - def discard(self, parent, name, *, found_at=None): - """Forget a file, or with found_at only one stored before that lookup.""" - key = (parent, name) + def discard(self, parent, name): with self._lock: - known = self._files.get(key) - if known is not None and ( - found_at is None or known[2] <= found_at - ): - del self._files[key] + self._files.pop((parent, name), None) def clear(self): with self._lock: diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 44904c49..ab7de306 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -882,28 +882,24 @@ def _creation_lock(self, parent_id, name): def _lookup_path(self, path, *, folders_only=False): if not path: return _PathMatch([self.root]), self._dirs.generation - found_at = self._known_files.revision + revision = self._known_files.revision resolver = self._resolver() match = resolver.resolve(path, folders_only=folders_only) - name = posixpath.basename(path) - # Add the lowest ID under each parent last, so it is the one kept. - items = sorted(match.files, key=attrgetter("id"), reverse=True) + files = [ + (item.parent, item.id, item.mime_type) + for item in match.files + if item.parent is not None + ] with self._dirs.lock: # A lookup that a change overtook must not bring back old files. - if resolver.generation != self._dirs.generation: - return match, resolver.generation - # What the listing found replaces what was known under each parent. - for parent in match.searched: - self._known_files.discard(parent, name, found_at=found_at) - for item in items: - if item.parent is not None: - self._known_files.add( - item.parent, - item.name, - item.id, - item.mime_type, - found_at=found_at, - ) + # A folder lookup, as ls() makes, does not make files replaceable. + if ( + resolver.generation == self._dirs.generation + and not folders_only + ): + self._known_files.found( + match.searched, posixpath.basename(path), files, revision + ) return match, resolver.generation def _canonical_id(self, folder_id): diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 2f574612..8f865572 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -898,10 +898,16 @@ def test_write_after_a_write_to_the_path_replaces_the_file_in_one_request( assert other.cat_file(path) == b"new" +@pytest.mark.parametrize( + "look", + [lambda fs, path: None, lambda fs, path: fs.ls(path)], + ids=["unseen", "ls"], +) def test_write_after_another_client_made_the_file_adds_a_second_file( - service_auth, fs, remote_dir, remote_dir_id + service_auth, fs, remote_dir, remote_dir_id, look ): file_id = create_on_drive(service_auth, remote_dir_id, "file", "old")["id"] + look(fs, remote_dir + "/file") fs.pipe_file(remote_dir + "/file", b"new") From fa71a5066faf73409f944fb5853f99190fd1c7c3 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 5 Dec 2026 18:03:21 -0800 Subject: [PATCH 9/9] Keep removed files forgotten, and known files across a failed rmdir A removal now records its revision, so a lookup that started before it cannot bring the file back for the next write to overwrite. A failed rmdir lookup refreshes only that path instead of forgetting every known file. A rename of a file with two parents remembers it under its new name. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/cache.py | 20 ++++++++-- pydrive2/fs/spec.py | 7 ++-- pydrive2/test/test_fs.py | 14 +++++++ pydrive2/test/test_fs_unit.py | 70 +++++++++++++++++++++++++++++++++++ 4 files changed, 104 insertions(+), 7 deletions(-) diff --git a/pydrive2/fs/cache.py b/pydrive2/fs/cache.py index 58df897d..3f995454 100644 --- a/pydrive2/fs/cache.py +++ b/pydrive2/fs/cache.py @@ -447,11 +447,13 @@ class KnownFiles: def __init__(self, limit: int): self.limit = limit self._lock = Lock() - # Counts stored entries, so a lookup can tell which ones are newer. + # Counts changes, so a lookup can tell which ones came after it began. self.revision = 0 self._files: OrderedDict[ tuple[str, str], tuple[str, str | None, int] ] = OrderedDict() + # The revision of the latest removal under each name. + self._removed: OrderedDict[tuple[str, str], int] = OrderedDict() def add(self, parent, name, file_id, mime_type): """Remember a file; it does not displace a lower ID, as reads pick.""" @@ -462,7 +464,8 @@ def found(self, parents, name, files, revision): """Record a lookup's answer in one step, so readers see all or none. It replaces what was known under each parent it read, except files - stored after the lookup started at this revision. + stored after the lookup started at this revision. A file removed + since then stays forgotten. """ with self._lock: for parent in parents: @@ -470,7 +473,8 @@ def found(self, parents, name, files, revision): if known is not None and known[2] <= revision: del self._files[parent, name] for parent, file_id, mime_type in files: - self._add((parent, name), file_id, mime_type) + if self._removed.get((parent, name), 0) <= revision: + self._add((parent, name), file_id, mime_type) def _add(self, key, file_id, mime_type): known = self._files.get(key) @@ -494,9 +498,17 @@ def get(self, parents, name): return min(found, default=None) def discard(self, parent, name): + """Forget a file, and when, so an older lookup cannot bring it back.""" + key = (parent, name) with self._lock: - self._files.pop((parent, name), None) + self._files.pop(key, None) + self.revision += 1 + self._removed[key] = self.revision + self._removed.move_to_end(key) + if len(self._removed) > self.limit: + self._removed.popitem(last=False) def clear(self): with self._lock: self._files.clear() + self._removed.clear() diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ab7de306..c5c02bb6 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -204,7 +204,7 @@ def directory(self, path, *, create=False): return match blocked = posixpath.join(self.fs.root, last) if self.fresh: - self.fs.invalidate_cache(blocked) + self.fs._dirs.invalidate(last) if match: raise NotADirectoryError( errno.ENOTDIR, os.strerror(errno.ENOTDIR), blocked @@ -1456,9 +1456,10 @@ def mv(self, path1, path2, recursive=False, maxdepth=None, **kwargs): ) moved = next(item for item in match.files if item.id == file1_id) self._known_files.discard(moved.parent, moved.name) - if destination_parent is not None: + # A rename keeps every parent, including the one it was found in. + if (parent := destination_parent or moved.parent) is not None: self._known_files.add( - destination_parent, dst_name, file1_id, moved.mime_type + parent, dst_name, file1_id, moved.mime_type ) def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs): diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 8f865572..9abdf0f4 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -1094,6 +1094,20 @@ def test_write_after_rm_file_of_the_path_creates_a_file_in_one_request( assert fs_factory()[0].cat_file(path) == b"new" +def test_write_after_rmdir_of_a_missing_folder_replaces_the_known_file( + fs, remote_dir, drive_methods +): + path = remote_dir + "/file" + fs.pipe_file(path, b"old") + with pytest.raises(FileNotFoundError): + fs.rmdir(remote_dir + "/missing") + drive_methods.clear() + + fs.pipe_file(path, b"new") + + assert drive_methods == ["drive.files.update"] + + def test_write_after_mv_to_the_path_replaces_the_moved_file( fs, fs_factory, remote_dir, drive_methods ): diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 23b75182..33a10537 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -2351,6 +2351,50 @@ def invalidate(on_request): assert [r[1] for r in writer_requests] == ["POST"] +def test_write_after_rm_file_during_a_lookup_of_the_path_creates_a_file( + mock_drive, +): + found = {"id": "A", "name": "item", "mimeType": "text/plain"} + finder, _ = mock_drive(listing(found)) + remover, remover_requests = mock_drive(listing(found), response({})) + writer, writer_requests = mock_drive(response(dict(found, id="B"))) + fs = filesystem(finder) + threads = finder.auth.thread_local + finder_http = finder.auth.thread_local.http + remover_http = remover.auth.thread_local.http + writer_http = writer.auth.thread_local.http + started, release = Event(), Event() + lookups = [] + + def pause(request): + started.set() + assert release.wait(5) + + def look_up(): + threads.http = reporting(finder_http, pause) + return fs.exists("root/item") + + with ThreadPoolExecutor(max_workers=1) as pool: + + def look_up_before_the_trash(request): + if request[1] == "PATCH": + lookups.append(pool.submit(look_up)) + assert started.wait(5) + + threads.http = reporting(remover_http, look_up_before_the_trash) + try: + fs.rm_file("root/item") + finally: + release.set() + assert lookups[0].result(timeout=5) + threads.http = writer_http + + fs.pipe_file("root/item", b"new") + + assert [r[1] for r in remover_requests] == ["GET", "PATCH"] + assert [r[1] for r in writer_requests] == ["POST"] + + def test_write_after_exists_no_longer_finds_a_known_file_replaces_the_other( mock_drive, ): @@ -2397,6 +2441,32 @@ def test_write_after_exists_found_a_lower_id_file_with_two_parents_replaces_it( assert urlsplit(requests[-1][0]).path.endswith("/files/A") +def test_write_after_mv_renamed_a_file_with_two_parents_replaces_it( + mock_drive, +): + old = { + "id": "A", + "name": "old", + "mimeType": "text/plain", + "parents": ["P", "X"], + } + new = dict(old, name="new") + drive, requests = mock_drive( + listing(folder("dir", "P")), + listing(), + listing(old), + response(new), + response(new), + ) + fs = filesystem(drive) + fs.mv("root/dir/old", "root/dir/new") + + fs.pipe_file("root/dir/new", b"data") + + assert requests[-1][1] == "PATCH" + assert urlsplit(requests[-1][0]).path.endswith("/files/A") + + def test_write_after_cp_file_onto_a_found_file_replaces_the_one_reads_return( mock_drive, ):