Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

fix(amazon_s3): read() returns empty bytes for size=0 instead of the whole object (#2805)

Yan-Wei, Shie6af45945b4f6
diff --git a/python/cocoindex/connectors/amazon_s3/_source.py b/python/cocoindex/connectors/amazon_s3/_source.py
index 181dc38a..296dfd7f 100644
--- a/python/cocoindex/connectors/amazon_s3/_source.py
+++ b/python/cocoindex/connectors/amazon_s3/_source.py
@@ -250,6 +250,9 @@ async def read(client: AioBaseClient, uri: str, size: int = -1) -> bytes:
The object content as bytes.
"""
bucket_name, key = _parse_s3_uri(uri)
+ if size == 0:
+ return b""
+
if size >= 0:
response = await client.get_object(
Bucket=bucket_name, Key=key, Range=f"bytes=0-{size - 1}"
diff --git a/python/tests/connectors/test_amazon_s3.py b/python/tests/connectors/test_amazon_s3.py
index 0e67e1dc..b99497f2 100644
--- a/python/tests/connectors/test_amazon_s3.py
+++ b/python/tests/connectors/test_amazon_s3.py
@@ -231,6 +231,26 @@ class TestS3File:
assert await f.read(2) == b""
assert await f.read() == b""
+ async def test_read_helper_partial_reads(self, s3_client: tuple[Any, str]) -> None:
+ """The standalone ``read()`` helper honors ``size``, including 0."""
+ client, bucket_name = s3_client
+ uri = f"s3://{bucket_name}/file1.txt"
+
+ assert await amazon_s3.read(client, uri, size=0) == b""
+ assert await amazon_s3.read(client, uri, size=2) == b"he"
+ assert await amazon_s3.read(client, uri) == b"hello"
+
+ async def test_read_helper_empty_object(self, s3_client: tuple[Any, str]) -> None:
+ """The standalone ``read()`` helper returns b"" for an empty object."""
+ client, bucket_name = s3_client
+ boto3.client("s3", region_name="us-east-1").put_object(
+ Bucket=bucket_name, Key="empty.bin", Body=b""
+ )
+ uri = f"s3://{bucket_name}/empty.bin"
+
+ assert await amazon_s3.read(client, uri, size=0) == b""
+ assert await amazon_s3.read(client, uri) == b""
+
async def test_read_text(self, s3_client: tuple[Any, str]) -> None:
"""await read_text() returns file content as text."""
client, bucket_name = s3_client