Skip to content

Replace a known file on a write, without a lookup per write - #455

Draft
shcheklein wants to merge 11 commits into
mainfrom
write-replaces-existing-file
Draft

shcheklein wants to merge 11 commits into
mainfrom
write-replaces-existing-file

Conversation

@shcheklein

@shcheklein shcheklein commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

A filesystem write to the path of an existing file added a second file with the same name. Now a write replaces the file when the filesystem knows that the file is there, and it still sends one request.

Example

fs.pipe_file("root/config.json", b'{"version": 1}')
fs.pipe_file("root/config.json", b'{"version": 2}')

fs.ls("root")                    # before: ['root/config.json', 'root/config.json']
fs.cat_file("root/config.json")  # before: either version

Drive allows two files with the same name. Reads of that path pick the file with the lowest ID, which on real Drive is effectively random. So a program that rewrote a file could keep reading the old content.

After: one config.json, holding version 2. It is the same Drive file as before, so its ID, sharing and links do not change.

Which files a write replaces

Drive has no "create unless the name exists", so only a lookup can tell whether a file is there. Instead of a lookup per write, the filesystem uses what it already knows:

  • files it wrote or copied;
  • files it found by their path: exists(), info(), or a read (open, cat_file, get_file).

It keeps the latest 10,000 of these, about 350 bytes each, so at most about 3.5 MB. It also keeps the latest 10,000 names it removed a file from, so a lookup that started earlier cannot bring that file back: up to about 3 MB more. Listings (ls, find, walk, glob, du) add none, so walking a large remote keeps nothing.

Any other write creates a new file without asking Drive, as before. To replace a file that another client or an earlier process wrote, call fs.exists(path) first.

Requests per write

Write main previous push now
to a new path 1 2 1
to a path the filesystem knows 1 (adds a duplicate) 2 1 (replaces)
to a known file that another client deleted, trashed, moved or renamed 1 2 2

One exception: Drive reports the real ID of root or appDataFolder as the parent, so the first replace there of a file the filesystem only looked up also reads that ID, once per filesystem. An upload there teaches the filesystem the ID for free.

DVC asks the remote which objects it already has and uploads only the missing ones, so its uploads stay at one request each and never meet an existing file.

The rules

  • pipe_file(), put_file(), open(path, "wb") and touch() replace the content of a known file. The file keeps its ID, sharing and type: a .json file stays application/json.
  • When exists() found several files with the name, also in two same-name folders, the write replaces the one that reads return. An upload, copy or move that adds a file with the name keeps the lower known ID, so writes keep going to the file that reads return. A lookup's answer replaces what the filesystem knew under each parent it read, so a file it no longer finds is forgotten.
  • A lookup that invalidate_cache() or a folder change overtook records nothing.
  • Writing to the path of a folder the filesystem knows raises IsADirectoryError, and to the path of a known Google Docs file or shortcut PermissionError, before any bytes are sent.
  • Drive returns the file's trashed, name and parents with every update. If another client trashed, moved or renamed the known file, or Drive answers 404, the filesystem forgets it and creates a new file at the path. The new content also reaches the changed file, whose earlier content stays in its Drive revisions. This replaces the earlier FileNotFoundError, since without a lookup an outdated entry is normal.
  • rm_file() and mv() keep the known files in step: after rm_file a write creates, and after mv a write to the new path replaces the moved file. invalidate_cache() forgets all known files.
  • Threads that write one path through the same filesystem take turns, so they leave one file. A write to a name that mkdir is creating waits for it and then raises IsADirectoryError. Other filesystem instances and other clients do not share this lock.

The fsspec guide (new "Writing files" section) and the upgrade guide describe this.

Not changed

  • cp_file onto an existing file still adds a second file.
  • mv onto an existing file still raises NotADirectoryError.

Both change in a separate PR.

Validation

Live, on real Drive, each test in its own folder:

  • a write to a new path sends only files.create;
  • a second write to the same path sends only files.update and leaves one file with the new content;
  • a write after another client created the file adds a second file and leaves the first one untouched (the accepted gap);
  • after exists(), pipe_file, open("wb") and a 2 MiB put_file (a resumable upload) each replace the other client's file, which keeps its application/json type and stays the only file;
  • after exists(), touch() and pipe_file(path, b"") empty the file;
  • after exists() on two files of the name, the one with the lower ID gets the new content and the other keeps its own;
  • after exists() on a file in the second of two same-name folders, the write replaces that file and adds nothing to the other folder;
  • a replace whose answer is lost is repeated and leaves one file with the new content;
  • after another client trashed, deleted, renamed or moved the known file, the next write creates exactly one new file at the path, with the new content;
  • the same for a known file directly in root that another client moved into a folder;
  • after rm_file, a write sends only files.create; after mv, a write to the new path sends only files.update;
  • a write to the path of a folder made by makedirs raises IsADirectoryError, and no file appears;
  • after exists(), a write to a Google Doc or a shortcut raises PermissionError.

Offline:

  • two threads race on one filesystem: a write to a new path waits for the other thread's create and then replaces that file, and a write to a name that mkdir is creating waits and raises IsADirectoryError;
  • after 10,001 writes, the first path is no longer known and the next write to it creates a file (about 8 s, as it really makes the 10,001 writes);
  • after exists() found file A and cp_file added B at the path, a write replaces A;
  • a lookup paused while another thread calls invalidate_cache() records nothing, so the next write creates;
  • after a second exists() no longer finds file A in one of two same-name folders, a write replaces B, the one it found.

The last three fail without their fixes.

The offline expectations that the lookup had changed are back to main's. The offline suite passes with the current google-auth (539 passed). With google-auth 2.15.0 every filesystem test passes; 5 settings-file tests fail there on main too.

🤖 Generated with Claude Code

shcheklein and others added 2 commits December 2, 2026 19:29
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 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/test/test_fs.py Resolved

@shcheklein shcheklein left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI generated — Copilot]

5-pass review summary: important semantic fix for overwrite behavior, with real issues to address around MIME type clobbering, 2x request cost on new folders, in-process concurrent upload races, concurrent-delete 404s, and missing retry/truncation tests.

Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/test/test_fs.py Resolved
… 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 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues remain for the filesystem changes that replace existing content while preserving Drive file identity and sharing.

No open issues 🎉

What changed in this PR

Updates filesystem writes to replace existing file content instead of creating duplicates, preserving the Drive file’s ID, type, and sharing.

Changes:

  • Matches write targets to read resolution and rejects folders, Google Workspace files, and shortcuts.
  • Serializes same-path writes within one filesystem instance and retries content replacements after connection failures.
  • Adds overwrite and concurrency tests and documents the changed behavior.
File Description
pydrive2/​test/​test_fs.py Adds live coverage for replacement, identity preservation, retries, and rejected targets.
pydrive2/​test/​test_fs_unit.py Tests concurrent writes and updates expected lookup requests.
pydrive2/​fs/​spec.py Implements target lookup, validation, locking, and content replacement.
docs/​upgrading.rst Explains changed write behavior and errors.
docs/​fsspec.rst Documents replacement semantics and concurrency limits.

Review effort: Balanced

shcheklein and others added 2 commits December 4, 2026 12:22
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
@shcheklein shcheklein changed the title Replace the content of an existing file on a write Replace a known file on a write, without a lookup per write Dec 4, 2026
@shcheklein
shcheklein requested a balanced review from Copilot December 4, 2026 20:31

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved file-identity and cache-invalidation bugs can leave root paths missing, make reads and writes target different files, and cause writes to update stale file IDs.

3 open issues

Review effort: Balanced

Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
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 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Critical cache invalidation and reconciliation flaws leave stale entries that can cause writes to create duplicates instead of replacing existing files.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

High severity Clear cache under the directory lock

pydrive2/​fs/​spec.py:709

The clear is still outside _dirs.lock. A lookup can publish a known file after this clear but before invalidation acquires the lock and increments the generation; the entry then survives the completed invalidation, so the next write updates it instead of creating. Move the clear inside the same locked section as the generation change.

High severity Remove stale cached candidates when reconciling lookups

pydrive2/​fs/​spec.py:880

After a lookup learns lower-ID A and B in two same-name folders, deleting or moving A externally and looking up the path again leaves A cached even though the lookup now finds only B. The next write selects stale A and creates a duplicate rather than replacing B, so reads can still return B's old content. Reconcile cached candidates across all queried parent/name pairs, including those with no match, before publishing the lookup results.

3 resolved since last review

Review effort: Balanced

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 <noreply@anthropic.com>
@shcheklein

Copy link
Copy Markdown
Member Author

AI generated · Claude · On the two "previously missed issues" in Copilot's second review (no inline threads), both fixed in 4fe00e7:

  • Clear the cache under the directory lock. invalidate_cache() now clears the known files inside the same _dirs.lock section that bumps the generation. A lookup records its files under that lock and only if the generation is unchanged, so it records either before the clear or not at all.
  • Remove stale candidates when a lookup runs again. A name lookup now replaces what was known under every parent it read, including parents where it found nothing. Offline test: test_write_after_exists_no_longer_finds_a_known_file_replaces_the_other learns A and B in two same-name folders, looks up again and finds only B, then checks that the write replaces B. It fails without the change.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human review is needed to assess lookup races and file-tracking edge cases that can cause later writes to overwrite moved files or select incorrect replacement targets.

No open issues 🎉

Review effort: Balanced

Main refuses a write directly under a trashed root and rm_file of a
trashed root. Writes here build the parent list themselves, so a direct
child now gets the root through _get_item_id, and rm_file keeps its
lookup for the known files and reads the root first. The tests keep
main's create_on_drive, which now takes extra metadata.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

An unresolved cache race can create duplicate files, while folder-move handling and multi-parent file caching can cause writes to create or update the wrong file.

3 open issues

Review effort: Balanced

Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
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 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Listing-only lookups incorrectly make files eligible for replacement, and an unlocked known-file read can race with refreshes and create duplicates.

2 open issues
3 resolved since last review

Review effort: Balanced

Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
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 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because unpublished findings identify parent-cache inconsistencies that can cause subsequent writes to create duplicate files.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved cache and path-resolution bugs can restore removed file mappings, causing writes to overwrite moved or trashed files or create duplicates.

5 open issues

Review effort: Max

Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
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 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants