sangkyoonnam commented on code in PR #931: URL: https://github.com/apache/burr/pull/931#discussion_r4235327411
########## burr/integrations/artifacts/s3.py: ########## @@ -0,0 +1,226 @@ +# 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. + +"""An :py:class:`~burr.core.artifacts.ArtifactStore` backed by AWS S3. + +Requires the ``boto3`` package -- install with ``pip install "apache-burr[s3]"``. + +Also provides :py:class:`AsyncS3ArtifactStore`, a non-blocking counterpart backed by +``aiobotocore`` (installed alongside ``boto3`` via the same ``s3`` extra) for use from async +actions -- ``S3ArtifactStore`` performs blocking network I/O and should not be called from async +actions, since it would block the event loop for the duration of each upload/download. +""" + +from typing import Any, Optional + +from burr.core.artifacts import ArtifactStore, AsyncArtifactStore +from burr.integrations import base + +try: + import boto3 + import botocore.exceptions +except ImportError as e: + base.require_plugin(e, "s3") + +try: + import aiobotocore.session +except ImportError as e: + base.require_plugin(e, "s3") + + +class S3ArtifactStore(ArtifactStore): + """Stores artifacts as objects in an S3 bucket, optionally under a key prefix.""" + + @classmethod + def from_config(cls, config: dict) -> "S3ArtifactStore": + """Creates a new instance from a configuration dictionary. See :py:meth:`from_values` + for the accepted keys.""" + return cls.from_values(**config) + + @classmethod + def from_values( + cls, + bucket: str, + prefix: str = "", + client_kwargs: Optional[dict] = None, + ) -> "S3ArtifactStore": + """Creates a new instance, constructing its own boto3 S3 client. + + :param bucket: Name of the S3 bucket to store artifacts in. + :param prefix: Optional key prefix (e.g. ``"my-app/artifacts"``) applied to every key. + :param client_kwargs: Optional kwargs passed to ``boto3.client("s3", ...)``. + """ + client = boto3.client("s3", **(client_kwargs or {})) + return cls(bucket, prefix=prefix, client=client) + + def __init__(self, bucket: str, prefix: str = "", client: Optional[Any] = None): + """Constructor. + + :param bucket: Name of the S3 bucket to store artifacts in. + :param prefix: Optional key prefix (e.g. ``"my-app/artifacts"``) applied to every key. + :param client: An existing boto3 S3 client. If not provided, one is created with + default credentials/region resolution (``boto3.client("s3")``). + """ + self.bucket = bucket + self.prefix = prefix + self.client = client if client is not None else boto3.client("s3") Review Comment: This client is what breaks `RayExecutor` (repro in the summary). A `__getstate__` that drops `client` and a `__setstate__` that rebuilds it fixes the Ray case; I checked that with a subclass that keeps `client_kwargs` and rebuilds from them. `from_values` could keep its construction kwargs for that. For an injected client, I'd fail clearly on pickle unless reconstruction options are supplied, since silently rebuilding with defaults can change its credentials or config. A test next to `test_ray_executor_end_to_end_persistence` in `tests/integrations/test_burr_ray.py` would keep this from regressing. ########## 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() + if existing_digest != digest: + raise ValueError( + f"Key '{resolved_key}' already exists with different content (existing " + f"digest {existing_digest}, new digest {digest}). Use a different explicit " + f"key, or omit `key` to use content-addressed storage." + ) + # Identical content is already stored under this key -- nothing to do. + else: + self.put(data, resolved_key) Review Comment: Explicit and default keys share a namespace, and only the explicit-key branch compares content. Writing `b"wrong"` under `hashlib.sha256(b"expected").hexdigest()` and then calling `put_artifact(b"expected")` returns a ref that fails `get_artifact` with a digest mismatch; I ran this against `LocalFileSystemArtifactStore`. The async path at 230-242 is the same. Not likely in practice, but it's sequential, so it isn't covered by leaving concurrent writers to the caller. Could occupied default keys be verified before returning a ref? ########## burr/core/application.py: ########## @@ -2544,6 +2565,46 @@ def with_state_persister( self.state_persister = persister # tracks for later; validates in build / abuild return self + def with_object_store( + self, object_store: Union[ArtifactStore, AsyncArtifactStore] + ) -> "ApplicationBuilder[StateType]": + """Adds an object/blob store to the application, for storing large values (files, + dataframes, images, etc...) outside of ``State`` -- see :py:mod:`burr.core.artifacts`. + + Unlike :py:meth:`with_state_persister`, this does not add a lifecycle hook -- Burr never + reads from or writes to the store on its own. It is purely made available to actions + through :py:class:`ApplicationContext` (``__context.object_store``) so they don't each + need to construct/import their own store, and so it can be swapped (e.g. local disk in + dev, S3 in prod) in one place. + + .. code-block:: python + + from burr.core import action, State, ApplicationContext + from burr.core.artifacts import ArtifactStore + + @action(reads=[], writes=["pdf_doc"]) + def ingest_pdf(state: State, pdf_bytes: bytes, __context: ApplicationContext) -> State: + ref = __context.object_store.put_artifact(pdf_bytes, media_type="application/pdf") + return state.update(pdf_doc=ref) + + app = ( + ApplicationBuilder() + .with_actions(ingest_pdf, ...) + .with_object_store(LocalFileSystemArtifactStore(root_dir="./blobs")) + .build() + ) + + An :py:class:`AsyncArtifactStore` (e.g. an ``aiobotocore``-backed S3 store) may be passed + too, for use from async actions without blocking the event loop -- build the application + with :py:meth:`abuild` in that case, since :py:meth:`build` rejects an async store (it + can't be awaited from a sync action). Review Comment: This still says `build()` rejects an async store. After the last round, `build()` accepts it and the check runs in `validate_correct_async_use()` (line 2198), as the `build()` docstring at 2877 and `artifact-storage.rst` now say. ########## docs/concepts/artifact-storage.rst: ########## @@ -0,0 +1,263 @@ +.. + 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. + + +================ +Artifact Storage +================ + +.. _artifact-storage: + +.. note:: + + Burr comes with an optional object/blob storage abstraction for large values (files, + images, dataframes, model weights, etc...) that you don't want to embed directly in + :py:class:`State <burr.core.state.State>`. This is separate from :doc:`state-persistence` -- + it's for the *values* your actions produce/consume, not the state machine's bookkeeping. + +TL;DR +----- + +:py:class:`State <burr.core.state.State>` is fully re-serialized to your persister/tracker +after every action. If you put a large binary blob (a PDF, an image, a big dataframe) directly +in state, that entire blob gets re-written on every subsequent step, even if it never changes. + +Burr's artifact storage API solves this by giving you a place to write the blob once +(an :py:class:`ArtifactStore <burr.core.artifacts.ArtifactStore>`), and a small, +content-addressed handle to keep in state instead (an +:py:class:`ArtifactRef <burr.core.artifacts.ArtifactRef>`). The ref serializes/deserializes like +any other state value, but loading it back does **not** eagerly fetch the underlying bytes -- +you explicitly call :py:meth:`ArtifactRef.read <burr.core.artifacts.ArtifactRef.read>` (or its +async counterpart, :py:meth:`ArtifactRef.aread <burr.core.artifacts.ArtifactRef.aread>`, for an +``AsyncArtifactStore``) when you actually need them. + +This is an opt-in, explicit mechanism. Burr never reads from or writes to an artifact store on +its own -- your actions are always the ones calling ``put_artifact``/``get_artifact``. + +Why not just put the bytes in State? +------------------------------------- + +Consider an action that ingests an uploaded PDF and a later action that summarizes it: + +.. code-block:: python + + @action(reads=[], writes=["pdf_bytes"]) + def ingest_pdf(state: State, pdf_bytes: bytes) -> State: + return state.update(pdf_bytes=pdf_bytes) # the whole PDF is now in State + + @action(reads=["pdf_bytes"], writes=["summary"]) + def summarize(state: State) -> State: + summary = call_llm(state["pdf_bytes"]) + return state.update(summary=summary) + +Every time ``State`` is persisted or tracked after this point (including for actions that have +nothing to do with the PDF), the full PDF bytes are re-serialized along with everything else. +This gets expensive quickly, and it also means large binary data ends up embedded in your +persistence layer and shown as raw JSON in the tracking UI. + +Storing an artifact reference instead +-------------------------------------- + +Use an :py:class:`ArtifactStore <burr.core.artifacts.ArtifactStore>` to store the blob once, and +keep only the small :py:class:`ArtifactRef <burr.core.artifacts.ArtifactRef>` -- a key, size, +SHA-256 digest, and optional media type -- in state: + +.. code-block:: python + + from burr.core import action, State, ApplicationContext + from burr.core.artifacts import ArtifactStore + + @action(reads=[], writes=["pdf_doc"]) + def ingest_pdf(state: State, pdf_bytes: bytes, __context: ApplicationContext) -> State: + store: ArtifactStore = __context.object_store + ref = store.put_artifact(pdf_bytes, media_type="application/pdf") + return state.update(pdf_doc=ref) # only the small ref is in State now + + @action(reads=["pdf_doc"], writes=["summary"]) + def summarize(state: State, __context: ApplicationContext) -> State: + store: ArtifactStore = __context.object_store + pdf_bytes = state["pdf_doc"].read(store) # explicit, lazy fetch + summary = call_llm(pdf_bytes) + return state.update(summary=summary) + +``put_artifact`` computes a SHA-256 digest of the data and, unless you pass an explicit ``key``, +uses that digest as the storage key. This makes writes idempotent and content-addressed -- +storing the same bytes twice (even across app runs) is a no-op, so you get de-duplication for +free without any bookkeeping of your own. + +``get_artifact`` (and ``ArtifactRef.read``) re-computes the digest of whatever comes back from +the store and compares it to ``ref.digest`` by default, raising a ``ValueError`` if they don't +match -- this catches corrupted or overwritten data early rather than silently returning bad +bytes. + +If you pass an explicit ``key`` (rather than relying on content-addressing), reusing that key is +only safe if the content is the same: if the key already exists with *different* content, +``put_artifact`` raises a ``ValueError`` instead of silently overwriting or returning a ref that +doesn't match what's actually stored. Stick to content-addressed (default) keys unless you have a +specific reason to name your own -- e.g. a stable "latest" pointer you intend to update +out-of-band. Review Comment: Suggest adding something like: "For sequential `put_artifact` calls, reusing an explicit key requires identical bytes. If an action retries or resumes after writing an artifact, different bytes under the same key raise `ValueError`. Use default content-addressed keys for nondeterministic output." ########## 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: AWS S3 supports this through [`PutObject(IfNoneMatch="*")`](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html). An existing key returns 412 `PreconditionFailed`, and a concurrent conditional write can get 409 `ConditionalRequestConflict`, which needs a retry. Since the digest comparison in `put_artifact` runs before the write, a 412 handler would have to fetch the existing object and compare digests before returning a ref. I haven't run this against real S3 or an S3-compatible store, so other providers would still need checking. -- 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]
