Copilot commented on code in PR #931:
URL: https://github.com/apache/burr/pull/931#discussion_r4215209382


##########
burr/core/artifacts.py:
##########
@@ -0,0 +1,349 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Blob/object storage abstraction for large values held in 
:py:class:`burr.core.state.State`.
+
+Rather than embedding large binary payloads (files, dataframes, images, 
etc...) directly in
+state -- which gets fully re-serialized to the persistence layer after every 
action -- store the
+payload in an :py:class:`ArtifactStore` and keep a small, content-addressed 
:py:class:`ArtifactRef`
+in state instead. Deserializing a ref does *not* eagerly fetch the underlying 
bytes -- callers
+must explicitly call :py:meth:`ArtifactRef.read` (or ``store.get_artifact``) 
to do so.
+
+See :doc:`../reference/serde` and :doc:`../concepts/state-persistence` for 
background on how
+state serialization interacts with this module.
+"""
+
+import abc
+import hashlib
+import os
+import tempfile
+from dataclasses import dataclass
+from typing import Optional
+
+from burr.core import serde
+
+
+@dataclass(frozen=True)
+class ArtifactRef:
+    """A lightweight, content-addressed reference to a blob stored in an 
:py:class:`ArtifactStore`.
+
+    This is what you should store in :py:class:`burr.core.state.State` -- 
*not* the raw bytes/object.
+    It is registered with :py:mod:`burr.core.serde` so it 
serializes/deserializes automatically as
+    part of normal state (de)serialization; deserializing only recreates this 
reference, it never
+    re-fetches the underlying bytes on its own.
+
+    :param key: The store-specific key/path the blob is stored under.
+    :param size_bytes: Size of the blob, in bytes.
+    :param digest: SHA-256 hex digest of the blob's contents, used to verify 
integrity on read
+        and to detect duplicate content.
+    :param media_type: Optional MIME type (e.g. ``"application/pdf"``) for the 
caller's own use.
+    """
+
+    key: str
+    size_bytes: int
+    digest: str
+    media_type: Optional[str] = None
+
+    def read(self, store: "ArtifactStore", verify: bool = True) -> bytes:
+        """Lazily fetches the underlying bytes for this reference from 
``store``.
+
+        :param store: The store this artifact was originally written to.
+        :param verify: Whether to verify the fetched bytes match 
``self.digest``. Defaults to True.
+        :return: The raw bytes of the artifact.
+        """
+        return store.get_artifact(self, verify=verify)
+
+    async def aread(self, store: "AsyncArtifactStore", verify: bool = True) -> 
bytes:
+        """Asynchronous counterpart to :py:meth:`read`, for use with an
+        :py:class:`AsyncArtifactStore` (e.g. from an async action).
+
+        :param store: The async store this artifact was originally written to.
+        :param verify: Whether to verify the fetched bytes match 
``self.digest``. Defaults to True.
+        :return: The raw bytes of the artifact.
+        """
+        return await store.get_artifact(self, verify=verify)
+
+
+class ArtifactStore(abc.ABC):
+    """Base class for blob/object storage backends.
+
+    Implement :py:meth:`put`, :py:meth:`get`, and :py:meth:`exists` for a new 
backend --
+    :py:meth:`put_artifact` and :py:meth:`get_artifact` are provided for free 
on top of those,
+    so digest computation/verification is not duplicated across backends.
+    """
+
+    @abc.abstractmethod
+    def put(self, data: bytes, key: str) -> None:
+        """Stores ``data`` under ``key``. Should be idempotent -- writing the 
same key twice
+        with the same content should not error.
+
+        :param data: The raw bytes to store.
+        :param key: The key/path to store the data under.
+        """
+
+    @abc.abstractmethod
+    def get(self, key: str) -> bytes:
+        """Retrieves the raw bytes stored under ``key``.
+
+        :param key: The key/path to load.
+        :raises FileNotFoundError: If no data is stored under ``key``.
+        """
+
+    @abc.abstractmethod
+    def exists(self, key: str) -> bool:
+        """Returns whether ``key`` is present in the store."""
+
+    def is_async(self) -> bool:
+        """Whether this store's I/O methods are async. Always False here -- see
+        :py:class:`AsyncArtifactStore` for the async contract. Mirrors
+        :py:meth:`burr.core.persistence.BaseStateSaver.is_async`."""
+        return False
+
+    def put_artifact(
+        self, data: bytes, media_type: Optional[str] = None, key: 
Optional[str] = None
+    ) -> ArtifactRef:
+        """Computes the digest/size for ``data``, writes it to the store, and 
returns a
+        fully-formed :py:class:`ArtifactRef`. This is the recommended way to 
write artifacts --
+        it ensures every backend computes/verifies digests the same way.
+
+        With the default content-addressed ``key`` (the hex digest), writing 
identical content
+        twice is always a safe no-op -- the key can only match if the bytes 
match.
+
+        With an explicit ``key``, a write is only skipped if the *existing* 
content stored under
+        that key has the same digest as ``data``. If the key already exists 
with *different*
+        content, this raises -- it never silently returns a ref that doesn't 
describe what's
+        actually stored.
+
+        :param data: The raw bytes to store.
+        :param media_type: Optional MIME type to record on the returned ref.
+        :param key: Optional explicit key to store under. If not provided, a 
content-addressed
+            key (the hex digest) is used -- so writing identical content twice 
is a no-op.
+        :raises ValueError: If ``key`` is explicitly provided and already 
exists with content
+            that does not match the digest of ``data``.
+        :return: An :py:class:`ArtifactRef` describing the stored artifact.
+        """
+        digest = hashlib.sha256(data).hexdigest()
+        resolved_key = key if key is not None else digest
+        if key is not None and self.exists(resolved_key):
+            existing_digest = 
hashlib.sha256(self.get(resolved_key)).hexdigest()

Review Comment:
   The explicit-key check is not atomic with the write, in either the sync or 
async helper. Concurrent calls with different bytes under the same absent key 
can both succeed: the local backend uses `os.replace`, and both S3 backends use 
unconditional `put_object`, so one returned reference fails digest 
verification. If another writer finishes before the backend's existence check, 
its silent early return can also produce an incorrect reference. Use atomic 
create-if-absent publication in each backend and verify the winning content on 
existing-key/conflict paths, raising `ValueError` for different bytes. Cover 
these interleavings with sync and async regression tests.



##########
docs/reference/integrations/s3.rst:
##########
@@ -0,0 +1,133 @@
+..
+   Licensed to the Apache Software Foundation (ASF) under one
+   or more contributor license agreements.  See the NOTICE file
+   distributed with this work for additional information
+   regarding copyright ownership.  The ASF licenses this file
+   to you under the Apache License, Version 2.0 (the
+   "License"); you may not use this file except in compliance
+   with the License.  You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing,
+   software distributed under the License is distributed on an
+   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+   KIND, either express or implied.  See the License for the
+   specific language governing permissions and limitations
+   under the License.
+
+
+.. _s3-artifacts-integration:
+
+===================
+S3 Artifact Storage
+===================
+
+An :py:class:`ArtifactStore <burr.core.artifacts.ArtifactStore>` backed by an
+`AWS S3 <https://aws.amazon.com/s3/>`_ bucket. See 
:doc:`../../concepts/artifact-storage` for
+background on artifact storage in general.
+
+Install the optional extra (pulls ``boto3`` and ``aiobotocore``):
+
+.. code-block:: bash
+
+   pip install "apache-burr[s3]"
+
+-------------
+Quick Example
+-------------
+
+.. code-block:: python
+
+    from burr.core import ApplicationBuilder
+    from burr.integrations.artifacts.s3 import S3ArtifactStore
+
+    object_store = S3ArtifactStore.from_values(
+        bucket="my-bucket",
+        prefix="burr-artifacts",  # optional
+    )
+
+    app = (
+        ApplicationBuilder()
+        .with_actions(...)
+        .with_transitions(...)
+        .with_state(...)
+        .with_entrypoint(...)
+        .with_object_store(object_store)
+        .build()
+    )
+
+If you already have a boto3 client (e.g. reusing a connection, custom endpoint 
for testing with
+`moto <https://github.com/getmoto/moto>`_ or a local S3-compatible server), 
construct the store
+directly and pass it in:
+
+.. code-block:: python
+
+    import boto3
+    from burr.integrations.artifacts.s3 import S3ArtifactStore
+
+    client = boto3.client("s3", region_name="us-east-1")
+    object_store = S3ArtifactStore(bucket="my-bucket", 
prefix="burr-artifacts", client=client)
+
+--------------------------
+Async (non-blocking) Usage
+--------------------------
+
+``S3ArtifactStore`` performs blocking network I/O through ``boto3`` -- calling 
it from an async
+action blocks the event loop for the duration of each upload/download. For 
async applications
+(built with :py:meth:`abuild 
<burr.core.application.ApplicationBuilder.abuild>`), use
+:py:class:`AsyncS3ArtifactStore 
<burr.integrations.artifacts.s3.AsyncS3ArtifactStore>` instead,
+which is backed by `aiobotocore <https://github.com/aio-libs/aiobotocore>`_:
+
+.. code-block:: python
+
+    from burr.core import ApplicationBuilder
+    from burr.integrations.artifacts.s3 import AsyncS3ArtifactStore
+
+    async with await AsyncS3ArtifactStore.acreate(
+        bucket="my-bucket",
+        prefix="burr-artifacts",  # optional
+    ) as object_store:
+        app = await (
+            ApplicationBuilder()
+            .with_actions(...)
+            .with_transitions(...)
+            .with_state(...)
+            .with_entrypoint(...)
+            .with_object_store(object_store)
+            .abuild()
+        )
+        await app.arun(...)
+    # the underlying aiobotocore client is closed automatically here, even on 
exception.
+
+``acreate`` opens and owns its underlying ``aiobotocore`` client. Using 
``async with`` (shown
+above) is the recommended way to release it, since it closes the client safely 
even on
+exceptions and early returns. You can also call ``await 
object_store.aclose()`` directly
+(e.g. on app shutdown) -- it's idempotent, so calling it more than once is 
safe. If you already
+have an open ``aiobotocore`` client, pass it directly via the constructor's 
``client`` argument
+instead.
+
+---------------
+IAM Permissions
+---------------
+
+At minimum, the runtime identity used by Burr needs permission to 
read/write/check objects in
+the target bucket (optionally scoped to the configured prefix):
+
+* ``s3:PutObject``
+* ``s3:GetObject``
+* ``s3:HeadObject``

Review Comment:
   `s3:HeadObject` is not an IAM action; `HeadObject` uses `s3:GetObject`. The 
current backend also needs bucket-level `s3:ListBucket` permission for 
missing-key checks to return 404 rather than 403. Otherwise `exists()` 
propagates the error and prevents uploading a new artifact. Replace the invalid 
action and distinguish object-prefix permissions from the bucket permission.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to