diff --git a/benchmarks/README.md b/benchmarks/README.md index 8137046cd..ed5c1767b 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -228,13 +228,29 @@ The filesystem suite transfers one S3 object through PyAthena's `S3FileSystem` ( Its operations, selected with `--transport`, are: - `read`: one `read()` of the whole object from a file opened with `block_size`; PyAthena's files read it as parallel range requests of that size and hold the parts and the joined object, about twice the object's size, in memory, while s3fs's file reads it as one stream through fsspec's read-ahead cache; -- `get`: `get_file()` to a local file in the trial's temporary directory; PyAthena's reads one block at a time through a file opened with `block_size`, whose `bytes` cache requests the next block with the first read and one block at a time afterwards, and s3fs's reads parallel ranges of `chunksize` with `max_concurrency` requests at a time; +- `get`: `get_file()` to a local file in the trial's temporary directory; PyAthena's reads waves of up to `max_workers` parallel ranges of `block_size`, at most as many as the request pool runs, and writes each wave before it reads the next (#1323), and s3fs's reads parallel ranges of `chunksize` with `max_concurrency` requests at a time; - `write`: writes through a file opened with `block_size`, which uploads the object as a multipart upload with parts of that size; PyAthena's files upload up to `max_workers` parts at a time, and s3fs's file one part at a time; - `put`: `put_file()` from a sparse local file of the object's size, so that no disk read bounds the upload; PyAthena's uploads up to `max_workers` parts of `block_size` at a time, and s3fs's `max_concurrency` parts of `chunksize`, or one PutObject for an object below both twice `chunksize` and 5 GiB; - `copy`: `cp_file()`, or `_cp_file()` of `AioS3FileSystem`, with parts of `block_size`; PyAthena copies an object over 5 GiB as a multipart copy with up to `max_workers` part copies at a time, and s3fs copies one over 150 MiB (`s3fs.core.MANAGED_COPY_THRESHOLD`) as a multipart copy of one part at a time; the copies of smaller objects, single CopyObject requests, are recorded as unsupported; PyAthena's copies exclude tags and annotations, which the generated objects do not have. Each case sets the filesystem's `max_workers` and the S3 client's `max_pool_connections`, through the connection's `s3_config` for PyAthena, and as `max_concurrency` and `config_kwargs` for s3fs, which creates its own client from the session's credentials. The `[filesystem]` section of `config.toml` sets the swept values, 8 and 40 workers and pools of 10 and 40 by default, and a `block_size` of 8 MiB. +Its `clients` tables name sets of other botocore `Config` options of the S3 clients, passed the same way with every API; each is a case, and a name other than `default`, the only one by default, ends the case IDs, such as `filesystem-s3-sync-put-w8-p10-required`. +The clients may not set `max_pool_connections`, which `pool_connections` sweeps. +A run takes them from its `--config`, and a fleet worker from the queue's `config.toml`, so give `jobs` and `queue` the same configuration. +For example, the upload checksum settings of #1325: + +```toml +[filesystem.clients.default] + +[filesystem.clients.required] +request_checksum_calculation = "when_required" + +[filesystem.clients.unsigned] +request_checksum_calculation = "when_required" +s3 = { payload_signing_enabled = false } +``` + The suite's scales are the object sizes in bytes in `[filesystem] sizes`, not the row counts in `[scales]`: 64 MiB (small), 256 MiB (medium), 1 GiB (large), and 6 GiB (xlarge) by default. A `get` also writes the object to the trial's temporary directory, which the parent process measures as the peak temp dir and removes; on the Amazon Linux 2023 hosts, that directory is on the tmpfs `/tmp`, so the object stays in memory outside the process's RSS. A `put` reads a sparse file, which no disk bounds. @@ -295,11 +311,12 @@ Its operations, selected with `--transport`, and the result each trial checks ar - `find`: `find(prefix)` of the set's listing; the keys returned; - `info`: `info(path)` of each file, through a thread pool of the case's concurrency for the synchronous filesystem and through batches of `fsspec.asyn._run_coros_in_chunks` for the other two; the entries returned. -Each case sets one concurrency from `[objects] concurrency`, 8 and 40 by default: the filesystem's `max_workers` and connection pool, as in the filesystem suite, and the `batch_size` of the `aio` and s3fs operations, which is the number of files they transfer at the same time. -The synchronous `S3FileSystem` inherits fsspec's sequential loops for `cat`, `get`, `put`, `pipe`, and `copy`, so its concurrency only sizes its executor and pool; its `rm` and the other two APIs' delete in DeleteObjects requests of 1,000 keys, which no batch size affects; and `find` pages through ListObjectsV2 with every API. +Each case sets one concurrency from `[objects] concurrency`, 8 and 40 by default: the filesystem's `max_workers` and connection pool, as in the filesystem suite, and the `batch_size` of the `cat`, `get`, `put`, `pipe`, and `copy` operations of every API, which is the number of files they transfer at the same time; the synchronous `S3FileSystem` runs them concurrently since #1322. +With a concurrency of 1, `cat`, `get`, `put`, `pipe`, and `copy` transfer one object at a time, so their time per object is the latency of one call. +`rm` deletes in DeleteObjects requests of up to 1,000 keys with every API, PyAthena's up to `max_workers` of them at once, so a set of up to 1,000 objects takes one request at any concurrency; `find` pages through ListObjectsV2 with every API. The `aio` API awaits each operation's coroutine on the trial's event loop, whose lag is sampled; the `sync` and `s3fs` APIs call the operation on the trial's thread. Besides the metrics of the filesystem suite, each trial records the objects per second and the process CPU time of the operation, user and system, as `cpu_seconds`. -The objects that `put`, `pipe`, and `copy` create, the copies that an `rm` trial prepares, and the local files of `get` and `put`, are removed after the check, also when the preparation or the operation failed, and a removal that fails makes the trial an error; a write of the `aio` API that a failed batch leaves running in a thread may create an object after the removal. +The objects that `put`, `pipe`, and `copy` create, the copies that an `rm` trial prepares, and the local files of `get` and `put`, are removed after the check, also when the preparation or the operation failed, and a removal that fails makes the trial an error. `cleanup` removes the sets and any remaining trial objects. ```bash diff --git a/benchmarks/pyathena_bench/cases.py b/benchmarks/pyathena_bench/cases.py index 21192df66..62de94b00 100644 --- a/benchmarks/pyathena_bench/cases.py +++ b/benchmarks/pyathena_bench/cases.py @@ -67,13 +67,16 @@ class Case: # filesystem suite. max_workers: int | None = None pool_connections: int | None = None + # The named botocore Config options of the filesystem suite's S3 clients. + client: str = "default" @property def id(self) -> str: if self.suite == "filesystem": + client = "" if self.client == "default" else f"-{self.client}" return ( f"{self.suite}-{self.family}-{self.api}-{self.transport}-" - f"w{self.max_workers}-p{self.pool_connections}" + f"w{self.max_workers}-p{self.pool_connections}{client}" ) if self.suite == "objects": return f"{self.suite}-{self.family}-{self.api}-{self.transport}-n{self.max_workers}" @@ -123,7 +126,9 @@ def matrix(settings: Settings, suite: str, shape: str) -> list[Case]: suites. The ``filesystem`` and ``objects`` suites do not query Athena and have no - shape; their cases belong to the ``flat`` shape. A case of the ``objects`` + shape; their cases belong to the ``flat`` shape. The ``filesystem`` suite + has a case for each named set of S3 client options in its ``clients`` + setting. A case of the ``objects`` suite sets its concurrency as the filesystem's ``max_workers`` and connection pool, and as the batch size of its operation. @@ -154,11 +159,13 @@ def matrix(settings: Settings, suite: str, shape: str) -> list[Case]: suite=suite, max_workers=workers, pool_connections=pool, + client=client, ) for operation in FILESYSTEM_OPERATIONS for api in FILESYSTEM_APIS for workers in settings.filesystem_max_workers for pool in settings.filesystem_pool_connections + for client in settings.filesystem_clients ] if suite == "objects": if shape != "flat": diff --git a/benchmarks/pyathena_bench/config.py b/benchmarks/pyathena_bench/config.py index 4c0fbb233..acfa55690 100644 --- a/benchmarks/pyathena_bench/config.py +++ b/benchmarks/pyathena_bench/config.py @@ -18,6 +18,9 @@ from pathlib import Path from typing import Any +from botocore.config import Config +from botocore.exceptions import BotoCoreError + FLAT_COLUMNS = ( '"timestamp", country_code, url, project, file.filename AS filename, ' "file.version AS version, file.type AS file_type, details.python AS python, " @@ -56,6 +59,11 @@ def identifier(value: str) -> str: return value +# The botocore checksum settings of an S3 client and their values. +CHECKSUM_SETTINGS = ("request_checksum_calculation", "response_checksum_validation") +CHECKSUM_VALUES = ("when_supported", "when_required") + + @dataclass(frozen=True) class Settings: region: str = "us-west-2" @@ -82,6 +90,10 @@ class Settings: filesystem_block_size: int = 8 * 2**20 filesystem_max_workers: list[int] = field(default_factory=lambda: [8, 40]) filesystem_pool_connections: list[int] = field(default_factory=lambda: [10, 40]) + # Named sets of botocore Config options of the S3 clients of the filesystem suite, + # such as its checksum settings; each is a case, and those other than "default" + # add their names to the case IDs. + filesystem_clients: dict[str, dict[str, Any]] = field(default_factory=lambda: {"default": {}}) # The objects suite: object counts by scale name, the size of each object, the # keys of the listing set per object, and the swept concurrency, which is the # filesystem's max_workers and connection pool and the batch size of its operations. @@ -139,6 +151,27 @@ def __post_init__(self) -> None: values = getattr(self, name) if not values or any(type(v) is not int or v < 1 for v in values): raise ValueError(f"Invalid {name}") + if not self.filesystem_clients: + raise ValueError("At least one filesystem client is required") + for name, options in self.filesystem_clients.items(): + identifier(name) + if not isinstance(options, dict): + raise ValueError("Filesystem clients must be tables of botocore Config options") + if "max_pool_connections" in options: + raise ValueError("pool_connections sets the connection pool of the clients") + try: + # Checks the names of the options; creating a client, which also checks + # values, would read the AWS configuration of the environment. + Config(**options) + except (TypeError, BotoCoreError) as e: + raise ValueError(f"Invalid options of the filesystem client {name}: {e}") from e + # botocore checks the values of the checksum settings only when it creates + # a client, which a trial would fail at. + for key in CHECKSUM_SETTINGS: + value = options.get(key, CHECKSUM_VALUES[0]) + # botocore lowercases the value before it checks it. + if not isinstance(value, str) or value.lower() not in CHECKSUM_VALUES: + raise ValueError(f"Invalid {key} of the filesystem client {name}") if not self.objects_counts: raise ValueError("Objects counts must name at least one scale") for name, count in self.objects_counts.items(): diff --git a/benchmarks/pyathena_bench/filesystem.py b/benchmarks/pyathena_bench/filesystem.py index 00eff7f35..368f45f35 100644 --- a/benchmarks/pyathena_bench/filesystem.py +++ b/benchmarks/pyathena_bench/filesystem.py @@ -191,12 +191,28 @@ def missing_api_reason(case: Case) -> str | None: return None +def client_options(settings: Settings, case: Case) -> dict[str, Any]: + """Return the botocore Config options of the S3 clients of a case. + + Args: + settings: Configuration with the named client options of the filesystem suite. + case: Case of the filesystem or objects suite. + + Returns: + The case's connection pool size, with the options of its client in the + filesystem suite; the objects suite's clients take no other option. + """ + options = settings.filesystem_clients[case.client] if case.suite == "filesystem" else {} + return {"max_pool_connections": case.pool_connections, **options} + + def filesystem(settings: Settings, case: Case, session_: Any, connection: Any) -> Any: """Create the filesystem of a case, with its S3 client. The PyAthena filesystems share the connection's S3 client, whose - connection pool has the case's size. s3fs creates its own client from the - session's credentials, with a connection pool of the same size, and takes + connection pool has the case's size and which takes the options of the + case's client (see :func:`client_options`). s3fs creates its own client + from the session's credentials, with the same pool size and options, and takes the case's ``max_workers`` as its ``max_concurrency``, the number of parallel range requests of ``get_file()`` and parts of ``put_file()``. Its client is connected here, as the PyAthena filesystems take the @@ -230,7 +246,7 @@ def filesystem(settings: Settings, case: Case, session_: Any, connection: Any) - config_kwargs={ "connect_timeout": 10, "read_timeout": 60, - "max_pool_connections": case.pool_connections, + **client_options(settings, case), }, max_concurrency=case.max_workers, skip_instance_cache=True, @@ -287,7 +303,7 @@ async def run_filesystem( region_name=settings.region, work_group=settings.workgroup, config=Config(connect_timeout=10, read_timeout=60), - s3_config=Config(max_pool_connections=case.pool_connections), + s3_config=Config(**client_options(settings, case)), ) fs = filesystem(settings, case, session_, connection) local = temp_dir / "object" diff --git a/benchmarks/pyathena_bench/objects.py b/benchmarks/pyathena_bench/objects.py index 511fc62b9..4d9753684 100644 --- a/benchmarks/pyathena_bench/objects.py +++ b/benchmarks/pyathena_bench/objects.py @@ -70,7 +70,8 @@ def batch(fs: Any, case: Case, paths: list[str], targets: list[str], local: Path asyncio filesystem's coroutines are awaited on the running event loop. The ``info`` fan-out, which fsspec has no batch for, runs the synchronous filesystem's ``info()`` in a thread pool of the case's concurrency, and - the coroutines of the other two in batches of it. + the coroutines of the other two in batches of it. The batch operations of + every API get the case's concurrency as their ``batch_size``. Args: fs: The filesystem of the case's API. @@ -100,7 +101,9 @@ def batch(fs: Any, case: Case, paths: list[str], targets: list[str], local: Path # The batch size is not an option of the deletes: PyAthena's and # s3fs's send DeleteObjects requests of 1,000 keys. return fs._rm(paths) if case.api == "aio" else fs.rm(paths) - options: dict[str, Any] = {} if case.api == "sync" else {"batch_size": n} + # Every API transfers this many objects at once; the synchronous filesystem's + # default batch size, its max_workers, is the same, but is not relied on. + options: dict[str, Any] = {"batch_size": n} if operation == "cat": return fs._cat(paths, **options) if case.api == "aio" else fs.cat(paths, **options) if operation == "get": diff --git a/benchmarks/tests/test_config.py b/benchmarks/tests/test_config.py index 949be0d7f..04ff7993c 100644 --- a/benchmarks/tests/test_config.py +++ b/benchmarks/tests/test_config.py @@ -42,10 +42,18 @@ def test_identifier_rejects_sql_and_path_syntax(value): {"objects_listing_keys_per_object": 0}, {"objects_size": 5 * 2**30 + 1}, {"objects_concurrency": []}, + {"filesystem_clients": {}}, + {"filesystem_clients": {"Required": {}}}, + {"filesystem_clients": {"required": "when_required"}}, + {"filesystem_clients": {"required": {"checksum": "when_required"}}}, + {"filesystem_clients": {"required": {"request_checksum_calculation": "when_requred"}}}, + {"filesystem_clients": {"required": {"response_checksum_validation": "never"}}}, + {"filesystem_clients": {"retries": {"retries": {"mode": "standrad"}}}}, + {"filesystem_clients": {"pool": {"max_pool_connections": 40}}}, ], ) def test_invalid_measurement_settings(changes): - with pytest.raises(ValueError, match=r"Invalid|positive|must"): + with pytest.raises(ValueError, match=r"Invalid|positive|must|required|sets"): replace(Settings(), **changes) @@ -131,6 +139,55 @@ def test_filesystem_matrix_sweeps_workers_and_pools_for_each_api_and_operation() assert matrix(settings, "filesystem", "nested") == [] +def test_filesystem_clients_add_named_cases(tmp_path): + # GH-1325: each named set of S3 client options is a case of every operation, API, + # and pool; the default client keeps the IDs without a client name. + config = tmp_path / "config.toml" + config.write_text( + "[filesystem]\nmax_workers = [8]\npool_connections = [10]\n" + "[filesystem.clients.default]\n" + '[filesystem.clients.required]\nrequest_checksum_calculation = "when_required"\n' + "[filesystem.clients.unsigned]\n" + 'request_checksum_calculation = "when_required"\n' + "s3 = { payload_signing_enabled = false }\n" + ) + settings = Settings.load(config) + assert settings.filesystem_clients == { + "default": {}, + "required": {"request_checksum_calculation": "when_required"}, + "unsigned": { + "request_checksum_calculation": "when_required", + "s3": {"payload_signing_enabled": False}, + }, + } + cases = matrix(settings, "filesystem", "flat") + assert len(cases) == 5 * 3 * 3 + assert { + "filesystem-s3-sync-put-w8-p10", + "filesystem-s3-aio-put-w8-p10-required", + "filesystem-s3-s3fs-write-w8-p10-unsigned", + } <= {c.id for c in cases} + assert len({c.id for c in cases}) == len(cases) + + +def test_filesystem_clients_are_checked_without_the_aws_configuration(monkeypatch): + # GH-1325: the options are checked without creating a client, which would read + # the AWS configuration of the environment and change nested options in place; + # botocore accepts the checksum values in any case. + monkeypatch.setenv("AWS_PROFILE", "missing") + clients = { + "required": { + "request_checksum_calculation": "WHEN_REQUIRED", + "retries": {"max_attempts": 2}, + } + } + settings = Settings(filesystem_clients=clients) + assert settings.filesystem_clients["required"] == { + "request_checksum_calculation": "WHEN_REQUIRED", + "retries": {"max_attempts": 2}, + } + + def test_filesystem_section_is_loaded_with_its_own_scales(tmp_path): config = tmp_path / "config.toml" config.write_text( diff --git a/benchmarks/tests/test_filesystem.py b/benchmarks/tests/test_filesystem.py index 7143108f9..8c7259b29 100644 --- a/benchmarks/tests/test_filesystem.py +++ b/benchmarks/tests/test_filesystem.py @@ -19,6 +19,7 @@ from pyathena_bench.cases import SINGLE_COPY_THRESHOLDS, Case from pyathena_bench.config import Settings from pyathena_bench.filesystem import ( + client_options, filesystem, get_object, missing_api_reason, @@ -265,6 +266,82 @@ def test_s3fs_filesystem_takes_the_session_credentials_and_the_case_sizes(monkey ] +CLIENTS = { + "unsigned": { + "request_checksum_calculation": "when_required", + "s3": {"payload_signing_enabled": False}, + } +} + + +def client_case(api, suite="filesystem", client="unsigned"): + return Case( + "s3", + api, + "put", + "bytes" if suite == "filesystem" else "objects", + suite=suite, + max_workers=8, + pool_connections=10, + client=client, + ) + + +@pytest.mark.parametrize("api", ["sync", "aio"]) +def test_pyathena_clients_take_the_options_of_the_case(api, monkeypatch, tmp_path): + # GH-1325: the PyAthena filesystems get the case's pool and the options of its + # client through the connection's s3_config. + connected = {} + + class ConnectedError(Exception): + pass + + def connect(**kwargs): + connected.update(kwargs) + raise ConnectedError + + monkeypatch.setattr("pyathena_bench.filesystem.connect", connect) + with pytest.raises(ConnectedError): + asyncio.run( + run_filesystem( + Settings(filesystem_clients=CLIENTS), + client_case(api), + SimpleNamespace(), + "s3://bucket/source", + "s3://bucket/destination", + 2**20, + tmp_path, + ) + ) + config = connected["s3_config"] + assert config.max_pool_connections == 10 + assert config.request_checksum_calculation == "when_required" + assert config.s3 == {"payload_signing_enabled": False} + + +def test_s3fs_client_takes_the_options_of_the_case(monkeypatch): + # GH-1325: s3fs gets them as config_kwargs of its own client. + s3fs = RecordingS3FS() + monkeypatch.setattr("pyathena_bench.filesystem.s3fs", s3fs) + session = SimpleNamespace(get_credentials=lambda: FakeCredentials()) + filesystem(Settings(filesystem_clients=CLIENTS), client_case("s3fs"), session, None) + assert s3fs.created[0]["config_kwargs"] == { + "connect_timeout": 10, + "read_timeout": 60, + "max_pool_connections": 10, + "request_checksum_calculation": "when_required", + "s3": {"payload_signing_enabled": False}, + } + + +def test_objects_clients_take_no_filesystem_client_options(): + # The objects suite's cases have the default client, which a configuration of + # the filesystem suite need not define. + settings = Settings(filesystem_clients=CLIENTS) + case = client_case("s3fs", suite="objects", client="default") + assert client_options(settings, case) == {"max_pool_connections": 10} + + def test_s3fs_api_needs_the_s3fs_package(monkeypatch): monkeypatch.setattr("pyathena_bench.filesystem.s3fs", None) case = Case( diff --git a/benchmarks/tests/test_objects.py b/benchmarks/tests/test_objects.py index 6d4126355..08de88561 100644 --- a/benchmarks/tests/test_objects.py +++ b/benchmarks/tests/test_objects.py @@ -84,9 +84,14 @@ def run_batch(fs, case, paths=PATHS, targets=TARGETS, local=Path("/local"), size @pytest.mark.parametrize( ("api", "method", "options"), - [("sync", "cat", {}), ("aio", "_cat", {"batch_size": 8}), ("s3fs", "cat", {"batch_size": 8})], + [ + ("sync", "cat", {"batch_size": 8}), + ("aio", "_cat", {"batch_size": 8}), + ("s3fs", "cat", {"batch_size": 8}), + ], ) -def test_cat_passes_the_batch_size_of_the_asyncio_apis(api, method, options): +def test_cat_passes_the_batch_size_of_every_api(api, method, options): + # GH-1322: the synchronous filesystem's batch operations run concurrently too. fs = RecordingFileSystem() case = Case("s3", api, "cat", "objects", suite="objects", max_workers=8) assert len(run_batch(fs, case)) == 3 @@ -95,7 +100,7 @@ def test_cat_passes_the_batch_size_of_the_asyncio_apis(api, method, options): @pytest.mark.parametrize("api", ["sync", "aio", "s3fs"]) def test_get_and_put_pair_the_objects_with_local_files_of_the_same_name(api, tmp_path): - options = {} if api == "sync" else {"batch_size": 8} + options = {"batch_size": 8} fs = RecordingFileSystem() locals_ = [str(tmp_path / f"{i:06d}") for i in range(3)] run_batch(fs, Case("s3", api, "get", "objects", suite="objects", max_workers=8), local=tmp_path) @@ -114,7 +119,7 @@ def test_pipe_writes_one_buffer_of_the_object_size_to_every_target(api): [(method, (values,), options)] = fs.calls assert method == ("_pipe" if api == "aio" else "pipe") assert values == dict.fromkeys(TARGETS, bytes(4)) - assert options == ({} if api == "sync" else {"batch_size": 8}) + assert options == {"batch_size": 8} @pytest.mark.parametrize("api", ["sync", "aio", "s3fs"]) @@ -122,7 +127,7 @@ def test_copy_excludes_tags_and_annotations(api): fs = RecordingFileSystem() run_batch(fs, Case("s3", api, "copy", "objects", suite="objects", max_workers=8)) expected = { - **({} if api == "sync" else {"batch_size": 8}), + "batch_size": 8, "TaggingDirective": "REPLACE", "AnnotationDirective": "EXCLUDE", }