dynamicio 9.2.0rc2__tar.gz → 9.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/CHANGELOG.md +4 -0
  2. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/PKG-INFO +1 -1
  3. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/mixins/with_s3.py +107 -34
  4. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_mixins/test_s3_mixins.py +393 -0
  5. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.claude/skills/create-pr/SKILL.md +0 -0
  6. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.coveragerc +0 -0
  7. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.flake8 +0 -0
  8. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.github/CODEOWNERS +0 -0
  9. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.github/ISSUE_TEMPLATE/bug_report.md +0 -0
  10. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.github/ISSUE_TEMPLATE/feature_request.md +0 -0
  11. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.github/dependabot.yml +0 -0
  12. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.github/pull_request_template.md +0 -0
  13. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.github/workflows/build_and_publish.yml +0 -0
  14. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.github/workflows/pr_title_checker.yml +0 -0
  15. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.gitignore +0 -0
  16. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.gitlint +0 -0
  17. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.pre-commit-config.yaml +0 -0
  18. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.pylintrc +0 -0
  19. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.python-version +0 -0
  20. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/.yamllint +0 -0
  21. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/AGENTS.md +0 -0
  22. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/CONTRIBUTING.md +0 -0
  23. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/LICENSE +0 -0
  24. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/Makefile +0 -0
  25. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/README.md +0 -0
  26. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/catalog-info.yaml +0 -0
  27. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/__init__.py +0 -0
  28. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/resources/definitions/input.yaml +0 -0
  29. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/resources/definitions/processed.yaml +0 -0
  30. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/resources/definitions/raw.yaml +0 -0
  31. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/resources/schemas/input/bar.yaml +0 -0
  32. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/resources/schemas/input/events.yaml +0 -0
  33. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/resources/schemas/input/foo.yaml +0 -0
  34. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/resources/schemas/processed/final_bar.yaml +0 -0
  35. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/resources/schemas/processed/final_foo.yaml +0 -0
  36. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/src/__init__.py +0 -0
  37. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/src/__main__.py +0 -0
  38. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/src/constants.py +0 -0
  39. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/src/environment.py +0 -0
  40. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/src/io.py +0 -0
  41. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/src/runner_selection.py +0 -0
  42. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/src/runners/__init__.py +0 -0
  43. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/src/runners/staging.py +0 -0
  44. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/src/runners/transform.py +0 -0
  45. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/__init__.py +0 -0
  46. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/conftest.py +0 -0
  47. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/constants.py +0 -0
  48. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/data/input/bar.parquet +0 -0
  49. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/data/input/events/part_2026.parquet +0 -0
  50. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/data/input/foo.csv +0 -0
  51. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/data/processed/expected/final_bar.parquet +0 -0
  52. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/data/processed/expected/final_foo.parquet +0 -0
  53. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/data/raw/expected/staged_bar.parquet +0 -0
  54. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/data/raw/expected/staged_foo.parquet +0 -0
  55. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/runners/__init__.py +0 -0
  56. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/runners/conftest.py +0 -0
  57. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/runners/test_staging.py +0 -0
  58. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/runners/test_transform.py +0 -0
  59. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/test_pipeline.py +0 -0
  60. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/test_prefix_schema_evolution.py +0 -0
  61. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/demo/tests/test_runner_selection.py +0 -0
  62. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/adr/0001-direct-boto3-s3-io.md +0 -0
  63. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/adr/0002-tolerate-missing-columns-in-parquet-prefix-reads.md +0 -0
  64. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/adr/0003-athena-via-aws-wrangler.md +0 -0
  65. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/adr/0004-ranged-parquet-reads-with-filters.md +0 -0
  66. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/adr/README.md +0 -0
  67. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/api.md +0 -0
  68. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/images/data-types.png +0 -0
  69. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/images/logo-original.png +0 -0
  70. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/images/logo-transparent.png +0 -0
  71. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/images/perf-awswrangler-vs-awscli/chart_read.png +0 -0
  72. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/images/perf-awswrangler-vs-awscli/chart_read_correction.png +0 -0
  73. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/images/perf-awswrangler-vs-awscli/chart_write.png +0 -0
  74. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/images/perf-pipeline-run/pipeline-task-delta.png +0 -0
  75. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/images/sample-pipeline.png +0 -0
  76. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/images/supported_sources.png +0 -0
  77. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/images/wrapped-panda.png +0 -0
  78. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/index.md +0 -0
  79. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/docs/perf-s3-io.md +0 -0
  80. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/__init__.py +0 -0
  81. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/__main__.py +0 -0
  82. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/animals.py +0 -0
  83. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/cli.py +0 -0
  84. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/config/__init__.py +0 -0
  85. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/config/io_config.py +0 -0
  86. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/config/pydantic/__init__.py +0 -0
  87. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/config/pydantic/config.py +0 -0
  88. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/config/pydantic/io_resources.py +0 -0
  89. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/config/pydantic/table_schema.py +0 -0
  90. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/core.py +0 -0
  91. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/errors.py +0 -0
  92. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/metrics.py +0 -0
  93. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/mixins/__init__.py +0 -0
  94. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/mixins/utils.py +0 -0
  95. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/mixins/with_athena.py +0 -0
  96. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/mixins/with_kafka.py +0 -0
  97. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/mixins/with_local.py +0 -0
  98. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/mixins/with_postgres.py +0 -0
  99. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/py.typed +0 -0
  100. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/dynamicio/validations.py +0 -0
  101. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/mkdocs.yaml +0 -0
  102. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/pyproject.toml +0 -0
  103. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/__init__.py +0 -0
  104. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/conftest.py +0 -0
  105. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/constants.py +0 -0
  106. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/mocking/__init__.py +0 -0
  107. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/mocking/io.py +0 -0
  108. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/mocking/models.py +0 -0
  109. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/external/h5_with_more_columns.h5 +0 -0
  110. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/external/json_with_more_columns.json +0 -0
  111. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/hdf/part_01.h5 +0 -0
  112. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/hdf/part_02.h5 +0 -0
  113. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/not_just_hdf/part_01.h5 +0 -0
  114. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/not_just_hdf/part_02.h5 +0 -0
  115. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/not_just_hdf/something_to_ignore.txt +0 -0
  116. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/not_just_parquet/part_01.parquet +0 -0
  117. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/not_just_parquet/part_02.parquet +0 -0
  118. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/not_just_parquet/something_to_ignore.txt +0 -0
  119. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/parquet/dynamic/dir_01/part_01.parquet +0 -0
  120. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/parquet/dynamic/dir_01/part_02.parquet +0 -0
  121. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/parquet/dynamic/dir_02/part_01.parquet +0 -0
  122. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/parquet/dynamic/dir_02/part_02.parquet +0 -0
  123. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/parquet/part_01.parquet +0 -0
  124. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/parquet/part_02.parquet +0 -0
  125. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/parquet_w_empty_files/emptyfile.parquet +0 -0
  126. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/batch/parquet_w_empty_files/fullfile.parquet +0 -0
  127. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/multi_row_json.json +0 -0
  128. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/single_row_json.json +0 -0
  129. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/some_csv_to_read.csv +0 -0
  130. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/some_hdf_to_read.h5 +0 -0
  131. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/some_json_to_read.json +0 -0
  132. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/some_parquet_to_read.parquet +0 -0
  133. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/input/some_pg_parquet_to_read.parquet +0 -0
  134. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/processed/.gitkeep +0 -0
  135. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/data/temp/.gitkeep +0 -0
  136. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/definitions/external.yaml +0 -0
  137. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/definitions/input.yaml +0 -0
  138. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/definitions/processed.yaml +0 -0
  139. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/definitions/test_input.yaml +0 -0
  140. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/schemas/bar.yaml +0 -0
  141. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/schemas/foo.yaml +0 -0
  142. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/schemas/pg.yaml +0 -0
  143. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/schemas/read_from_s3_csv.yaml +0 -0
  144. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/schemas/some_csv_to_read.yaml +0 -0
  145. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/schemas/some_hdf_to_read.yaml +0 -0
  146. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/schemas/some_json_to_read.yaml +0 -0
  147. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/schemas/some_parquet_to_read.yaml +0 -0
  148. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/schemas/some_pg_parquet_to_read.yaml +0 -0
  149. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/resources/schemas/write_to_s3_csv.yaml +0 -0
  150. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_cli.py +0 -0
  151. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_config.py +0 -0
  152. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_core.py +0 -0
  153. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_errors.py +0 -0
  154. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_metrics.py +0 -0
  155. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_mixins/__init__.py +0 -0
  156. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_mixins/test_athena_mixin.py +0 -0
  157. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_mixins/test_kafka_mixins.py +0 -0
  158. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_mixins/test_local_mixins.py +0 -0
  159. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_mixins/test_postgres_mixins.py +0 -0
  160. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_mixins/test_utils.py +0 -0
  161. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_table_schema.py +0 -0
  162. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/tests/test_validations.py +0 -0
  163. {dynamicio-9.2.0rc2 → dynamicio-9.2.1}/uv.lock +0 -0
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ - fix: transient S3 connection errors no longer fail a read or write. The shared boto3 client now uses the `standard` retry mode with 10 attempts, `connect_timeout=10` and `read_timeout=60`. The in-memory and file transfers (`put_object`, `upload_fileobj`, `get_object`, `download_fileobj`) are repeated, up to 5 attempts with backoff, on `ConnectionClosedError`, `ConnectTimeoutError`, `EndpointConnectionError`, `ReadTimeoutError`, `IncompleteReadError`, `ResponseStreamingError` and the `RetriesExceededError` that the transfer manager raises (s3transfer's and boto3's) when a download above 16 MiB gave up on a broken part. botocore does not retry these once the body is being sent or read. The buffer is rewound before each attempt (bytes written are identical), each retry is logged at WARNING with the bucket and key, and the shared client is rebuilt so the next attempt opens fresh connections. Other errors (for example `ClientError`) are raised as before, and nothing changes when no error occurs
6
+
3
7
  ## v9.2.0
4
8
 
5
9
  - feat: a single-file S3 parquet read with `filters` reads only the row groups whose footer statistics can match, over ranged `GetObject` requests through `pyarrow.fs.S3FileSystem` (one for each process and bucket). The rows, index and dtypes are the same as before. Reads without `filters` or with `filters=[]`, fastparquet reads, reads with a non-pyarrow `filesystem`, prefix reads and reads with wrangler-only kwargs do not change. On the ranged read, a missing key or a permission problem raises pyarrow `FileNotFoundError` or `OSError` in place of botocore `ClientError`, and a custom S3 endpoint of boto3 (`AWS_ENDPOINT_URL`) does not apply. See ADR 0004
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: dynamicio
3
- Version: 9.2.0rc2
3
+ Version: 9.2.1
4
4
  Summary: Panda's wrapper for IO operations
5
5
  Author-email: Christos Hadjinikolis <christos.hadjinikolis@gmail.com>, Radu Ghitescu <radu.ghitescu@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -6,26 +6,31 @@ import dataclasses
6
6
  import fnmatch
7
7
  import io
8
8
  import os
9
+ import random
9
10
  import shutil
10
11
  import tempfile
11
12
  import threading
13
+ import time
12
14
  import urllib.parse
13
15
  import uuid
14
16
  from concurrent.futures import ThreadPoolExecutor
15
17
  from contextlib import contextmanager
16
- from typing import IO, Any, Callable, Dict, Generator, List, Mapping, Optional, Union
18
+ from typing import IO, Any, Callable, Dict, Generator, List, Mapping, Optional, TypeVar, Union
17
19
  from urllib.parse import urlparse
18
20
 
19
21
  import awswrangler as wr
20
22
  import boto3
23
+ import boto3.exceptions
21
24
  import boto3.s3.transfer
22
25
  import pandas as pd
23
26
  import pyarrow as pa
24
27
  import pyarrow.fs as pafs
25
28
  import pyarrow.parquet as pq
29
+ import s3transfer.exceptions
26
30
  import s3transfer.futures
27
31
  import tables
28
32
  from botocore.config import Config
33
+ from botocore.exceptions import ConnectionClosedError, ConnectTimeoutError, EndpointConnectionError, IncompleteReadError, ReadTimeoutError, ResponseStreamingError
29
34
  from magic_logger import logger
30
35
  from pandas import DataFrame, Series
31
36
 
@@ -152,6 +157,12 @@ class HdfIO:
152
157
  fobj.write(file_handle.get_file_image())
153
158
 
154
159
 
160
+ # Pool: must cover the sync thread pools. Retries: botocore's "standard" mode (10 attempts) also covers broken connections and
161
+ # throttling. Keepalive probes stop idle pooled connections from being dropped silently; the timeouts match botocore's read default
162
+ # and fail a dead connect quickly so that it is retried.
163
+ _CLIENT_CONFIG = Config(max_pool_connections=64, retries={"mode": "standard", "max_attempts": 10}, connect_timeout=10, read_timeout=60)
164
+
165
+
155
166
  def _shared_s3_client():
156
167
  """Return a per-process S3 client built from the shared session (thread-safe, keeps connections alive)."""
157
168
  session = _shared_boto3_session()
@@ -159,10 +170,55 @@ def _shared_s3_client():
159
170
  with _SESSION_LOCK:
160
171
  if pid not in _CLIENT:
161
172
  _CLIENT.clear()
162
- _CLIENT[pid] = session.client("s3", config=Config(max_pool_connections=64)) # pool must cover the sync thread pools
173
+ _CLIENT[pid] = session.client("s3", config=_CLIENT_CONFIG)
163
174
  return _CLIENT[pid]
164
175
 
165
176
 
177
+ def _drop_shared_s3_client() -> None:
178
+ """Forget this process's shared client so the next call builds one with fresh connection pools."""
179
+ with _SESSION_LOCK:
180
+ _CLIENT.pop(os.getpid(), None)
181
+
182
+
183
+ _T = TypeVar("_T")
184
+ # Errors that mean "the connection broke, the request may not have been handled": repeating an S3 GET or PUT of the same object is safe.
185
+ # Above `_DIRECT_TRANSFER_MAX_BYTES` the transfer manager repeats a broken part 5 times and then raises RetriesExceededError, wrapping the error
186
+ # in `last_exception`: s3transfer's own for `download_fileobj`, boto3's for `download_file`. Only broken connections are wrapped this way.
187
+ _TRANSIENT_S3_ERRORS = (
188
+ ConnectionClosedError,
189
+ ConnectTimeoutError,
190
+ EndpointConnectionError,
191
+ IncompleteReadError,
192
+ ReadTimeoutError,
193
+ ResponseStreamingError,
194
+ s3transfer.exceptions.RetriesExceededError,
195
+ boto3.exceptions.RetriesExceededError,
196
+ )
197
+ _TRANSFER_ATTEMPTS = 5
198
+ _TRANSFER_BACKOFF_SECONDS = 0.5
199
+
200
+
201
+ def _retry_transient(operation: Callable[[], _T], description: str) -> _T:
202
+ """Run a whole S3 transfer, repeating it when the connection breaks, and return its result.
203
+
204
+ botocore retries a request that fails on a broken connection, but not a response body that breaks while it is
205
+ being read, nor a multipart transfer that gave up. This repeats the transfer as a whole, after dropping the shared
206
+ client so a new attempt cannot reuse a pool of dead sockets. `operation` must be safe to repeat: it has to
207
+ rewind its own buffers and overwrite the same object.
208
+ """
209
+ for attempt in range(1, _TRANSFER_ATTEMPTS + 1):
210
+ try:
211
+ return operation()
212
+ except _TRANSIENT_S3_ERRORS as error:
213
+ if attempt == _TRANSFER_ATTEMPTS:
214
+ raise
215
+ delay = _TRANSFER_BACKOFF_SECONDS * 2 ** (attempt - 1) * (1 + random.random())
216
+ logger.warning(f"[s3] {type(error).__name__} on {description} (attempt {attempt} of {_TRANSFER_ATTEMPTS}), retrying in {delay:.1f}s: {error}")
217
+ _drop_shared_s3_client()
218
+ time.sleep(delay)
219
+ raise AssertionError("unreachable") # pragma: no cover
220
+
221
+
166
222
  def _s3_filesystem(bucket: str) -> pafs.S3FileSystem:
167
223
  """Return a per-process pyarrow S3 file system in the region of `bucket` (same default credential chain as boto3).
168
224
 
@@ -190,15 +246,20 @@ def _split_s3_url(url: str):
190
246
  _SYNC_MAX_CONCURRENCY = 32 # measured best/flat from 32 up for 200-5000 files; the old 10 was up to 2x slower on small prefixes
191
247
 
192
248
 
193
- def _download_file(client, bucket: str, key: str, local_path: str):
249
+ def _download_file(bucket: str, key: str, local_path: str):
194
250
  """Download one object: a single GetObject for small ones, the multipart transfer manager for large ones."""
195
- response = client.get_object(Bucket=bucket, Key=key)
196
- if response["ContentLength"] > _DIRECT_TRANSFER_MAX_BYTES:
197
- response["Body"].close()
198
- client.download_file(bucket, key, local_path)
199
- return
200
- with open(local_path, "wb") as fobj:
201
- shutil.copyfileobj(response["Body"], fobj)
251
+
252
+ def attempt():
253
+ client = _shared_s3_client() # reacquired: a retry must not reuse the client evicted after the failure
254
+ response = client.get_object(Bucket=bucket, Key=key)
255
+ if response["ContentLength"] > _DIRECT_TRANSFER_MAX_BYTES:
256
+ response["Body"].close()
257
+ client.download_file(bucket, key, local_path)
258
+ return
259
+ with open(local_path, "wb") as fobj:
260
+ shutil.copyfileobj(response["Body"], fobj)
261
+
262
+ _retry_transient(attempt, f"s3://{bucket}/{key}")
202
263
 
203
264
 
204
265
  def s3_sync_down(source_url: str, dest_dir: str, include_pattern: Optional[str] = None, max_concurrency: int = _SYNC_MAX_CONCURRENCY):
@@ -232,7 +293,7 @@ def s3_sync_down(source_url: str, dest_dir: str, include_pattern: Optional[str]
232
293
  continue
233
294
  local_path = os.path.join(dest_dir, *relative_key.split("/"))
234
295
  os.makedirs(os.path.dirname(local_path), exist_ok=True)
235
- futures.append(pool.submit(_download_file, client, bucket, obj["Key"], local_path))
296
+ futures.append(pool.submit(_download_file, bucket, obj["Key"], local_path))
236
297
  for future in futures:
237
298
  future.result()
238
299
 
@@ -274,13 +335,18 @@ def s3_read_down(source_url: str, reader: Callable[[io.BytesIO], Any], include_p
274
335
  return [future.result() for future in futures]
275
336
 
276
337
 
277
- def _upload_file(client, local_path: str, bucket: str, key: str, acl: str):
338
+ def _upload_file(local_path: str, bucket: str, key: str, acl: str):
278
339
  """Upload one file: a single PutObject for small ones, the multipart transfer manager for large ones."""
279
- if os.path.getsize(local_path) > _DIRECT_TRANSFER_MAX_BYTES:
280
- client.upload_file(local_path, bucket, key, ExtraArgs={"ACL": acl})
281
- return
282
- with open(local_path, "rb") as fobj:
283
- client.put_object(Bucket=bucket, Key=key, Body=fobj, ACL=acl)
340
+
341
+ def attempt():
342
+ client = _shared_s3_client() # reacquired: a retry must not reuse the client evicted after the failure
343
+ if os.path.getsize(local_path) > _DIRECT_TRANSFER_MAX_BYTES:
344
+ client.upload_file(local_path, bucket, key, ExtraArgs={"ACL": acl})
345
+ return
346
+ with open(local_path, "rb") as fobj:
347
+ client.put_object(Bucket=bucket, Key=key, Body=fobj, ACL=acl)
348
+
349
+ _retry_transient(attempt, f"s3://{bucket}/{key}")
284
350
 
285
351
 
286
352
  def s3_sync_up(source_dir: str, dest_url: str, acl: str = "bucket-owner-full-control", max_concurrency: int = _SYNC_MAX_CONCURRENCY):
@@ -294,7 +360,6 @@ def s3_sync_up(source_dir: str, dest_url: str, acl: str = "bucket-owner-full-con
294
360
  """
295
361
  bucket, key_prefix = _split_s3_url(dest_url)
296
362
  key_prefix = f"{key_prefix.rstrip('/')}/" if key_prefix else ""
297
- client = _shared_s3_client()
298
363
 
299
364
  with ThreadPoolExecutor(max_workers=max_concurrency) as pool:
300
365
  futures = []
@@ -302,7 +367,7 @@ def s3_sync_up(source_dir: str, dest_url: str, acl: str = "bucket-owner-full-con
302
367
  for name in files:
303
368
  local_path = os.path.join(root, name)
304
369
  relative_key = os.path.relpath(local_path, source_dir).replace(os.sep, "/")
305
- futures.append(pool.submit(_upload_file, client, local_path, bucket, f"{key_prefix}{relative_key}", acl))
370
+ futures.append(pool.submit(_upload_file, local_path, bucket, f"{key_prefix}{relative_key}", acl))
306
371
  for future in futures:
307
372
  future.result()
308
373
 
@@ -316,26 +381,34 @@ _WRANGLER_ONLY_WRITE_PARQUET = utils.args_of(wr.s3.to_parquet) - utils.args_of(p
316
381
 
317
382
  def _download_to_memory(bucket: str, key: str) -> io.BytesIO:
318
383
  """Download an S3 object into memory over the shared client (one round trip for small objects)."""
319
- client = _shared_s3_client()
320
- response = client.get_object(Bucket=bucket, Key=key)
321
- if response["ContentLength"] <= _DIRECT_TRANSFER_MAX_BYTES:
322
- return io.BytesIO(response["Body"].read())
323
- response["Body"].close()
324
- fobj = io.BytesIO()
325
- client.download_fileobj(bucket, key, fobj)
326
- fobj.seek(0)
327
- return fobj
384
+
385
+ def attempt():
386
+ client = _shared_s3_client()
387
+ response = client.get_object(Bucket=bucket, Key=key)
388
+ if response["ContentLength"] <= _DIRECT_TRANSFER_MAX_BYTES:
389
+ return io.BytesIO(response["Body"].read())
390
+ response["Body"].close()
391
+ fobj = io.BytesIO()
392
+ client.download_fileobj(bucket, key, fobj)
393
+ fobj.seek(0)
394
+ return fobj
395
+
396
+ return _retry_transient(attempt, f"s3://{bucket}/{key}")
328
397
 
329
398
 
330
399
  def _upload_from_memory(fobj: io.BytesIO, bucket: str, key: str, acl: str = "bucket-owner-full-control") -> None:
331
400
  """Upload an in-memory buffer over the shared client (single PUT for small objects)."""
332
- client = _shared_s3_client()
333
401
  size = fobj.getbuffer().nbytes
334
- fobj.seek(0)
335
- if size <= _DIRECT_TRANSFER_MAX_BYTES:
336
- client.put_object(Bucket=bucket, Key=key, Body=fobj.getvalue(), ACL=acl)
337
- else:
338
- client.upload_fileobj(fobj, bucket, key, ExtraArgs={"ACL": acl})
402
+
403
+ def attempt():
404
+ client = _shared_s3_client()
405
+ fobj.seek(0)
406
+ if size <= _DIRECT_TRANSFER_MAX_BYTES:
407
+ client.put_object(Bucket=bucket, Key=key, Body=fobj.getvalue(), ACL=acl)
408
+ else:
409
+ client.upload_fileobj(fobj, bucket, key, ExtraArgs={"ACL": acl})
410
+
411
+ _retry_transient(attempt, f"s3://{bucket}/{key}")
339
412
 
340
413
 
341
414
  def _read_parquet_object(fobj: IO[bytes], schema: DataframeSchema, options: Mapping[str, Any], absent: List[str]) -> pd.DataFrame:
@@ -2,24 +2,31 @@
2
2
  import io
3
3
  import os
4
4
  import shutil
5
+ import socket
6
+ import struct
5
7
  import subprocess
6
8
  import sys
7
9
  import threading
8
10
  import types
9
11
  import urllib.parse
10
12
  import urllib.request
13
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
14
  from io import StringIO
12
15
  from tempfile import NamedTemporaryFile
13
16
  from unittest import mock
14
17
  from unittest.mock import MagicMock, patch
15
18
 
16
19
  import boto3
20
+ import boto3.exceptions
17
21
  import pandas as pd
18
22
  import pyarrow.fs as pafs
19
23
  import pyarrow.parquet as pq
20
24
  import pydantic
21
25
  import pytest
26
+ import s3transfer.exceptions
22
27
  import yaml
28
+ from botocore.config import Config
29
+ from botocore.exceptions import ClientError, ConnectionClosedError, EndpointConnectionError, ReadTimeoutError, ResponseStreamingError
23
30
 
24
31
  # Application Imports
25
32
  import dynamicio.errors
@@ -1903,3 +1910,389 @@ class TestS3ParquetRangedReadOverS3Protocol:
1903
1910
  gets = self._object_gets(moto_s3_server)
1904
1911
  assert len(gets) == 1 and gets[0]["range"] is None and gets[0]["bytes"] == len(s3_object)
1905
1912
  assert len(df) == 300_000
1913
+
1914
+
1915
+ class _FlakyS3Client:
1916
+ """An in-memory S3 client whose first `failures` transfers drop the connection, as S3 did on a pooled socket."""
1917
+
1918
+ def __init__(self, failures, error):
1919
+ self.failures = failures
1920
+ self.error = error
1921
+ self.calls = 0
1922
+ self.objects = {}
1923
+
1924
+ def _maybe_fail(self):
1925
+ self.calls += 1
1926
+ if self.calls <= self.failures:
1927
+ raise self.error
1928
+
1929
+ def put_object(self, Bucket, Key, Body, **_): # pylint: disable=invalid-name
1930
+ self._maybe_fail()
1931
+ self.objects[(Bucket, Key)] = Body.read() if hasattr(Body, "read") else bytes(Body)
1932
+
1933
+ def upload_fileobj(self, fobj, bucket, key, **_):
1934
+ data = fobj.read() # consumes the buffer, as the transfer manager does before it fails
1935
+ self._maybe_fail()
1936
+ self.objects[(bucket, key)] = data
1937
+
1938
+ def get_object(self, Bucket, Key): # pylint: disable=invalid-name
1939
+ data = self.objects[(Bucket, Key)]
1940
+ body = MagicMock()
1941
+ chunks = [data, b""]
1942
+ body.read.side_effect = lambda *_: self._raise_or(chunks.pop(0))
1943
+ return {"ContentLength": len(data), "Body": body}
1944
+
1945
+ def _raise_or(self, data):
1946
+ self._maybe_fail()
1947
+ return data
1948
+
1949
+ def download_fileobj(self, bucket, key, fobj):
1950
+ self._maybe_fail()
1951
+ fobj.write(self.objects[(bucket, key)])
1952
+
1953
+ def upload_file(self, local_path, bucket, key, **_):
1954
+ self._maybe_fail()
1955
+ with open(local_path, "rb") as fobj:
1956
+ self.objects[(bucket, key)] = fobj.read()
1957
+
1958
+ def download_file(self, bucket, key, local_path):
1959
+ self._maybe_fail()
1960
+ with open(local_path, "wb") as fobj:
1961
+ fobj.write(self.objects[(bucket, key)])
1962
+
1963
+
1964
+ class TestS3TransientConnectionErrors:
1965
+ """A broken connection during a transfer is repeated instead of failing the task (intermittent put_object BrokenPipe)."""
1966
+
1967
+ BUCKET, KEY = "bucket", "dir/file.parquet"
1968
+
1969
+ @staticmethod
1970
+ def _closed():
1971
+ return ConnectionClosedError(endpoint_url="https://s3.eu-west-1.amazonaws.com/bucket/dir/file.parquet")
1972
+
1973
+ @pytest.fixture(autouse=True)
1974
+ def _no_sleep(self):
1975
+ with patch.object(dynamicio.mixins.with_s3.time, "sleep") as sleep:
1976
+ yield sleep
1977
+
1978
+ @pytest.mark.unit
1979
+ def test_small_upload_is_repeated_and_stores_identical_bytes(self, _no_sleep):
1980
+ # Given
1981
+ data = os.urandom(4096)
1982
+ client = _FlakyS3Client(failures=2, error=self._closed())
1983
+
1984
+ # When
1985
+ with patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", return_value=client), patch("dynamicio.mixins.with_s3.logger") as logger:
1986
+ dynamicio.mixins.with_s3._upload_from_memory(io.BytesIO(data), self.BUCKET, self.KEY)
1987
+
1988
+ # Then
1989
+ assert client.calls == 3 and client.objects[(self.BUCKET, self.KEY)] == data
1990
+ assert _no_sleep.call_count == 2
1991
+ assert all(self.KEY in call.args[0] and "ConnectionClosedError" in call.args[0] for call in logger.warning.call_args_list) and logger.warning.call_count == 2
1992
+
1993
+ @pytest.mark.unit
1994
+ @pytest.mark.parametrize("threshold", [1024, 10**9], ids=["transfer-manager", "single-request"])
1995
+ def test_file_upload_is_repeated_on_the_replacement_client_and_stores_identical_bytes(self, tmp_path, threshold):
1996
+ # Given: the client that failed is evicted, so the retry must ask for the shared client again
1997
+ data = os.urandom(4096)
1998
+ local_path = tmp_path / "upload.bin"
1999
+ local_path.write_bytes(data)
2000
+ failing = _FlakyS3Client(failures=1, error=self._closed())
2001
+ replacement = _FlakyS3Client(failures=0, error=self._closed())
2002
+
2003
+ # When
2004
+ with (
2005
+ patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", side_effect=[failing, replacement]),
2006
+ patch.object(dynamicio.mixins.with_s3, "_DIRECT_TRANSFER_MAX_BYTES", threshold),
2007
+ ):
2008
+ dynamicio.mixins.with_s3._upload_file(str(local_path), self.BUCKET, self.KEY, "bucket-owner-full-control")
2009
+
2010
+ # Then
2011
+ assert failing.calls == 1 and not failing.objects
2012
+ assert replacement.calls == 1 and replacement.objects[(self.BUCKET, self.KEY)] == data
2013
+
2014
+ @pytest.mark.unit
2015
+ @pytest.mark.parametrize("threshold", [1024, 10**9], ids=["transfer-manager", "single-request"])
2016
+ def test_file_download_is_repeated_on_the_replacement_client_and_writes_identical_bytes(self, tmp_path, threshold):
2017
+ # Given
2018
+ data = os.urandom(4096)
2019
+ failing = _FlakyS3Client(failures=1, error=self._closed())
2020
+ failing.objects[(self.BUCKET, self.KEY)] = data
2021
+ replacement = _FlakyS3Client(failures=0, error=self._closed())
2022
+ replacement.objects[(self.BUCKET, self.KEY)] = data
2023
+
2024
+ # When
2025
+ with (
2026
+ patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", side_effect=[failing, replacement]),
2027
+ patch.object(dynamicio.mixins.with_s3, "_DIRECT_TRANSFER_MAX_BYTES", threshold),
2028
+ ):
2029
+ dynamicio.mixins.with_s3._download_file(self.BUCKET, self.KEY, str(tmp_path / "download.bin"))
2030
+
2031
+ # Then
2032
+ assert failing.calls == 1 and replacement.calls > 0 # a body read is a call too
2033
+ assert (tmp_path / "download.bin").read_bytes() == data
2034
+
2035
+ @pytest.mark.unit
2036
+ @pytest.mark.parametrize("wrapper", [s3transfer.exceptions.RetriesExceededError, boto3.exceptions.RetriesExceededError], ids=["download_fileobj", "download_file"])
2037
+ def test_a_download_the_transfer_manager_gave_up_on_is_repeated(self, tmp_path, wrapper):
2038
+ # Given: above 16 MiB s3transfer repeats a broken part 5 times and raises RetriesExceededError (boto3's own class for download_file)
2039
+ data = os.urandom(4096)
2040
+ client = _FlakyS3Client(failures=2, error=wrapper(ResponseStreamingError(error="Connection broken")))
2041
+ client.objects[(self.BUCKET, self.KEY)] = data
2042
+
2043
+ # When
2044
+ with patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", return_value=client), patch.object(dynamicio.mixins.with_s3, "_DIRECT_TRANSFER_MAX_BYTES", 1024):
2045
+ in_memory = dynamicio.mixins.with_s3._download_to_memory(self.BUCKET, self.KEY)
2046
+ client.calls = 0
2047
+ dynamicio.mixins.with_s3._download_file(self.BUCKET, self.KEY, str(tmp_path / "download.bin"))
2048
+
2049
+ # Then
2050
+ assert in_memory.getvalue() == data and (tmp_path / "download.bin").read_bytes() == data
2051
+
2052
+ @pytest.mark.unit
2053
+ def test_multipart_upload_rewinds_the_buffer_before_each_attempt(self):
2054
+ # Given
2055
+ data = os.urandom(4096)
2056
+ client = _FlakyS3Client(failures=1, error=self._closed())
2057
+
2058
+ # When
2059
+ with patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", return_value=client), patch.object(dynamicio.mixins.with_s3, "_DIRECT_TRANSFER_MAX_BYTES", 1024):
2060
+ dynamicio.mixins.with_s3._upload_from_memory(io.BytesIO(data), self.BUCKET, self.KEY)
2061
+
2062
+ # Then
2063
+ assert client.calls == 2 and client.objects[(self.BUCKET, self.KEY)] == data
2064
+
2065
+ @pytest.mark.unit
2066
+ @pytest.mark.parametrize(
2067
+ "error", [ConnectionClosedError(endpoint_url="u"), EndpointConnectionError(endpoint_url="u"), ReadTimeoutError(endpoint_url="u"), ResponseStreamingError(error="reset")]
2068
+ )
2069
+ def test_download_is_repeated_for_each_transient_error_type(self, error):
2070
+ # Given
2071
+ data = os.urandom(2048)
2072
+ client = _FlakyS3Client(failures=1, error=error)
2073
+ client.objects[(self.BUCKET, self.KEY)] = data
2074
+
2075
+ # When
2076
+ with patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", return_value=client):
2077
+ result = dynamicio.mixins.with_s3._download_to_memory(self.BUCKET, self.KEY)
2078
+
2079
+ # Then
2080
+ assert result.getvalue() == data and client.calls == 2
2081
+
2082
+ @pytest.mark.unit
2083
+ def test_the_shared_client_is_dropped_after_a_connection_error(self):
2084
+ # Given
2085
+ client = _FlakyS3Client(failures=1, error=self._closed())
2086
+
2087
+ # When
2088
+ with patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", return_value=client), patch.object(dynamicio.mixins.with_s3, "_drop_shared_s3_client") as drop:
2089
+ dynamicio.mixins.with_s3._upload_from_memory(io.BytesIO(b"x"), self.BUCKET, self.KEY)
2090
+
2091
+ # Then
2092
+ drop.assert_called_once()
2093
+
2094
+ @pytest.mark.unit
2095
+ def test_the_original_error_is_raised_when_every_attempt_fails(self):
2096
+ # Given
2097
+ client = _FlakyS3Client(failures=100, error=self._closed())
2098
+
2099
+ # When / Then
2100
+ with patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", return_value=client), pytest.raises(ConnectionClosedError):
2101
+ dynamicio.mixins.with_s3._upload_from_memory(io.BytesIO(b"x"), self.BUCKET, self.KEY)
2102
+ assert client.calls == dynamicio.mixins.with_s3._TRANSFER_ATTEMPTS
2103
+
2104
+ @pytest.mark.unit
2105
+ def test_errors_that_are_not_connection_errors_are_not_repeated(self):
2106
+ # Given
2107
+ client = _FlakyS3Client(failures=100, error=ClientError({"Error": {"Code": "AccessDenied", "Message": "denied"}}, "PutObject"))
2108
+
2109
+ # When / Then
2110
+ with patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", return_value=client), pytest.raises(ClientError):
2111
+ dynamicio.mixins.with_s3._upload_from_memory(io.BytesIO(b"x"), self.BUCKET, self.KEY)
2112
+ assert client.calls == 1
2113
+
2114
+ @pytest.mark.unit
2115
+ def test_a_cloud_parquet_write_survives_dropped_connections_and_reads_back_identically(self):
2116
+ # Given
2117
+ df = pd.DataFrame.from_dict({"col_1": [3, 2, 1, 0], "col_2": ["a", "b", "c", "d"]})
2118
+ config = TestS3ParquetTransferPaths._config("WRITE_TO_S3_PARQUET", "definitions/processed.yaml")
2119
+ client = _FlakyS3Client(failures=2, error=self._closed())
2120
+
2121
+ # When
2122
+ with patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", return_value=client):
2123
+ WriteS3IO(source_config=config).write(df)
2124
+
2125
+ # Then
2126
+ stored = next(iter(client.objects.values()))
2127
+ pd.testing.assert_frame_equal(pd.read_parquet(io.BytesIO(stored)), df)
2128
+
2129
+ @pytest.mark.unit
2130
+ def test_the_shared_client_is_configured_for_retries_and_timeouts(self):
2131
+ # When
2132
+ config = dynamicio.mixins.with_s3._CLIENT_CONFIG
2133
+
2134
+ # Then
2135
+ assert config.retries == {"mode": "standard", "max_attempts": 10}
2136
+ assert (config.connect_timeout, config.read_timeout, config.max_pool_connections) == (10, 60, 64)
2137
+
2138
+
2139
+ class TestS3ConnectionResetsOverRealSockets:
2140
+ """Resets the TCP connection of the first requests to a local S3 server, as the pods saw ConnectionClosedError / BrokenPipe on put_object."""
2141
+
2142
+ @pytest.fixture
2143
+ def flaky_s3(self, monkeypatch):
2144
+ moto_server = pytest.importorskip("moto.server") # dev dependency only; the dependency-ranges CI jobs do not install it
2145
+ serving = pytest.importorskip("werkzeug.serving")
2146
+ for name in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"):
2147
+ monkeypatch.setenv(name, "testing")
2148
+ server = serving.make_server("127.0.0.1", 0, moto_server.DomainDispatcherApplication(moto_server.create_backend_app), threaded=True)
2149
+ threading.Thread(target=server.serve_forever, daemon=True).start()
2150
+ listener = socket.socket()
2151
+ listener.bind(("127.0.0.1", 0))
2152
+ listener.listen(64)
2153
+ state = types.SimpleNamespace(resets_left=0, resets=0, lock=threading.Lock())
2154
+
2155
+ def pipe(source, target):
2156
+ try:
2157
+ while chunk := source.recv(65536):
2158
+ target.sendall(chunk)
2159
+ except OSError:
2160
+ pass
2161
+ finally:
2162
+ for sock in (source, target):
2163
+ try:
2164
+ sock.shutdown(socket.SHUT_RDWR)
2165
+ except OSError:
2166
+ pass
2167
+
2168
+ def handle(client):
2169
+ with state.lock:
2170
+ reset = state.resets_left > 0
2171
+ if reset:
2172
+ state.resets_left -= 1
2173
+ state.resets += 1
2174
+ if reset:
2175
+ client.recv(1024) # the request has started when S3 drops the connection
2176
+ client.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) # close() sends RST
2177
+ client.close()
2178
+ return
2179
+ upstream = socket.create_connection(("127.0.0.1", server.server_port))
2180
+ threading.Thread(target=pipe, args=(client, upstream), daemon=True).start()
2181
+ threading.Thread(target=pipe, args=(upstream, client), daemon=True).start()
2182
+
2183
+ def accept_loop():
2184
+ while True:
2185
+ try:
2186
+ client, _ = listener.accept()
2187
+ except OSError:
2188
+ return
2189
+ threading.Thread(target=handle, args=(client,), daemon=True).start()
2190
+
2191
+ threading.Thread(target=accept_loop, daemon=True).start()
2192
+ endpoint = f"http://127.0.0.1:{listener.getsockname()[1]}"
2193
+ client = boto3.client("s3", endpoint_url=endpoint, region_name="us-east-1", config=dynamicio.mixins.with_s3._CLIENT_CONFIG)
2194
+ boto3.client("s3", endpoint_url=f"http://127.0.0.1:{server.server_port}", region_name="us-east-1").create_bucket(Bucket="bucket")
2195
+ yield types.SimpleNamespace(client=client, state=state)
2196
+ listener.close()
2197
+ server.shutdown()
2198
+
2199
+ @pytest.mark.unit
2200
+ @pytest.mark.parametrize("resets", [3, 25])
2201
+ @pytest.mark.parametrize("size", [64 * 1024, 20 * 1024**2])
2202
+ def test_upload_and_download_survive_reset_connections_with_identical_bytes(self, flaky_s3, resets, size):
2203
+ # Given: 3 resets are absorbed by botocore's own retries, 25 outlast them and need the transfer to be repeated
2204
+ data = os.urandom(size)
2205
+ flaky_s3.state.resets_left = resets
2206
+
2207
+ # When
2208
+ with patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", return_value=flaky_s3.client), patch.object(dynamicio.mixins.with_s3.time, "sleep"):
2209
+ dynamicio.mixins.with_s3._upload_from_memory(io.BytesIO(data), "bucket", "dir/object.bin")
2210
+ flaky_s3.state.resets_left = resets
2211
+ downloaded = dynamicio.mixins.with_s3._download_to_memory("bucket", "dir/object.bin")
2212
+
2213
+ # Then
2214
+ assert flaky_s3.state.resets == 2 * resets
2215
+ assert downloaded.getvalue() == data
2216
+
2217
+
2218
+ class TestS3LargeDownloadWithBrokenBody:
2219
+ """Above 16 MiB the transfer manager downloads ranged parts, repeats each one 5 times and then raises RetriesExceededError."""
2220
+
2221
+ @pytest.fixture
2222
+ def breaking_s3(self, monkeypatch):
2223
+ """A minimal S3 endpoint for one object whose ranged GETs reset the connection halfway through the body while `cuts_left` > 0."""
2224
+ for name in ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"):
2225
+ monkeypatch.setenv(name, "testing")
2226
+ state = types.SimpleNamespace(data=os.urandom(20 * 1024**2), cuts_left=0, cuts=0, lock=threading.Lock())
2227
+
2228
+ class Handler(BaseHTTPRequestHandler):
2229
+ protocol_version = "HTTP/1.1"
2230
+
2231
+ def log_message(self, *_):
2232
+ pass
2233
+
2234
+ def _send(self, status, headers, body=b""):
2235
+ self.send_response(status)
2236
+ for name, value in headers.items():
2237
+ self.send_header(name, value)
2238
+ self.end_headers()
2239
+ self.wfile.write(body)
2240
+
2241
+ def do_HEAD(self): # pylint: disable=invalid-name
2242
+ self.send_response(200)
2243
+ self.send_header("Content-Length", str(len(state.data)))
2244
+ self.send_header("ETag", '"etag"')
2245
+ self.end_headers()
2246
+
2247
+ def do_GET(self): # pylint: disable=invalid-name
2248
+ start, end = 0, len(state.data) - 1
2249
+ if self.headers.get("Range"):
2250
+ first, last = self.headers["Range"].removeprefix("bytes=").split("-")
2251
+ start, end = int(first), min(int(last or end), end)
2252
+ body = state.data[start : end + 1]
2253
+ self.send_response(206 if self.headers.get("Range") else 200)
2254
+ self.send_header("Content-Length", str(len(body)))
2255
+ self.send_header("ETag", '"etag"')
2256
+ if self.headers.get("Range"):
2257
+ self.send_header("Content-Range", f"bytes {start}-{end}/{len(state.data)}")
2258
+ self.end_headers()
2259
+ with state.lock:
2260
+ cut = bool(self.headers.get("Range")) and state.cuts_left > 0
2261
+ if cut:
2262
+ state.cuts_left -= 1
2263
+ state.cuts += 1
2264
+ try:
2265
+ if cut:
2266
+ self.wfile.write(body[: len(body) // 2])
2267
+ self.wfile.flush()
2268
+ self.close_connection = True # the server closes the socket with the body short of its Content-Length
2269
+ else:
2270
+ self.wfile.write(body)
2271
+ except OSError:
2272
+ self.close_connection = True
2273
+
2274
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
2275
+ threading.Thread(target=server.serve_forever, daemon=True).start()
2276
+ client = boto3.client(
2277
+ "s3", endpoint_url=f"http://127.0.0.1:{server.server_port}", region_name="us-east-1", config=dynamicio.mixins.with_s3._CLIENT_CONFIG.merge(Config(read_timeout=10))
2278
+ )
2279
+ yield types.SimpleNamespace(client=client, state=state)
2280
+ server.shutdown()
2281
+ server.server_close()
2282
+
2283
+ @pytest.mark.unit
2284
+ def test_download_whose_body_breaks_is_repeated_after_the_transfer_manager_gives_up(self, breaking_s3):
2285
+ # Given: more cuts than one transfer-manager run can absorb (3 parts, 5 attempts each), fewer than the attempts of the whole transfer
2286
+ breaking_s3.state.cuts_left = 20
2287
+
2288
+ # When
2289
+ with (
2290
+ patch.object(dynamicio.mixins.with_s3, "_shared_s3_client", return_value=breaking_s3.client),
2291
+ patch.object(dynamicio.mixins.with_s3.time, "sleep"),
2292
+ patch("dynamicio.mixins.with_s3.logger") as logger,
2293
+ ):
2294
+ downloaded = dynamicio.mixins.with_s3._download_to_memory("bucket", "dir/object.bin")
2295
+
2296
+ # Then
2297
+ assert downloaded.getvalue() == breaking_s3.state.data
2298
+ assert any("RetriesExceededError" in call.args[0] for call in logger.warning.call_args_list)