diff --git a/docs/source/python/api/filesystems.rst b/docs/source/python/api/filesystems.rst index 4bf61e41974c..7f1cd9800d31 100644 --- a/docs/source/python/api/filesystems.rst +++ b/docs/source/python/api/filesystems.rst @@ -29,6 +29,7 @@ Interface :toctree: ../generated/ FileInfo + FileInfoIterator FileSelector FileSystem diff --git a/python/pyarrow/_fs.pxd b/python/pyarrow/_fs.pxd index 0df75530bbd6..76918eb0fc4f 100644 --- a/python/pyarrow/_fs.pxd +++ b/python/pyarrow/_fs.pxd @@ -53,6 +53,25 @@ cdef class FileSelector(_Weakrefable): cdef inline CFileSelector unwrap(self) nogil +cdef class FileInfoIterator(_Weakrefable): + cdef: + object iterator_owner + object iteration_lock + FileSelector selector + vector[CFileInfo] batch + size_t batch_index + c_bool started + c_bool finished + SharedPtrNoGIL[CFileInfoVectorIterator] iterator + + @staticmethod + cdef wrap(object owner, FileSelector selector) + + cdef _start(self) + + cdef _close(self) + + cdef class FileSystem(_Weakrefable): cdef: shared_ptr[CFileSystem] wrapped diff --git a/python/pyarrow/_fs.pyx b/python/pyarrow/_fs.pyx index 10b6ac52dd55..4b213563f759 100644 --- a/python/pyarrow/_fs.pyx +++ b/python/pyarrow/_fs.pyx @@ -27,6 +27,7 @@ from pyarrow.util import _stringify_path from abc import ABC, abstractmethod from datetime import datetime, timezone +from threading import Lock import os import pathlib import sys @@ -408,6 +409,100 @@ cdef class FileSelector(_Weakrefable): return f"" +cdef class FileInfoIterator(_Weakrefable): + """ + An iterator over FileInfo objects produced by a file selector. + + Create an iterator with ``FileSystem.get_file_info_iterator()``. + + File discovery starts on the first ``next()`` call, not when the + iterator is created. Entries are fetched from the filesystem in + batches and yielded one at a time. Iteration releases its resources + on exhaustion or error. Call ``close()`` to release them when + stopping early. Concurrent calls to ``next()`` or ``close()`` on the + same iterator raise ``ValueError``. + """ + + def __cinit__(self): + self.iteration_lock = Lock() + self.batch_index = 0 + self.started = False + self.finished = False + + def __init__(self): + raise TypeError( + "FileInfoIterator cannot be instantiated directly; " + "use FileSystem.get_file_info_iterator() instead") + + @staticmethod + cdef wrap(object owner, FileSelector selector): + cdef FileInfoIterator self = \ + FileInfoIterator.__new__(FileInfoIterator) + self.iterator_owner = owner + self.selector = selector + return self + + def __iter__(self): + return self + + def __next__(self): + cdef CFileInfo info + if not self.iteration_lock.acquire(blocking=False): + raise ValueError("iterator already executing") + try: + if self.finished: + raise StopIteration + try: + if not self.started: + self._start() + while self.batch_index == self.batch.size(): + with nogil: + self.batch = GetResultValue( + self.iterator.get().Next()) + self.batch_index = 0 + if self.batch.empty(): + raise StopIteration + info = self.batch[self.batch_index] + result = FileInfo.wrap(info) + self.batch_index += 1 + return result + except BaseException: + self._close() + raise + finally: + self.iteration_lock.release() + + def close(self): + """Stop iteration and release the underlying C++ resources.""" + if not self.iteration_lock.acquire(blocking=False): + raise ValueError("iterator already executing") + try: + self._close() + finally: + self.iteration_lock.release() + + cdef _start(self): + cdef: + CFileSelector c_selector = self.selector.selector + shared_ptr[CFileSystem] filesystem = \ + ( self.iterator_owner).wrapped + CFileInfoVectorIterator iterator + with nogil: + iterator = MakeFileInfoVectorIterator(filesystem, c_selector) + self.iterator = make_shared[CFileInfoVectorIterator](move(iterator)) + self.started = True + + cdef _close(self): + cdef vector[CFileInfo] empty_batch + with nogil: + self.iterator.reset() + self.batch.swap(empty_batch) + self.batch_index = 0 + self.finished = True + self.iterator_owner = None + self.selector = None + + cdef class FileSystem(_Weakrefable): """ Abstract file system API. @@ -620,6 +715,45 @@ cdef class FileSystem(_Weakrefable): return [FileInfo.wrap(info) for info in infos] + def get_file_info_iterator(self, FileSelector selector not None): + """ + Get file information from a selector as an iterator of FileInfo. + + Unlike :meth:`get_file_info`, which returns a list once the whole + selection has been listed, this method returns an iterator that + yields ``FileInfo`` objects one at a time. File discovery starts + on the first ``next()`` call, and entries are fetched from the + filesystem in batches. + + Whether discovery is actually incremental depends on the + filesystem. ``LocalFileSystem`` and ``S3FileSystem`` expose batches + as discovery progresses, allowing processing to overlap with listing. + Other filesystems, including ``GcsFileSystem``, + ``AzureFileSystem``, ``HadoopFileSystem`` and ``PyFileSystem`` + (which backs the fsspec integration), currently list the whole + selection on the first ``next()`` call and then yield it from + memory; for those, stopping early saves no listing work. In all + cases the entries yielded are the same as ``get_file_info``. + + The order in which entries are yielded is not guaranteed. + + Call :meth:`FileInfoIterator.close` to release resources when + stopping early; exhausting the iterator releases them + automatically. Filesystems that prefetch results may already have + started work that closing does not cancel. + + Parameters + ---------- + selector : FileSelector + The selector describing the directory to list. + + Returns + ------- + FileInfoIterator + A closeable iterator yielding ``FileInfo`` objects. + """ + return FileInfoIterator.wrap(self, selector) + def create_dir(self, path, *, bint recursive=True): """ Create a directory and subdirectories. diff --git a/python/pyarrow/fs.py b/python/pyarrow/fs.py index 670ccaaf2455..f4a448e63e8a 100644 --- a/python/pyarrow/fs.py +++ b/python/pyarrow/fs.py @@ -25,6 +25,7 @@ FileSelector, FileType, FileInfo, + FileInfoIterator, FileSystem, LocalFileSystem, SubTreeFileSystem, diff --git a/python/pyarrow/includes/libarrow_fs.pxd b/python/pyarrow/includes/libarrow_fs.pxd index 19b663c863e3..3807e61bc37a 100644 --- a/python/pyarrow/includes/libarrow_fs.pxd +++ b/python/pyarrow/includes/libarrow_fs.pxd @@ -21,6 +21,16 @@ from pyarrow.includes.common cimport * from pyarrow.includes.libarrow cimport * from pyarrow.includes.libarrow_python cimport CTimePoint +cdef extern from "arrow/python/filesystem_iterator.h" namespace "arrow::py::fs" nogil: + cdef cppclass CFileInfoVectorIterator \ + "arrow::py::fs::FileInfoVectorIterator": + CResult[vector[CFileInfo]] Next() + + CFileInfoVectorIterator MakeFileInfoVectorIterator( + const shared_ptr[CFileSystem]& filesystem, + const CFileSelector& selector) + + cdef extern from "arrow/filesystem/api.h" namespace "arrow::fs" nogil: ctypedef enum CFileType "arrow::fs::FileType": diff --git a/python/pyarrow/src/arrow/python/filesystem_iterator.h b/python/pyarrow/src/arrow/python/filesystem_iterator.h new file mode 100644 index 000000000000..eea99aa5eb2c --- /dev/null +++ b/python/pyarrow/src/arrow/python/filesystem_iterator.h @@ -0,0 +1,56 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/filesystem/filesystem.h" +#include "arrow/util/future.h" +#include "arrow/util/iterator.h" + +namespace arrow::py::fs { + +class FileInfoVectorIterator { + public: + FileInfoVectorIterator() = default; + explicit FileInfoVectorIterator(arrow::fs::FileInfoGenerator generator) + : generator_(std::move(generator)) {} + + Result Next() { + if (!generator_) { + return IterationEnd(); + } + auto next = generator_().result(); + if (!next.ok() || IsIterationEnd(*next)) { + generator_ = nullptr; + } + return next; + } + + private: + arrow::fs::FileInfoGenerator generator_; +}; + +inline FileInfoVectorIterator MakeFileInfoVectorIterator( + const std::shared_ptr& filesystem, + const arrow::fs::FileSelector& selector) { + return FileInfoVectorIterator(filesystem->GetFileInfoGenerator(selector)); +} + +} // namespace arrow::py::fs diff --git a/python/pyarrow/tests/test_fs.py b/python/pyarrow/tests/test_fs.py index 416c75bccd2b..bd850947d746 100644 --- a/python/pyarrow/tests/test_fs.py +++ b/python/pyarrow/tests/test_fs.py @@ -34,6 +34,7 @@ running_on_musllinux) from pyarrow.fs import (FileType, FileInfo, FileSelector, FileSystem, + FileInfoIterator, LocalFileSystem, SubTreeFileSystem, _MockFileSystem, FileSystemHandler, PyFileSystem, FSSpecHandler, copy_files) @@ -835,6 +836,289 @@ def test_get_file_info_with_selector(fs, pathfn): fs.delete_dir(base_dir) +@pytest.mark.parametrize('recursive', [False, True]) +def test_get_file_info_iterator(fs, pathfn, recursive): + base_dir = pathfn('iterator-dir') + nested_dir = pathfn('iterator-dir/nested') + paths = { + pathfn('iterator-dir/a.txt'), + pathfn('iterator-dir/b.txt'), + pathfn('iterator-dir/nested/c.txt'), + } + + fs.create_dir(nested_dir) + try: + for path in paths: + with fs.open_output_stream(path): + pass + + selector = FileSelector(base_dir, recursive=recursive) + expected = { + (info.path, info.type, info.size) + for info in fs.get_file_info(selector) + } + iterator = fs.get_file_info_iterator(selector) + assert isinstance(iterator, FileInfoIterator) + assert iter(iterator) is iterator + infos = list(iterator) + assert all(isinstance(info, FileInfo) for info in infos) + assert len(infos) == len(expected) + assert {(info.path, info.type, info.size) for info in infos} == expected + file_names = {'a.txt', 'b.txt'} + if recursive: + file_names.add('c.txt') + assert {info.base_name for info in infos + if info.type == FileType.File} == file_names + assert next(iterator, None) is None + finally: + fs.delete_dir(base_dir) + + +def test_get_file_info_iterator_close(fs, pathfn): + base_dir = pathfn('iterator-close') + fs.create_dir(base_dir) + try: + with fs.open_output_stream(pathfn('iterator-close/file.txt')): + pass + iterator = fs.get_file_info_iterator(FileSelector(base_dir)) + iterator.close() + iterator.close() + assert next(iterator, None) is None + + # Closing after partially consuming the iterator also works. + iterator = fs.get_file_info_iterator(FileSelector(base_dir)) + assert isinstance(next(iterator), FileInfo) + iterator.close() + assert next(iterator, None) is None + finally: + fs.delete_dir(base_dir) + + +def test_get_file_info_iterator_is_lazy(): + # Discovery must not start until the first next() call. + listed = [] + + class LazyHandler(DummyHandler): + def get_file_info_selector(self, selector): + listed.append(selector.base_dir) + return super().get_file_info_selector(selector) + + fs = PyFileSystem(LazyHandler()) + iterator = fs.get_file_info_iterator(FileSelector('somedir')) + assert listed == [] + assert isinstance(next(iterator), FileInfo) + assert listed == ['somedir'] + iterator.close() + + +def test_get_file_info_iterator_errors(localfs): + fs = localfs['fs'] + with pytest.raises(TypeError): + FileInfoIterator() + with pytest.raises(TypeError): + fs.get_file_info_iterator(None) + with pytest.raises(TypeError): + fs.get_file_info_iterator('not-a-selector') + + missing = localfs['pathfn']('missing-iterator-dir') + iterator = fs.get_file_info_iterator(FileSelector(missing)) + with pytest.raises(FileNotFoundError): + next(iterator) + assert next(iterator, None) is None + iterator.close() + + iterator = fs.get_file_info_iterator( + FileSelector(missing, allow_not_found=True)) + assert list(iterator) == [] + + +def test_get_file_info_iterator_spans_batches(tmp_path): + # More entries than the local filesystem's batch size, so the iterator + # has to pull several batches while yielding entries one by one. + paths = {str(tmp_path / f'{i}.txt') for i in range(2500)} + for path in paths: + pathlib.Path(path).touch() + + fs = LocalFileSystem() + infos = list(fs.get_file_info_iterator(FileSelector(str(tmp_path)))) + assert {info.path for info in infos} == paths + assert len(infos) == len(paths) + + # Stopping early must not require consuming every entry. + iterator = fs.get_file_info_iterator(FileSelector(str(tmp_path))) + first = [next(iterator) for _ in range(5)] + assert len(first) == 5 + iterator.close() + assert next(iterator, None) is None + + +@pytest.mark.parametrize('finish', ['close', 'exhaust']) +def test_get_file_info_iterator_concurrent(monkeypatch, finish): + from concurrent.futures import ThreadPoolExecutor + from threading import Event, Lock + + from pyarrow import _fs + + entered = Event() + resume = Event() + + class PausingLock: + def __init__(self): + self.lock = Lock() + + def acquire(self, blocking=True): + acquired = self.lock.acquire(blocking=blocking) + if acquired and not entered.is_set(): + # Keep next() inside its critical section until both + # competing operations have been checked. + entered.set() + if not resume.wait(timeout=10): + self.lock.release() + raise AssertionError('Timed out waiting to resume iteration') + return acquired + + def release(self): + self.lock.release() + + monkeypatch.setattr(_fs, 'Lock', PausingLock) + iterator = PyFileSystem(DummyHandler()).get_file_info_iterator( + FileSelector('somedir')) + with ThreadPoolExecutor(max_workers=1) as executor: + pending = executor.submit(next, iterator) + try: + assert entered.wait(timeout=10) + with pytest.raises(ValueError, match='iterator already executing'): + next(iterator) + with pytest.raises(ValueError, match='iterator already executing'): + iterator.close() + finally: + resume.set() + info = pending.result(timeout=10) + + assert info.path == 'somedir/file1' + if finish == 'close': + iterator.close() + else: + assert [i.path for i in iterator] == ['somedir/subdir1'] + iterator.close() + assert next(iterator, None) is None + + +@pytest.mark.parametrize('finish', ['close', 'exhaust', 'error', 'delete']) +def test_get_file_info_iterator_lifetime(tmp_path, finish): + fs = LocalFileSystem() + owner = weakref.ref(fs) + path = tmp_path / 'missing' if finish == 'error' else tmp_path + iterator = fs.get_file_info_iterator(FileSelector(str(path))) + del fs + assert owner() is not None + + if finish == 'close': + iterator.close() + elif finish == 'exhaust': + assert list(iterator) == [] + elif finish == 'error': + with pytest.raises(FileNotFoundError): + next(iterator) + else: + del iterator + assert owner() is None + + +def test_get_file_info_iterator_pyfilesystem_fallback(): + fs = PyFileSystem(DummyHandler()) + iterator = fs.get_file_info_iterator( + FileSelector('somedir', recursive=True)) + assert [info.path for info in iterator] == [ + 'somedir/file1', + 'somedir/subdir1', + 'somedir/subdir1/file2', + ] + + +def test_get_file_info_iterator_pyfilesystem_errors(): + fs = PyFileSystem(DummyHandler()) + iterator = fs.get_file_info_iterator(FileSelector('otherdir')) + with pytest.raises(FileNotFoundError, match='otherdir'): + next(iterator) + assert next(iterator, None) is None + iterator.close() + + iterator = fs.get_file_info_iterator( + FileSelector('otherdir', allow_not_found=True)) + assert list(iterator) == [] + + +@pytest.mark.parametrize('error', [FileNotFoundError, RuntimeError, StopIteration]) +def test_get_file_info_iterator_handler_error_releases_owner(error): + class FailingHandler(DummyHandler): + def get_file_info_selector(self, selector): + raise error('handler failure') + + fs = PyFileSystem(FailingHandler()) + owner = weakref.ref(fs) + iterator = fs.get_file_info_iterator(FileSelector('somedir')) + del fs + with pytest.raises(error, match='handler failure'): + next(iterator) + assert owner() is None + assert next(iterator, None) is None + iterator.close() + + +@pytest.mark.parametrize('finish', ['close', 'delete']) +def test_get_file_info_iterator_unused_is_lazy(finish): + class UnusedHandler(DummyHandler): + def get_file_info_selector(self, selector): + pytest.fail('Closing or deleting an unused iterator must not list') + + iterator = PyFileSystem(UnusedHandler()).get_file_info_iterator( + FileSelector('somedir')) + if finish == 'close': + iterator.close() + assert next(iterator, None) is None + else: + del iterator + + +def test_get_file_info_iterator_failing_generator(localfs): + # SubTreeFileSystem rejects URIs before it can build a generator, which + # exercises the failing-generator code path. + subtree = SubTreeFileSystem(localfs['pathfn']('.'), localfs['fs']) + iterator = subtree.get_file_info_iterator(FileSelector('s3://bucket/key')) + with pytest.raises(pa.ArrowInvalid, match='got a URI'): + next(iterator) + assert next(iterator, None) is None + iterator.close() + + +def test_get_file_info_iterator_delete_while_iterating(tmp_path): + for i in range(2500): + (tmp_path / f'{i}.txt').touch() + + fs = LocalFileSystem() + iterator = fs.get_file_info_iterator(FileSelector(str(tmp_path))) + assert isinstance(next(iterator), FileInfo) + # Drop the iterator mid-stream so the C++ generator is released while + # background discovery may still be in flight. + del iterator + + +def test_get_file_info_iterator_subtree(localfs): + fs = localfs['fs'] + base_dir = localfs['pathfn']('iterator-subtree') + fs.create_dir(base_dir) + try: + with fs.open_output_stream( + localfs['pathfn']('iterator-subtree/file.txt')): + pass + subtree = SubTreeFileSystem(base_dir, fs) + infos = list(subtree.get_file_info_iterator(FileSelector(''))) + assert [info.path for info in infos] == ['file.txt'] + finally: + fs.delete_dir(base_dir) + + def test_create_dir(fs, pathfn): # s3fs fails deleting dir fails if it is empty # (https://github.com/dask/s3fs/issues/317)