From b06ca434c19276a48d81642aa312ce69a7c5e188 Mon Sep 17 00:00:00 2001 From: Sam Gamble Date: Wed, 21 Oct 2026 16:02:36 +0100 Subject: [PATCH 1/3] Faster directory archives: gzip level 1 default and optional zstd Directory archives written by `put()` used tarfile's default gzip level 9 on a single core. On a 12.4 GB Oasis inputs directory that took 369 s locally (~23 min on Fargate) for a 7.9x ratio; level 1 takes 32 s for 7.1x. - Default gzip compresslevel is now 1 (configurable via `archive_compresslevel`) - New `archive_compression` option ('gz' or 'zst') and per call `put(..., compression=...)` override; zstd is multi-threaded (`archive_threads`, -1 for every core) via the stdlib `compression.zstd` on Python 3.14+ or the `zstandard` package (new `[zstd]` extra) - `extract()` detects zstd archives by magic bytes - Archive options are kept by `to_config()` - New `archive_suffix()` returns the extension for the configured format Co-Authored-By: Claude Opus 5.5 --- oasis_data_manager/filestore/archive.py | 117 +++++++++++++++++ oasis_data_manager/filestore/backends/aws.py | 4 +- oasis_data_manager/filestore/backends/base.py | 60 +++++++-- optional-package.in | 1 + pyproject.toml | 4 + tests/filestorage/test_archive.py | 118 ++++++++++++++++++ 6 files changed, 289 insertions(+), 15 deletions(-) create mode 100644 oasis_data_manager/filestore/archive.py create mode 100644 tests/filestorage/test_archive.py diff --git a/oasis_data_manager/filestore/archive.py b/oasis_data_manager/filestore/archive.py new file mode 100644 index 0000000..bd6c9c4 --- /dev/null +++ b/oasis_data_manager/filestore/archive.py @@ -0,0 +1,117 @@ +"""Tar archive helpers used by the storage backends to `put` and `extract` directories + +Archives are written as gzip (``tar.gz``, the default) or zstandard (``tar.zst``). +zstd uses the standard library ``compression.zstd`` module on Python 3.14+, or the +``zstandard`` package (``pip install oasis-data-manager[zstd]``) on older versions. +""" +import contextlib +import os +import tarfile + +from oasis_data_manager.errors import OasisDataManagerException + +GZIP = "gz" +ZSTD = "zst" +ARCHIVE_SUFFIXES = {GZIP: "tar.gz", ZSTD: "tar.zst"} + +# Speed over size: on Oasis inputs gzip level 1 is ~11x faster than level 9 for a ~10% larger archive +DEFAULT_COMPRESSLEVEL = {GZIP: 1, ZSTD: 3} + +ZSTD_MAGIC = b"\x28\xb5\x2f\xfd" + + +def validate_compression(compression): + if compression not in ARCHIVE_SUFFIXES: + raise OasisDataManagerException( + f"Unsupported archive compression '{compression}', expected one of {list(ARCHIVE_SUFFIXES)}" + ) + return compression + + +def _zstd_threads(threads): + """-1 uses every available core, 0 compresses in the calling thread""" + if threads is None or threads < 0: + return os.cpu_count() or 1 + return threads + + +def _stdlib_zstd(): + try: + from compression import zstd + except ImportError: + return None + return zstd + + +def _zstandard(): + try: + import zstandard + except ImportError: + raise OasisDataManagerException( + "zstd archives need Python 3.14+ or the 'zstandard' package, install with 'pip install oasis-data-manager[zstd]'" + ) + return zstandard + + +def is_zstd(archive_fp): + with open(archive_fp, "rb") as f: + return f.read(4) == ZSTD_MAGIC + + +def compress_dir(archive_fp, directory, arcname="/", compression=GZIP, compresslevel=None, threads=-1): + """Write `directory` to a tar archive at `archive_fp` + + :param compression: `gz` or `zst` + :param compresslevel: compression level, defaults to `DEFAULT_COMPRESSLEVEL` for the format + :param threads: zstd worker threads, -1 for every core (ignored for gzip) + """ + validate_compression(compression) + level = DEFAULT_COMPRESSLEVEL[compression] if compresslevel is None else int(compresslevel) + + if compression == GZIP: + with tarfile.open(archive_fp, "w:gz", compresslevel=level) as tar: + tar.add(directory, arcname=arcname) + return + + threads = _zstd_threads(threads) + zstd = _stdlib_zstd() + if zstd: + options = {zstd.CompressionParameter.compression_level: level} + if threads and zstd.CompressionParameter.nb_workers.bounds()[1] > 0: + options[zstd.CompressionParameter.nb_workers] = threads + with zstd.ZstdFile(archive_fp, "w", options=options) as zf, tarfile.open(fileobj=zf, mode="w|") as tar: + tar.add(directory, arcname=arcname) + return + + cctx = _zstandard().ZstdCompressor(level=level, threads=threads) + with open(archive_fp, "wb") as fh, cctx.stream_writer(fh, closefd=False) as writer, \ + tarfile.open(fileobj=writer, mode="w|") as tar: + tar.add(directory, arcname=arcname) + + +@contextlib.contextmanager +def open_archive(archive_fp): + """Open a gzip, zstd or uncompressed tar archive for reading + + zstd archives are opened as a stream: iterate or `extractall`, don't seek back to earlier members. + """ + if not is_zstd(archive_fp): + with tarfile.open(archive_fp) as tar: + yield tar + return + + zstd = _stdlib_zstd() + if zstd: + with zstd.ZstdFile(archive_fp, "r") as zf, tarfile.open(fileobj=zf, mode="r|") as tar: + yield tar + return + + dctx = _zstandard().ZstdDecompressor() + with open(archive_fp, "rb") as fh, dctx.stream_reader(fh) as reader, tarfile.open(fileobj=reader, mode="r|") as tar: + yield tar + + +def extract_archive(archive_fp, directory): + with open_archive(archive_fp) as tar: + os.makedirs(directory, exist_ok=True) + tar.extractall(directory) diff --git a/oasis_data_manager/filestore/backends/aws.py b/oasis_data_manager/filestore/backends/aws.py index 5c7f791..bbe0419 100755 --- a/oasis_data_manager/filestore/backends/aws.py +++ b/oasis_data_manager/filestore/backends/aws.py @@ -261,12 +261,12 @@ def url(self, object_name, parameters=None, expire=None): else: return self._strip_signing_parameters(url) - def put(self, reference, filename=None, subdir="", suffix=None, arcname=None): + def put(self, reference, filename=None, subdir="", suffix=None, arcname=None, compression=None): # Prepend location so the returned key is bucket-relative (location/subdir/file). # The server's CopyObject and is_in_bucket() both use the raw bucket key, so the # returned value must include the location prefix, not be relative to it. effective_subdir = os.path.join(self.location, subdir) if self.location else subdir - return super().put(reference, filename=filename, subdir=effective_subdir, suffix=suffix, arcname=arcname) + return super().put(reference, filename=filename, subdir=effective_subdir, suffix=suffix, arcname=arcname, compression=compression) def get_storage_url(self, filename=None, suffix="tar.gz", encode_params=True): filename = ( diff --git a/oasis_data_manager/filestore/backends/base.py b/oasis_data_manager/filestore/backends/base.py index 943a6a8..42a5af8 100755 --- a/oasis_data_manager/filestore/backends/base.py +++ b/oasis_data_manager/filestore/backends/base.py @@ -2,7 +2,7 @@ import logging import os import shutil -import tarfile +# import tarfile # archive handling moved to oasis_data_manager.filestore.archive import tempfile import uuid from pathlib import Path @@ -14,6 +14,7 @@ from fsspec.implementations.dirfs import DirFileSystem from oasis_data_manager.errors import OasisDataManagerException +from oasis_data_manager.filestore.archive import ARCHIVE_SUFFIXES, GZIP, compress_dir, extract_archive, validate_compression import xxhash LOG_FILE_SUFFIX = "txt" @@ -69,12 +70,25 @@ class BaseStorage(object): fsspec_filesystem_class: Optional[Type[fsspec.AbstractFileSystem]] def __init__( - self, root_dir="", cache_dir: Union[str, None] = "/tmp/data-cache", logger=None, **kwargs + self, + root_dir="", + cache_dir: Union[str, None] = "/tmp/data-cache", + logger=None, + archive_compression: str = GZIP, + archive_compresslevel: Optional[int] = None, + archive_threads: int = -1, + **kwargs ): # Use for caching files across multiple runs, set value 'None' or 'False' to disable self.cache_root = cache_dir self.root_dir = root_dir + # How directories are archived by `put`: 'gz' or 'zst', level (None for the format default) + # and zstd worker threads (-1 for every core) + self.archive_compression = validate_compression(archive_compression) + self.archive_compresslevel = archive_compresslevel + self.archive_threads = archive_threads + self.logger = logger or logging.getLogger() self._fs: Optional[StrictRootDirFs] = None @@ -86,9 +100,18 @@ def _normalize_root_dir(container, root_dir): def to_config(self) -> dict: return { "storage_class": f"{self.__module__}.{type(self).__name__}", - "options": self.config_options, + "options": { + **self.config_options, + "archive_compression": self.archive_compression, + "archive_compresslevel": self.archive_compresslevel, + "archive_threads": self.archive_threads, + }, } + def archive_suffix(self, compression=None): + """Filename extension of directory archives written by `put`, e.g. `tar.gz`""" + return ARCHIVE_SUFFIXES[validate_compression(compression or self.archive_compression)] + @property def config_options(self): raise NotImplementedError() @@ -148,11 +171,9 @@ def extract(self, archive_fp, directory, storage_subdir=""): os.path.join(temp_dir_path, os.path.basename(archive_fp)), subdir=storage_subdir, ) - with tarfile.open(local_archive_path) as f: - os.makedirs(directory, exist_ok=True) - f.extractall(directory) + extract_archive(local_archive_path, directory) - def compress(self, archive_fp, directory, arcname=None): + def compress(self, archive_fp, directory, arcname=None, compression=None): """Compress a directory Parameters @@ -166,10 +187,19 @@ def compress(self, archive_fp, directory, arcname=None): :param arcname: If given, `arcname' set an alternative name for the file in the archive. :type arcname: str + + :param compression: `gz` or `zst`, defaults to `self.archive_compression` + :type compression: str """ arcname = arcname if arcname else "/" - with tarfile.open(archive_fp, "w:gz") as tar: - tar.add(directory, arcname=arcname) + compress_dir( + archive_fp, + directory, + arcname=arcname, + compression=compression or self.archive_compression, + compresslevel=self.archive_compresslevel, + threads=self.archive_threads, + ) def get_from_cache(self, reference, required=False, no_cache_target=None): """ @@ -326,7 +356,7 @@ def get(self, reference, output_path="", subdir="", required=False): return None - def put(self, reference, filename=None, subdir="", suffix=None, arcname=None): + def put(self, reference, filename=None, subdir="", suffix=None, arcname=None, compression=None): """Place object in storage Top level send to storage function, @@ -348,9 +378,13 @@ def put(self, reference, filename=None, subdir="", suffix=None, arcname=None): name for the file in the archive. :type arcname: str - :param suffix: Set the filename extension defaults to `tar.gz` + :param suffix: Set the filename extension defaults to the archive suffix, e.g. `tar.gz` :type suffix: str + :param compression: Archive compression for a directory, `gz` or `zst`, + defaults to `self.archive_compression` + :type compression: str + :return: access storage reference returned from self._store_file, self._store_dir This will either be a pre-signed URL or absolute filepath :rtype str @@ -370,14 +404,14 @@ def put(self, reference, filename=None, subdir="", suffix=None, arcname=None): return storage_location elif os.path.isdir(reference): - ext = "tar.gz" if not suffix else suffix + ext = self.archive_suffix(compression) if not suffix else suffix filename = filename if filename else self._get_unique_filename(ext) storage_path = os.path.join(subdir, filename) if subdir else filename self.fs.mkdirs(os.path.dirname(storage_path), exist_ok=True) self.logger.info("Store dir: {} -> {}".format(reference, storage_path)) with tempfile.NamedTemporaryFile() as f: - self.compress(f.name, reference, arcname) + self.compress(f.name, reference, arcname, compression=compression) self.fs.put(f.name, storage_path) return storage_path else: diff --git a/optional-package.in b/optional-package.in index ac2b166..0aa6201 100644 --- a/optional-package.in +++ b/optional-package.in @@ -7,3 +7,4 @@ distributed geopandas==0.14.4 pyogrio s3fs>=2023.12.2 +zstandard; python_version < '3.14' diff --git a/pyproject.toml b/pyproject.toml index 3f7f45f..84f8e2f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,11 +36,15 @@ s3 = [ azure = [ "adlfs", ] +zstd = [ + "zstandard; python_version < '3.14'", +] extra = [ "oasis-data-manager[geo]", "oasis-data-manager[dask]", "oasis-data-manager[s3]", "oasis-data-manager[azure]", + "oasis-data-manager[zstd]", ] [project.urls] diff --git a/tests/filestorage/test_archive.py b/tests/filestorage/test_archive.py new file mode 100644 index 0000000..9e297c7 --- /dev/null +++ b/tests/filestorage/test_archive.py @@ -0,0 +1,118 @@ +import os +import tarfile +from pathlib import Path +from tempfile import TemporaryDirectory + +import pytest + +from oasis_data_manager.errors import OasisDataManagerException +from oasis_data_manager.filestore import archive +from oasis_data_manager.filestore.archive import compress_dir, extract_archive, is_zstd +from oasis_data_manager.filestore.backends.local import LocalStorage +from oasis_data_manager.filestore.config import get_storage_from_config + +try: + import zstandard # noqa: F401 + HAS_ZSTANDARD = True +except ImportError: + HAS_ZSTANDARD = False + +HAS_STDLIB_ZSTD = archive._stdlib_zstd() is not None +needs_zstd = pytest.mark.skipif(not (HAS_STDLIB_ZSTD or HAS_ZSTANDARD), reason="zstd needs Python 3.14+ or zstandard") + + +def make_tree(root): + Path(root, "sub").mkdir(parents=True) + Path(root, "a.csv").write_text("loc_id,tiv\n" + "1,100.0\n" * 1000) + Path(root, "sub", "b.bin").write_bytes(bytes(range(256)) * 64) + return {"a.csv": Path(root, "a.csv").read_bytes(), "sub/b.bin": Path(root, "sub", "b.bin").read_bytes()} + + +def assert_tree(root, expected): + for rel, content in expected.items(): + assert Path(root, rel).read_bytes() == content + + +@pytest.mark.parametrize("compression", ["gz", pytest.param("zst", marks=needs_zstd)]) +def test_compress_then_extract___contents_round_trip(compression): + with TemporaryDirectory() as src, TemporaryDirectory() as work, TemporaryDirectory() as dst: + expected = make_tree(src) + archive_fp = os.path.join(work, "archive") + + compress_dir(archive_fp, src, compression=compression) + extract_archive(archive_fp, dst) + + assert is_zstd(archive_fp) == (compression == "zst") + assert_tree(dst, expected) + + +@pytest.mark.skipif(not HAS_ZSTANDARD, reason="zstandard not installed") +def test_zstd_without_stdlib_module___zstandard_package_is_used(monkeypatch): + monkeypatch.setattr(archive, "_stdlib_zstd", lambda: None) + with TemporaryDirectory() as src, TemporaryDirectory() as work, TemporaryDirectory() as dst: + expected = make_tree(src) + archive_fp = os.path.join(work, "archive.tar.zst") + + compress_dir(archive_fp, src, compression="zst", threads=2) + extract_archive(archive_fp, dst) + + assert_tree(dst, expected) + + +def test_gzip_default_level___fast_level_is_used(monkeypatch): + levels = [] + real_open = tarfile.open + + def spy_open(*args, **kwargs): + levels.append(kwargs.get("compresslevel")) + return real_open(*args, **kwargs) + + monkeypatch.setattr(archive.tarfile, "open", spy_open) + with TemporaryDirectory() as src, TemporaryDirectory() as work: + make_tree(src) + compress_dir(os.path.join(work, "a.tar.gz"), src) + compress_dir(os.path.join(work, "b.tar.gz"), src, compresslevel=9) + + assert levels == [1, 9] + + +def test_unknown_compression___raises(): + with pytest.raises(OasisDataManagerException): + LocalStorage(archive_compression="bz2") + + +@pytest.mark.parametrize("compression, suffix", [("gz", ".tar.gz"), pytest.param("zst", ".tar.zst", marks=needs_zstd)]) +def test_put_directory___archive_uses_storage_compression(compression, suffix): + with TemporaryDirectory() as root, TemporaryDirectory() as src, TemporaryDirectory() as dst: + expected = make_tree(src) + storage = LocalStorage(root_dir=root, cache_dir=None, archive_compression=compression) + + ref = storage.put(src) + storage.extract(ref, dst) + + assert ref.endswith(suffix) + assert_tree(dst, expected) + + +@needs_zstd +def test_put_directory_with_compression_override___override_is_used(): + with TemporaryDirectory() as root, TemporaryDirectory() as src, TemporaryDirectory() as dst: + expected = make_tree(src) + storage = LocalStorage(root_dir=root, cache_dir=None) + + ref = storage.put(src, compression="zst") + storage.extract(ref, dst) + + assert ref.endswith(".tar.zst") + assert is_zstd(os.path.join(root, ref)) + assert_tree(dst, expected) + + +def test_storage_from_config___archive_options_are_kept(): + with TemporaryDirectory() as root: + storage = LocalStorage(root_dir=root, archive_compression="zst", archive_compresslevel=5, archive_threads=4) + + result = get_storage_from_config(storage.to_config()) + + assert (result.archive_compression, result.archive_compresslevel, result.archive_threads) == ("zst", 5, 4) + assert result.archive_suffix() == "tar.zst" From 4dc53a07a4084a95b81d066b9e5ce121031a0247 Mon Sep 17 00:00:00 2001 From: Sam Gamble Date: Fri, 23 Oct 2026 11:22:48 +0100 Subject: [PATCH 2/3] Remove unused ARCHIVE_FILE_SUFFIX constant ARCHIVE_SUFFIXES in filestore/archive.py now determines archive suffixes. Co-Authored-By: Claude Opus 5.5 --- oasis_data_manager/filestore/backends/base.py | 1 - 1 file changed, 1 deletion(-) diff --git a/oasis_data_manager/filestore/backends/base.py b/oasis_data_manager/filestore/backends/base.py index 42a5af8..658667c 100755 --- a/oasis_data_manager/filestore/backends/base.py +++ b/oasis_data_manager/filestore/backends/base.py @@ -18,7 +18,6 @@ import xxhash LOG_FILE_SUFFIX = "txt" -ARCHIVE_FILE_SUFFIX = "tar.gz" class MissingInputsException(OasisDataManagerException): From 958b31cb61a1aca2bd63d9b17f4209126f6544ce Mon Sep 17 00:00:00 2001 From: Sam Gamble Date: Fri, 23 Oct 2026 11:23:39 +0100 Subject: [PATCH 3/3] Use tarfile's native zstd support on Python 3.14+ Write with tarfile.open(..., "w:zst", options=...) and let tarfile auto-detect zstd on read, instead of wrapping a ZstdFile in a streamed tar. Reads on 3.14+ are now seekable; the zstandard fallback is unchanged. Co-Authored-By: Claude Opus 5.5 --- oasis_data_manager/filestore/archive.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/oasis_data_manager/filestore/archive.py b/oasis_data_manager/filestore/archive.py index bd6c9c4..b3b641c 100644 --- a/oasis_data_manager/filestore/archive.py +++ b/oasis_data_manager/filestore/archive.py @@ -79,7 +79,7 @@ def compress_dir(archive_fp, directory, arcname="/", compression=GZIP, compressl options = {zstd.CompressionParameter.compression_level: level} if threads and zstd.CompressionParameter.nb_workers.bounds()[1] > 0: options[zstd.CompressionParameter.nb_workers] = threads - with zstd.ZstdFile(archive_fp, "w", options=options) as zf, tarfile.open(fileobj=zf, mode="w|") as tar: + with tarfile.open(archive_fp, "w:zst", options=options) as tar: tar.add(directory, arcname=arcname) return @@ -93,19 +93,15 @@ def compress_dir(archive_fp, directory, arcname="/", compression=GZIP, compressl def open_archive(archive_fp): """Open a gzip, zstd or uncompressed tar archive for reading - zstd archives are opened as a stream: iterate or `extractall`, don't seek back to earlier members. + zstd archives read with the `zstandard` package are opened as a stream: iterate or `extractall`, + don't seek back to earlier members. """ - if not is_zstd(archive_fp): + # tarfile detects zstd itself when compression.zstd is available + if _stdlib_zstd() or not is_zstd(archive_fp): with tarfile.open(archive_fp) as tar: yield tar return - zstd = _stdlib_zstd() - if zstd: - with zstd.ZstdFile(archive_fp, "r") as zf, tarfile.open(fileobj=zf, mode="r|") as tar: - yield tar - return - dctx = _zstandard().ZstdDecompressor() with open(archive_fp, "rb") as fh, dctx.stream_reader(fh) as reader, tarfile.open(fileobj=reader, mode="r|") as tar: yield tar