Skip to content

Cache Drive folders by parent ID and exact name - #420

Merged
shcheklein merged 17 commits into
mainfrom
fs/directory-edge-cache
Nov 30, 2026
Merged

shcheklein merged 17 commits into
mainfrom
fs/directory-edge-cache

Conversation

@shcheklein

@shcheklein shcheklein commented Nov 28, 2026 •

Copy link
Copy Markdown
Member

Fixes #413.

What changes for filesystem users

  • A folder keeps its cached children when it moves. If two Drive folders are both named dup, renaming one leaves the other folder’s children under dup. This applies to fs.mv() and to moves discovered in a fresh listing.
  • A successful ls() or find() refreshes the folders under each parent it listed. On main, ls("root") could return an empty list and the next exists("root/gone") could still return true. A slower lookup could also put that folder back after the empty listing.
  • When a file and folder share a name, cold and warm reads now use the same ID selection rule. On main, two consecutive opens selected file A and then folder Z. The regressions also cover uploading, copying, and moving a file beside a cached folder, including a folder discovered while a rename is in flight. A warm descendant lookup reuses known folders even when an ancestor or mount shares its name with a file. Warm ls() and find() on a folder that shares its name with a file each take one Drive list request.
  • When a batched response omits a child's parent, find() uses name-filtered queries and verifies the Drive ID before assigning a path. For one missing ID it checks the first parent and then narrows the remaining candidates by halves. Across all 50 possible parent positions, a simulated one-page listing took 3–10 requests total, including the two initial list calls. With several missing IDs a probe can locate several children and up to 50 parents may need querying. Normal responses need no probes.

How the cache works

Each filesystem indexes folder IDs by their physical parent and exact name. A reverse index records the parent and name of each folder. Moving an ID changes one edge. Evicting a directory walks the affected subtree. Bounded traversal gathers warm parents starting at the requested folder.

A query publishes only after all its pages and batches succeed. Explicit invalidation advances an instance generation. Each listing receives a revision when it starts. A newer observation of a folder ID takes precedence across names and parents. Retiring a subtree also prevents older in-flight reads from repopulating it. After an unrelated invalidation, an operation already in flight can finish using its previously resolved parents, but subsequent lookups in that operation bypass the current cache and their results cannot warm it. A long traversal can therefore need several refills on the next run. File metadata stays out of the persistent directory cache.

Drive calls run outside the shared cache lock. Large listings and subtree evictions still hold it while updating their affected edges in memory. Folder creation uses a separate lock per parent and name so unrelated uploads can create folders concurrently.

DVC request counts

On a simulated Drive with two folders named files/md5 and 256 populated prefixes under one of them, a full listing warms folder lookups across both parents. Listing each prefix takes 256 requests, finding each takes 256, and uploading one file per prefix takes 512. Warm existence checks take zero requests. Duplicate-parent comparison

Measured public operations with DVC 3.67.1, dvc-gdrive 3.0.1, dvc-objects 5.3.1 and dvc-data 3.18.3 over a simulated Drive HTTP transport. Both branches gave the following counts with fsspec 2024.2.0 and 2026.9.0. The traversal fixture contains one object in each of 251 two-character prefixes.

Operation Requests on main and this PR
Traverse all prefixes, cold / warm 7 / 6
Check 1 / 24 object IDs on a warm filesystem 1 / 7
Enumerate all 251 object IDs through the object database 7
Stream to a warm prefix 2
Two consecutive put_file calls to an initially warm prefix 2, then 3

Two concurrent streams to the same cold prefix used one folder lookup, one folder creation, and two content uploads. Two distinct cold prefixes used one lookup and one creation each. The second creation could finish while the first was blocked. An explicit invalidation between concurrent operations still forces a fresh lookup. The original five-cold and one-warm request assertions remain covered.

Large DVC remotes

Measured with HashFileDB.all(jobs=4) on the real DVC and PyDrive2 clients over a simulated Drive transport, after listing files/md5. Each remote had 256 populated prefixes and pages of up to 1,000 objects. Values are medians of three fresh processes per revision on CPython 3.12. Peak RSS is the increase above the warmed process. CPU timings exclude network latency.

Objects Requests on main / c89809b / c1541ac Local CPU, c89809b / c1541ac Peak RSS, c89809b / c1541ac
1,048,576 1,536 / 1,280 / 1,280 7.32 / 5.59 s 50 / 45 MiB
2,097,152 2,560 / 2,304 / 2,304 14.55 / 10.84 s 63 / 61 MiB

Both PR revisions retained 258 folder IDs and zero file IDs, about 65 KiB at either remote size. Temporary memory depends on prefix size and concurrent listings. At c1541ac the filesystem consumes metadata pages directly. The public GoogleDrive.ListFile() iterator still returns file objects. A names-only find() over 65,536 files took 0.175 CPU seconds, down from 0.284, with 66 requests on both revisions. A run of 100,000 warm exists() / makedirs(exist_ok=True) pairs made zero requests. Uploading 4,096 one-byte objects through DVC used the same request counts on both revisions.

Path resolution now keeps the configured mount and cache generation together for one operation. New public regression tests cover two edge cases. If Drive reports the same file again without its parent and subsequent probes find it nowhere, find() drops the earlier path. When the last matching folder is removed or renamed through the filesystem, duplicate parents release cached names that only recorded its absence.

Local performance and tradeoffs

Measured at 2a80989, before the review fixes. Median process CPU time in µs for repeated public operations on the same simulated transport. The invalidation case removes and rewarms a cached nested folder between samples. The unrelated folders were already warm.

Operation Main This PR
Invalidate a small subtree beside 100 / 1,000 / 5,000 other folders 41 / 374 / 1,966 4 / 4 / 4
Depth-limited find in a small subtree beside 5,000 other folders 861 690
Warm directory existence at depth 12 / 128, zero requests 2 / 4 2 / 12
Warm existence when all 251 same-name parents contain the child, zero requests 5 1
Warm existence when only the first / last of 251 parents contains the child, zero requests 2 / 2 1 / 15

Following edges costs more CPU for very deep paths and many same-name parents. For the 251-duplicate fixture, Python allocations measured with tracemalloc rose from 223 to 286 KiB retained and from 1,859 to 3,119 KiB peak. At depth 128 the corresponding figures were 353 to 346 KiB retained and 7,150 to 7,035 KiB peak. These include the SDK and test transport. Google Drive latency was outside this measurement.

The regression tests use public filesystem calls and inspect Drive HTTP requests. Coverage includes duplicate names, moves and removals, stale and incomplete responses, request batching, and concurrent creates. The offline suite passed on both fsspec versions (316 passed, 2 skipped per run). Ruff and mypy passed.

The additional review regressions cover both read completion orders, upload during folder creation, moves between traversal batches, and a move destination shared by a file and a folder. In a separate paginated 10,000-file simulation, both 51faac3 and the updated implementation made ten Drive requests for each of ls and find. Peak Python allocations for ls went from 8.4 to 8.7 MiB and for find from 17.0 to 8.1 MiB.

Large flat folder listings

At d28828b, single-folder ls() returns Drive rows in page order and retains only folder IDs for the cache. A file renamed during pagination can appear under both names. In a like-for-like comparison with b7ef2ab, peak RSS for 1,048,576 names fell from 238 to 109 MiB (1,049 requests). For 262,144 detailed entries it fell from 125 to 94 MiB (263 requests). These are medians of three fresh CPython 3.12 processes per revision over a simulated HTTP transport. Measurements and regression coverage

At 2d57699, name-only ls() requests IDs, names, parents and MIME types. Size and checksum are requested for detailed listings. Each page is reduced to compact rows, and the latest observation of an ID determines its returned entry. File-name collision tracking is limited to names that can affect a folder lookup.

Peak process RSS above startup in MiB for a warm folder, measured using CPython 3.12, fsspec 2026.9.0 and the real Drive SDK with a simulated HTTP transport serving 1,000 files per page. Each measurement used a fresh process.

Operation main 94b9d13 2d57699 Drive requests per run
Name-only ls, 65,536 files 31 93 26 66
Name-only ls, 262,144 files 112 360 94 263
Name-only ls, 1,048,576 files 426 — 337 1,049
Detailed ls, 65,536 files 30 92 39 66
Detailed ls, 262,144 files 110 353 139 263
Name-only find, 65,536 files 137 90 46 66

Detailed listings still peak above main. In the million-file name-only run, local process CPU was 5.1 seconds on the fix and 4.6 seconds on main. The transport simulated pagination and field selection. These numbers exclude network latency.

741751e also makes a folder move invalidate the destination name by its known physical parent ID when part of its path could not be cached. The regression uses duplicate folder names and a single-parent v3 response with hidden parent metadata. A subsequent rm_file() now selects the correct same-name folder.

Comment thread pydrive2/fs/cache.py Fixed

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

A critical cache bug misses file-name collisions across queried parents, causing warm reads to select a folder where cold lookups select a file.

1 open issue
What changed in this PR

Replaces PyDrive2’s path-based folder cache with parent-ID and exact-name indexing to address #413, preserve cached descendants across moves, and maintain DVC traversal request budgets.

Changes:

  • Adds edge-based cache updates, subtree invalidation, and safeguards against stale listing results.
  • Integrates the cache into filesystem operations and adds parent-attribution fallback for batched traversal.
  • Expands regression coverage and documents listing refresh and rename behavior.
File Description
pydrive2/​test/​test_fs_unit.py Adds regressions for duplicate names, moves, stale responses, and concurrent creation.
pydrive2/​test/​test_fs_listing.py Tests batching, pagination, and incomplete responses through public filesystem calls.
pydrive2/​fs/​spec.py Integrates edge-based caching into resolution, listing, traversal, and mutations.
pydrive2/​fs/​cache.py Implements directory edges, generation tracking, listing publication, and subtree eviction.
docs/​fsspec.rst Explains cache refresh and preservation of cached children across renames.

Review effort: Balanced

Comment thread pydrive2/fs/cache.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 · Claude · design and correctness review at 2a80989

The design is right: Drive IDs are stable, names are not unique, and each item has one parent. I found no correctness bugs. One performance regression is worth fixing before merge (SHOULD-1).

How I checked

  • A fake in-memory Drive with duplicate folders and files that share names with folders. One warm filesystem ran random mkdir, makedirs, touch, cp_file, mv, rm, rmdir and invalidate_cache calls. After each step, its exists, ID selection, ls, find, info and cat_file results were compared with a fresh filesystem's. 400 seeds × 150 steps: no difference.
  • The same with 8 threads × 120 operations and random delays on each Drive call, comparing every path afterwards. 60 seeds: no difference. The children/parents consistency rule held after every step.
  • The same harness finds main's file-or-folder ID bug in 6 of 40 seeds.

Comments

  • SHOULD-1: a folder name shared with a file is listed again on every operation through it. With a mount, operations also queue on _mount_lock. Tested patch inline.
  • CONSIDER-1: placing an unattributed item lists whole folders. A name query is enough.
  • CONSIDER-2: reads may not need the generation check.
  • NOTE-1: ls() now caches subfolders.
  • NIT-1, NIT-2: docs reflow, and a comment stating the children/parents rule.

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/cache.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread docs/fsspec.rst Resolved
Comment thread pydrive2/fs/cache.py Resolved

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 races can lose file-collision markers or restore stale folder names, and move destination resolution can send a file ID as a parent, causing Drive to reject the operation.

2 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Resolve move destinations using folder-only parent selection

pydrive2/​fs/​spec.py:919

The destination parent still uses final-item selection rather than folder-only resolution. If root/dest matches both file A and folder Z, warming that folder and then calling fs.mv("root/source", "root/dest") now resolves the parent to A: the collision-aware cache forces a fresh lookup, and _get_item_id() selects the minimum ID across files and folders. The move therefore sends a file ID as addParents, which Drive rejects. Resolve dst_parent with folders_only=True and select from its folder IDs, without creating missing directories.

1 resolved since last review

Review effort: Balanced

Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/fs/cache.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 (Copilot SDK in VS Code)

The edge-based design is the right direction, but I found three correctness races in the latest head: an older listing can make a newer listing unpublishable, a file completed before an in-flight folder create can be forgotten, and a moved item can be emitted under its stale path across query batches. The inline comments include deterministic public-operation reproducers.

Bigger picture: cache correctness currently depends on one global generation, pending-listing order, and separate incomplete/file_collisions state. I would make each parent/name edge own its folder IDs, file-collision state, and revision, and separate mutation invalidation from listing-observation order. That would remove the ad hoc publication rules and make these races much easier to prove.

This is a cohesive feature, but at 989 additions / 292 deletions I would also stack it: first the cache model and invariants, then filesystem integration, followed by DVC request-budget verification. That makes rollback and concurrency review materially safer.

The public, function-based tests are a good direction. The missing coverage is the ordering between different operations, not another cache internals test or a new test class.

Validation: the offline suite passed (291 passed, 2 skipped), and Ruff passed for the changed Python files.

Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/test/test_fs_unit.py Resolved
@shcheklein

Copy link
Copy Markdown
Member Author

Addressed the review findings in three commits, each with its public-operation regressions.

  • c595e52 orders competing folder observations by when the listing started and keeps a pending create visible to file writes until its POST completes. It also prevents a delayed listing from caching children under a detached parent.
  • 22b92f0 makes find() use the most recent attributable location when the same Drive ID moves between pages or parent batches.
  • 7b3f614 addresses the destination-parent finding in Copilot’s review summary. A move into a name shared by file A and folder Z sends addParents=Z. An existing file-only destination parent raises NotADirectoryError before Drive receives a mutation.

I kept the fixes on #420, with each commit passing the filesystem suite independently. A location revision belongs to the Drive ID because a rename spans two names and a move can span two parents. File collisions belong to the parent/name pair because several IDs can share that name. The mutation generation still protects operations that resolved a parent before explicit invalidation.

Both offline configurations passed (300 tests each, 2 skipped). The 251-prefix request budget remains 7 cold and 6 warm.

@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 · Claude · second pass at 7b3f614: bugs, simplification, alternatives, tests

I started at 51faac3 and moved to 7b3f614 when today's three commits landed. They already cover part of what I had found: the mv destination parent, both races from Copilot's threads, and the generation bump after a listing. I found no correctness bug at this head. What is left is one request-count regression against main, one question, and test clean-up.

How I checked, all at 7b3f614

  • Warm-vs-fresh fuzz on a stateful fake Drive. A long-lived filesystem and a new one must agree after every step. 2,250 seeds × 150 steps: root, two mounts below a folder that shares its name with a file, rows without parents, batches of 3, paging and hard delete. No difference.
  • 600 seeds with 8 threads: no difference. At 51faac3 the same runs hit the upload-during-folder-create race in 4 of 800 seeds. Another 240 seeds that also let two threads move the same item at once: 2 differences. The repro for that case gives the same result on main.
  • Both races from Copilot's threads also reproduce on main, so neither came from this PR. c595e52 closes them.
  • Main against this PR on a routing HTTP fake, for mv, ls, find and open on a name shared by a file and a folder.
  • Removed 25 single lines or blocks of cache logic one at a time and ran the 184 fs tests after each, to see which a test holds.

Comments

ID Priority What
PERF-1 Medium Warm ls and find on a folder that shares its name with a file cost 2 requests where main needs 1. Tested two-line patch.
Q-1 Medium One row without parents costs find up to 50 extra requests. Which real response does this?
TEST-1 Medium Two new guards cover for each other in their one test. Four more have no test.
TEST-2 Low One of the four tests for rows without parents duplicates another.
TEST-3 Low Three parametrized tests branch on their parameter. Branch-free version of one included.
TEST-4 Low Test names.
TEST-5 Low The two test_fs_listing.py tests fit in test_fs_unit.py with its helpers.
CLEAN-1 Low The two-parent branches cover a case Drive no longer produces, and only part of it.

ALT-1, for a follow-up: pick the ID by what the call needs. A name shared by a file and a folder resolves to the smallest ID of either kind. That is now the same warm and cold, but it is still arbitrary. open("root/item") asks Drive for a folder's content whenever the folder's ID sorts first, although a file with that name exists. Main does the same. mv and PERF-1 are the directory side of that rule. Directory calls could take folders, and content reads (open, get_file, the cp_file source) could take files. Only info, rm_file and an mv source are really ambiguous.

Tried, not recommended

  • has_directory as two contains calls: 15 fewer lines, but a child of duplicate-named parents costs one lookup the first time (main: 0).
  • Dropping the single-ID branch in _known_folder_ids: the tests pass, and each warm exists costs under 2 µs more at depth 12.

Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/test/test_fs_unit.py Resolved
Comment thread pydrive2/test/test_fs_unit.py Resolved
Comment thread pydrive2/test/test_fs_unit.py Resolved
Comment thread pydrive2/test/test_fs_listing.py Resolved
Comment thread pydrive2/fs/cache.py Resolved

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 are recorded for the folder-cache changes.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

@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 · Claude · third pass at 94b9d13: bugs, simplification, alternatives, tests

The eight threads from the last pass are fixed, and each fix checks out. This pass found one narrow bug in mv (BUG-1, tested three-line fix) and one test I would add before merge (TEST-1). The rest is small.

How I checked, all at 94b9d13

  • Warm-vs-fresh fuzz on a stateful fake Drive. A long-lived filesystem and a new one must agree after every step. 3,200 seeds × 150 steps: root, two mounts below a folder that shares its name with a file, 15 to 50% of batched rows without parents, batches of 3 and 7, paging and hard delete. No difference.
  • 650 seeds with 8 threads: no difference. Another 240 that let two threads move the same item at once: 1 difference. The repro for that case gives the same result on main.
  • 600 seeds with injected legacy two-parent files, find results not compared: 1 difference, which is BUG-1. With find compared, such files still give differences (32 of 250 seeds), as they do on main. Drive no longer produces them.
  • The new bisecting placement over all 50 positions of one row without parents: 1 to 8 probes, as the description says. With TEST-1's condition removed the fuzz fails in 106 of 150 seeds, so the fuzz covers that code. The test suite does not.
  • Removed 30 single lines or blocks one at a time and ran the 190 fs tests after each. Each of the six guards from the last pass now fails its own test.
  • Request counts against main for mv, ls, find and exists on a name shared by a file and a folder: equal.

Comments

ID Priority What
TEST-1 Medium No test holds the len(missing) == 1 condition of the bisect. Without it find drops files. Test included.
BUG-1 Low mv of a folder the cache does not know marks the destination by path, not by ID. A warm lookup can then miss the moved folder. Needs an uncacheable lookup on the way. Fix and test included.
TEST-2 Low No test holds clearing the file mark after the file is gone. Test included.
CLEAN-1 Low Seven lines that preserved ID order are dead since c595e52.
TEST-3 Low The concurrency helper's call sites pass up to eight positional arguments. Keyword version included.
TEST-4 Low Two request hooks assert what the tests' last lines already assert.
NIT-1 Low One function-local import.

Alternatives. Nothing new. ALT-1 (pick the ID by what the call needs) stays a follow-up, as agreed in the last thread.

Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/test/test_fs_unit.py Resolved
Comment thread pydrive2/test/test_fs_unit.py Resolved
Comment thread pydrive2/test/test_fs_unit.py Resolved

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

The required live Drive CI suite fails because the caching test still spies on the bypassed ListFile method instead of _query_children, leaving its call-count assertions incorrect.

1 open issue

Review effort: Balanced

Comment thread pydrive2/fs/spec.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 (Copilot SDK in VS Code)

Careful review at 535085c covering correctness, performance, and downstream implications.

The edge-based DirectoryCache design, deadlock-free lock hierarchy ({_mount_lock, creation_lock} -> _root_lock -> _dirs.lock), subtree-scoped invalidation, and _FileMetadataPages fast path are strong improvements over main.

Summary of findings (details inline):

  • Bug (High): DirectoryCache.moved() can attach a moved subtree under an uncached parent, orphaning it in self.children/self.parents so path-scoped invalidate_cache() cannot evict it and a later attachment resurrects stale descendants.
  • Bug (Medium): DirectoryCache.moved() loses old.parent in its fallback branch on an in-place rename when an ancestor moved concurrently (same pattern for in-place file renames in mv()).
  • Bug (Low/Edge): _relink() can form a detached A <-> B cycle if an external parent/child inversion is observed by listing only the child.
  • Performance & tradeoffs: detail=True ls() peak RSS (+26% at 262k files), double-pass observe() and ambiguous bail-out on single-parent legacy multi-parent files, global generation/retired blast radius under mixed concurrency, duplicate-parent child misses after full ls(), and linear probing in _locate_children() when len(missing) >= 2.
  • Implications: ls() warming the cache widens external-staleness/unbounded-growth surface (already documented for staleness in docs/upgrading.rst), and bypassing fs.client.ListFile in _query_children() breaks downstream mocks/subclasses wrapping ListFile.

Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/fs/cache.py Resolved
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

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

The revision-ordered parent-edge cache affects destructive operations and concurrent writes, warranting human review of publication/retirement invariants and live Drive validation beyond the supplied simulated-transport regressions.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@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 · Claude · fourth pass at b7ef2ab: performance, memory, races, edge cases

I found no wrong result at this head. What is left is two performance items, one missing test and one small edge.

  • PERF-1 is the only place where this PR asks Drive more than main does without buying correctness. It needs two folders with the same name. Tested patch included.
  • PERF-2 is a decision: the ID index in ls costs about half of the call's peak memory.

How I checked, all at b7ef2ab, on a simulated transport (nothing here ran against live Drive)

  • Warm-vs-fresh fuzz on a stateful fake Drive. A long-lived filesystem and a new one must agree after every step, and every cached edge must match Drive. 17,500 seeds × 40 steps: root, a folder ID as root, mounts, pages of 1 to 3, batches of 2 and 3, rows without parents, hard delete, and changes made behind the filesystem. No difference. On the same harness main differs in 151 of 600 seeds.
  • Races. 1,450 seeds with 8 to 16 threads, 150 of them letting two threads move the same item. Then about 19,800 interleavings of two or three operations, where the others run to completion at each request boundary of the first, once before Drive answers and once after. No difference and no deadlock. The interleaving run does catch a removed barrier (file_added without its pending-read invalidation: 4 of 200 seeds).
  • Guards. Removed 57 single guards one at a time. The 206 fs tests catch 46. The fuzz reaches one of the other 11 (TEST-1). For the remaining 10 I found no public sequence that depends on them: they need legacy two-parent rows, rows without parents, an item that changes between file and folder, or the root listed as its own descendant, or they only save requests.
  • Requests against main, same operations on the same Drive state: 600 seeds, 16,424 steps, 27,478 requests on main and 27,629 here. The PR asks more in 374 steps and less in 195. Each of the 374 is a lookup that main answered from its path cache: a last path component that could also be a file (intended, main can pick the wrong ID there), or PERF-1. With the PERF-1 patch the total is 27,459.
  • Memory and CPU with the real SDK, CPython 3.12, medians of three fresh processes. Request counts are equal in every row.
main this PR
names-only ls, 1,048,576 files, peak MiB 436 251
detailed ls, 262,144 files, peak MiB 112 125
names-only find, 1,048,576 files in 256 folders, peak MiB 1,941 340
detailed find, 262,144 files in 256 folders, peak MiB 497 168
kept per folder after find over 100,000 folders, bytes 306 333
warm exists on a folder, no request, µs 2.0 1.1

Comments

ID Priority What
PERF-1 Medium After ls or find has listed two same-name folders, the first lookup of each child folder costs a request that main does not make: 512 vs 256 on a 256-prefix fixture. Patch and test included.
PERF-2 Low, your call The ID index in single-folder ls is about half of its peak memory: 251 vs 120 MiB for a million names. It only handles a row that Drive repeats across pages.
TEST-1 Low No test holds the mount check in has_directory. Test included.
EDGE-1 Low find(detail=True) keeps one entry per path. When a file and a folder share a path below two same-name parents, find(withdirs=True, detail=True) can report the file while info() reports the folder, which has the lower ID. Same on main. Optional patch and test in the thread; it costs memory.

Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
Comment thread pydrive2/fs/cache.py Resolved
Comment thread pydrive2/fs/spec.py Resolved
@shcheklein
shcheklein merged commit 0104333 into main Nov 30, 2026
23 checks passed
@shcheklein
shcheklein deleted the fs/directory-edge-cache branch November 30, 2026 05:23
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.

Redesign the Drive folder-ID cache around parent edges and preserve DVC traversal budgets

2 participants