Skip to content

Handle virtual directories in recursive copies and moves - #2448

Open
MonikaDvorackova wants to merge 3 commits into
fsspec:masterfrom
MonikaDvorackova:fix/recursive-object-store-move-2447
Open

MonikaDvorackova wants to merge 3 commits into
fsspec:masterfrom
MonikaDvorackova:fix/recursive-object-store-move-2447

Conversation

@MonikaDvorackova

@MonikaDvorackova MonikaDvorackova commented Nov 10, 2026 •

Copy link
Copy Markdown

Summary

Fixes #2447.

Recursive copy/move on object stores must distinguish virtual directories from actual objects, including slash-suffixed directory markers.

This revision reuses detailed metadata collected during recursive path expansion rather than issuing an additional per-path info() / _info() lookup.

Sync and async implementations are covered, along with explicit path lists, depth-limited copies and moves, and preservation of source data on copy failure.

Validation — 2026-11-25

  • Full local fsspec test suite: 1,253 passed, 231 skipped, 2 xfailed, 0 failed (Python 3.12, macOS).
  • All 33 targeted regression tests passed.
  • Eight local GCS emulator benchmark scenarios completed successfully.
  • Recursive copies of 50 and 100 ordinary files required 54 and 104 requests respectively.
  • Explicit source/destination lists required 50 and 100 requests, with no extra per-file metadata lookups.
  • Ruff formatting and git diff --check passed.

The benchmark results are from a local emulator and are not directly comparable to real GCS or HNS measurements.

Limitations

The local GCS emulator did not reliably reproduce slash-suffixed marker objects. Marker regression tests therefore use simulated flat-store metadata.

Real GCS marker preservation, HNS correctness, and HNS performance remain unverified. Optional downstream backends and other Python versions were not fully tested.

AI assistance

An OpenAI coding assistant assisted with implementation, test design, and debugging. Changes were validated locally before the update was pushed.

@martindurant martindurant left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I believe part of the change that this is fixing, is to ensure that directory markers also get copied on a backend like s3 - but I think this PR would undo that. Getting it right might be as simple as replacing isdir with (not isfile).

A more comprehensive solution might be to have _expand_path (optionally) return detailed listings, like glob/find, so that we have the file/not file distinction readily available.

Comment thread fsspec/asyn.py Outdated
Comment on lines +585 to +586
if recursive and await self._isdir(p1):
await self._makedirs(p2, exist_ok=True)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This should be fast when the listings are all in dircache - is that guaranteed since we are already doing a recursive operation in this root?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For gcsfs, the two directory copies I ran on a flat bucket with the default listings cache made the same number of calls as on the merge-base. The other cases made more. API calls started by gcsfs for one recursive copy, fresh filesystem instance each time:

Workload Merge-base This PR
Flat, 100 files in 10 dirs 115 115
Flat, 50 files in 56 dirs 110 110
HNS, 50 files in 56 folders 110 223–237
HNS, 100 files in 10 folders 115 137
Flat, 100 files in 10 dirs, use_listings_cache=False 115 372–385
Flat, 50 files in 56 dirs, use_listings_cache=False 110 339–348
20 files passed as two lists, recursive=True 20 66–72

Counts cover the JSON API and Storage Control. Where a range is given, it is what I saw over six runs (sixteen for the first HNS row); the merge-base count was the same in every run. In the last three rows gcsfs cancels some calls when a parallel lookup answers first (89–92, 43–50 and 18–20 of them); they are included.

On HNS the extra calls come from makedirs, not from info: each one is a bucket get or a lookup or create of a destination folder, and none targets the source. For 56 folders the copy took 3.8 s instead of 2.8 s (medians of ten runs each; ranges 3.6–4.2 s and 2.8–2.9 s).

With the cache off, the source lookups go to the server. For lists, _expand_path is skipped, so the cache is cold.

With s3fs 2026.9.0 against moto, for the 100-file and the 56-directory tree: 113 and 108 calls on both the merge-base and this branch with the default cache; with the cache off, 335 against 235 and 320 against 270.

Comment thread fsspec/asyn.py Outdated
batch_size = batch_size or self.batch_size
coros = [self._cp_file(p1, p2, **kwargs) for p1, p2 in zip(paths1, paths2)]

async def copy_path(p1, p2):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This doesn't need to be dynamically defined.

@MonikaDvorackova

Copy link
Copy Markdown
Author

Thanks for the review. I've pushed commit fc813a8 to address the feedback.

  • Recursive sync and async copies now distinguish file objects, including directory markers, from virtual directories using info() / _info().
  • The async copy helper is now a class method rather than a dynamically defined nested function.
  • Added sync and async regression tests for directory-marker preservation.

Each path now requires one explicit metadata lookup for classification. I can't guarantee that this is served from dircache on every backend. Detailed recursive listings could provide a further optimization, but I've kept the existing expand_path() interface unchanged.

Local validation: 441 passed, 73 skipped, 1 xfailed. Ruff formatting and git diff --check passed.

Ready for another review.

@martindurant

Copy link
Copy Markdown
Member

@ap-- - I expect this fixes the issue, but would you have time to test if it causes serious slowdown in any of your cases?

@ap--

ap-- commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

@MonikaDvorackova Thanks for the PR!

@martindurant I should be able to find time to verify and run benchmarks next week. Will report back once completed!

Comment thread fsspec/asyn.py Outdated
Comment on lines +600 to +604
async def _copy_path(self, path1, path2, recursive=False, **kwargs):
if recursive and (await self._info(path1))["type"] == "directory":
await self._makedirs(path2, exist_ok=True)
else:
await self._cp_file(path1, path2, **kwargs)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

On a flat GCS bucket this drops directory placeholders. A new folder in the Cloud console is stored as a 0-byte object named name/. gcsfs lists it, but info("…/name/") strips the trailing slash and returns type: "directory", so the path goes to makedirs, which creates nothing on a flat bucket.

Copying a prefix with the default on_error:

Source objects Merge-base This PR
data.txt, empty_dir/, full_dir/, full_dir/x.txt all four copied data.txt and full_dir/x.txt only
data.txt, marker/ (14 bytes), default listings cache both copied data.txt only, no error, also with on_error="raise"

The first row is the same with use_listings_cache=False. In the second row, with the cache off, marker/ is copied.

I also ran this branch with not isfile in place of the info check: the results are identical. gcsfs returns isfile("…/empty_dir/") == False, with a warm or a cold listings cache.

With s3fs 2026.9.0 against moto, the merge-base does not copy these objects either, so on s3fs this is not a regression.

The sync loop in spec.py uses the same check.

Comment on lines +80 to +148
class MarkerAwareMemoryFS(ObjectStoreMemoryFS):
"""Simulate a backend where a directory marker is also a file."""

def isdir(self, path):
if path.rstrip("/") == "/src/marker":
return True
return super().isdir(path)

def isfile(self, path):
if path.rstrip("/") == "/src/marker":
return True
return super().isfile(path)

def cp_file(self, path1, path2, **kwargs):
if path1.rstrip("/") == "/src/marker":
return MemoryFileSystem.cp_file(self, path1, path2, **kwargs)
return super().cp_file(path1, path2, **kwargs)


def test_recursive_copy_preserves_directory_marker():
fs = MarkerAwareMemoryFS(skip_instance_cache=True)
fs.store.clear()
fs.pseudo_dirs[:] = [""]

try:
fs.pipe("/src/data.txt", b"data")
fs.pipe("/src/marker/", b"marker-content")

fs.copy("/src", "/dst", recursive=True, on_error="raise")

assert fs.cat("/dst/data.txt") == b"data"
assert fs.cat("/dst/marker") == b"marker-content"
finally:
fs.store.clear()
fs.pseudo_dirs[:] = [""]


class AsyncMarkerAwareFS(AsyncObjectStoreFS):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.store = MarkerAwareMemoryFS(skip_instance_cache=True)

async def _info(self, path, **kwargs):
if path.rstrip("/") == "/src/marker":
return {
"name": "/src/marker",
"size": len(self.store.cat("/src/marker")),
"type": "file",
}
return await super()._info(path, **kwargs)


def test_async_recursive_copy_preserves_directory_marker():
fs = AsyncMarkerAwareFS(skip_instance_cache=True)
store = fs.store
store.store.clear()
store.pseudo_dirs[:] = [""]

try:
store.pipe("/src/data.txt", b"data")
store.pipe("/src/marker/", b"marker-content")

fs.copy("/src", "/dst", recursive=True, on_error="raise")

assert store.cat("/dst/data.txt") == b"data"
assert store.cat("/dst/marker") == b"marker-content"
finally:
store.store.clear()
store.pseudo_dirs[:] = [""]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

These two tests pass without exercising a directory marker. MemoryFileSystem._strip_protocol removes the trailing slash, so pipe("/src/marker/", ...) stores an ordinary file at /src/marker, and info() already reports it as a file. During the copy isdir is never called for /src/marker, so the override has no effect.

test_recursive_copy_empty_directory has a similar gap: it passes because MemoryFileSystem.makedirs creates a real directory. With a makedirs that creates nothing, as on a flat bucket, /dst/empty is not a directory after the copy.

@MonikaDvorackova
MonikaDvorackova force-pushed the fix/recursive-object-store-move-2447 branch from fc813a8 to 59cedbf Compare November 25, 2026 14:43
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.

Recursive mv() of a directory fails on object stores since 2026.6.0

4 participants