xihaian251 opened a new pull request, #1045: URL: https://github.com/apache/burr/pull/1045
# Artifact Store aggregate, with an optional `action_scope` boundary for correct tracing > **Architecture decision pending: optional `action_scope` versus serial dispatch.** > This PR submits the contributor-preferred C-fixed candidate. It is a proposal for review, not a > maintainer-approved design. Base: `apache/burr:main` at `36e3ff3048c8cabd7aac6d5c373307934bf3c2df`. > Candidate commit/tree: `82075142910487efdd98de3b70b49efec436b2fd` / > `424eb59a5225a96ef386961224792ed768000805` (51 files, +11,744/−256). > A serial-dispatch alternative with the same feature set is available as > `d79d46cfa54d57761725c9502342a94160b6c9f4` / `34979b53e1c910073dd2f0d3bcc759cb2a1fddc1` > (50 files, +11,192/−234). This Draft PR is for architecture review and does **not** request > immediate merge. ## Summary This is the single aggregate PR requested in [#931](https://github.com/apache/burr/pull/931#issuecomment-6712854639): all Artifact Store work, the follow-ups from the review threads, and the correctness hardening accumulated since the original PR, on top of current `main` (which already contains #1027). It contains one feature (externalising large state values into an object store), one optional lifecycle capability intended to make OpenTelemetry tracing correct without changing hook dispatch, and seven groups of correctness fixes. It deliberately does **not** include unrelated fixes from #1033, #1000, #1026 or #1019. D-1 has been discussed in [#931](https://github.com/apache/burr/pull/931#issuecomment-6906624749), but no maintainer has chosen between the two candidates; the question remains pending. ## Relationship to #931 The original PR by **@vignesh-manel** (`06d02aec`) introduced `ArtifactRef`, the sync/async `ArtifactStore` contracts, local and S3 backends, `with_object_store()`, type/field-based store-aware serde, and state/persister/tracker propagation. That work is preserved and credited with `Co-authored-by: Vignesh Nayak Manel <[email protected]>` on the aggregate commit. Added on top: - **Resume correctness**: `Application.__init__` and resume load share one `SerializationContext`; a per-application memo survives resume. - **Serde backwards compatibility**: legacy serializers that do not accept `serialization_context` keep working; payload bytes are pinned by a gold file captured from `main`. - **Async tracking**: `AsyncLocalTrackingClient` awaits async serde, preserves the log schema, avoids double-firing sync/async hooks, and handles cancellation/error status. - **Artifact Store correctness**: atomic create-if-absent publication, conflict verification for explicit and content-addressed keys, symlink/root containment, real I/O error propagation, S3 conditional puts with 412/409 handling, S3 client pickle policy, async client lifecycle. - **Lifecycle hardening**: every hook in a group runs before the first error is re-raised; a failing synchronous hook no longer starves the asynchronous phase; a pending cancellation does not start a new hook. - All 14 review threads on #931 were mapped to code/tests: 13 `FIXED_AND_TESTED`, 1 `FIXED_NOT_FULLY_TESTED` because the Ray runtime could not start in this environment. ## Why `action_scope` (D-1, pending decision) `asyncio.gather` wraps each coroutine in a `Task`, and a Task starts with a **copy** of the current `contextvars.Context`. A `pre` hook that attaches an OpenTelemetry span therefore cannot make that span current in the task that runs the action. The measured consequence on `main` is that the step span ends before the action starts, and a child span started in the action lands in the wrong trace. The candidate adds an optional adapter hook `action_scope(**kwargs)`. `Application._astep` enters it in the task that runs the action, after `pre_run_step` and before `post_run_step`; scopes are exited in reverse order via `ExitStack`. Adapters that do not implement it are skipped, so hook scheduling, Task identity, ContextVar isolation and cancellation semantics remain unchanged. Streaming actions do not pass through `_astep`; their span is owned by synchronous `pre_start_stream` / `post_end_stream` hooks. Four streaming cases were checked (full consumption, early `break`, anyio cancel scope, `task.cancel()`), each producing one span with correct status and no context-detach error. Serial dispatch is available as an alternative, but it changes observable hook concurrency, Task identity, ContextVar visibility and `Task.cancelling()` semantics. Conditional/hybrid dispatch, explicit `Context` sharing, and synchronous-hook span ownership were evaluated and rejected as unstable or version-dependent. **No maintainer has yet accepted either design.** ## Compatibility `action_scope` is opt-in and existing adapters are unaffected. Two behaviour changes apply to both candidates and require explicit maintainer attention: - A hook group now runs every hook before re-raising the first error. - **`S3TrackingClient` now forwards `serde_kwargs` when serializing state.** On `main` it does not. This is a real behaviour change relative to `main`, not a documentation clarification. Streaming late hooks receive `exception=` so span status is accurate; all hook signatures already accept `**future_kwargs`. Packaging adds an `s3` extra (`boto3`, `aiobotocore`, `botocore>=1.35.2`) to the `tests` and `documentation` extras, increasing CI install size. The serial variant changes only `burr/lifecycle/internal.py` for dispatch, but changes the four observable hook behaviours listed above and roughly doubles hook latency when hooks perform I/O. ## Artifact Store correctness guarantees - A successful `ArtifactRef` always resolves to bytes matching its SHA-256 digest. - Publication uses a temp file, fsync and a no-replace primitive; POSIX uses `os.link()` where available, Windows uses non-replacing `os.rename()`, and unsupported POSIX filesystems refuse publication rather than overwrite a concurrent winner. - Real `ENOSPC`/`EIO`/`EROFS`/… errors propagate and are not mistaken for "no hard-link support". - Existing keys are verified: identical bytes are a no-op, different bytes raise `ValueError`, for both explicit and content-addressed keys. - `os.path.realpath()` containment is used for `put`/`get`/`exists`, including symlinked parents. - S3 uses `PutObject(IfNoneMatch="*")`; 412 means "already exists", 409 is retried with backoff, and the winner's content is verified. **Caveat**: S3 is exercised with Stubber / AsyncMock, not against real AWS. IAM docs were corrected (`HeadObject` is authorised by `s3:GetObject`; `s3:ListBucket` is bucket-level), but no real AWS or alternative provider was validated. ## Reviewer map — seven units | Unit | Key files | Invariant / entry point | |---|---|---| | 1. Artifact Store contract and backends | `burr/core/artifacts.py`, `burr/integrations/artifacts/s3.py` | Ref-to-bytes SHA-256 integrity and sync/async contracts; `tests/core/test_artifacts.py`, `tests/integrations/artifacts/test_s3.py`. | | 2. Type/Field Serde | `burr/core/serde.py`, `burr/core/state.py` | Legacy serializers keep working and payload bytes are unchanged; `tests/core/test_serde_context_compat.py`, gold-file payload test. | | 3. Persistence and Resume Memo | `burr/core/application.py`, `burr/integrations/persisters/*` | One shared `SerializationContext` across resume; memo survives resume; `tests/core/test_serialization_context.py`. | | 4. Async Tracking | `burr/tracking/client.py`, `burr/tracking/s3client.py`, `burr/tracking/base.py` | Async serde awaited, hooks not double-fired, accurate status; `tests/tracking/test_async_*.py`. | | 5. Lifecycle / OTel | `burr/lifecycle/internal.py`, `burr/core/application.py`, `burr/integrations/opentelemetry.py` | Optional `action_scope` preserves gather/Task/ContextVar/cancellation semantics; `tests/tracking/test_action_scope.py`, `test_lifecycle_scheduling.py`, `test_otel_cancellation_and_failure.py`. | | 6. Safety / Atomic Publication | `burr/core/artifacts.py`, `burr/integrations/artifacts/s3.py` | No partial/overwritten artifact, path containment, real I/O errors propagate; atomic write, conflict, symlink/junction and fresh-process pickle tests. | | 7. Tests, Documentation and Packaging | `docs/**`, `examples/artifact-storage/**`, `pyproject.toml`, all new tests | Runnable example, accurate docs, explicit `s3` extra; full suite command above and example application. | ## Review thread mapping | Thread(s) | Area | Primary test entry | |---|---|---| | `pOT` | fresh-process `ArtifactRef` deserialization | `test_artifact_ref_deserializes_in_fresh_process_without_explicit_import` | | `pO9`, `aHZ` | digest verification / explicit vs hash key conflict | `test_put_artifact_explicit_key_conflicting_content_raises`, artifact invariant probe | | `pPk` | symlink/root containment | `test_{put,get,exists}_rejects_symlinked_escape`, NTFS junction probe | | `pQH`, `Nu4F` | atomic publication / concurrent create-if-absent | atomic write test, 32-thread + 8-process probe | | `pQv`, `AeCm` | `ApplicationContext` compatibility / execution-time validation | `tests/core/test_application.py` context and validation tests | | `BzAT`, `AeFk` | async store/S3 client lifecycle | `tests/integrations/artifacts/test_s3.py`, aclose idempotence test | | `Nu5E` | IAM documentation | `docs/reference/integrations/s3.rst` | | `aHV` | S3 pickle/Ray boundary | `test_store_pickles_and_rebuilds_its_client`, fresh-process pickle probe | | `aHb`, `aHg` | documentation of build/abuild and explicit-key immutability | documentation diff | `aHV` remains `FIXED_NOT_FULLY_TESTED`: the pickle boundary is verified in a fresh process, but the real Ray runtime could not start. No GitHub thread was marked resolved by this submission. ## Tests and evidence The frozen tree was rebuilt from clean `main`; `git write-tree` reproduced the candidate tree and `git diff --check` passed. Full suite results (4 optional-dependency modules excluded): | Tree | Result | New failures | |---|---:|---:| | `main` | 787 passed, 6 failed, 4 skipped | — | | Serial candidate | 1065 passed, 6 failed, 16 skipped | 0 | | **C-fixed candidate** | **1074 passed, 6 failed, 16 skipped** | **0** | | C-fixed + #1033 | 1104 passed, 6 failed, 16 skipped | 0 | The six failures are identical on `main` and all candidates: four Graphviz tests (no `dot` binary), an sdist artifact-license test, and `test_end_to_end::test_echo_bot`. Mutation testing: 8/8 targeted mutants killed on both candidates. black, isort and flake8 show no new findings. Python 3.10.22 / 3.11.18 / 3.12.14 / 3.13.1: D-1 probes, `tests/core` (632 passed / 4 baseline failures / 12 skipped) and `tests/tracking` (Serial 106, C-fixed 115 passed) were run on all four versions. The **full repository suite was run only on 3.13**. Do not read the cross-version matrix as full-suite coverage. ## Known limitations - No real AWS S3 / IAM / alternative provider validation. - Ray 2.60.0 is installed, but `ray.init()` times out waiting for its GCS server on this Windows host; the Ray `MapStates` runtime path is `NOT_RUN`. The pickle/client-rebuild boundary is verified separately in a fresh process. - POSIX filesystems without hard-link support, real POSIX symlinks, and a real Linux/POSIX host were not validated; a real NTFS junction was used for containment checks. - `asyncpg`, `haystack`, `aiofiles` and Graphviz `dot` were unavailable or excluded where noted. - Hosted CI has not been triggered for this contribution. - `action_scope` needs a maintainer design decision. - #1033 remains open. If it merges first, `astream_result`'s container callback needs the documented six-line conflict resolution. ## Attribution and AI disclosure This PR builds on **@vignesh-manel**'s original #931, the user's F4 follow-up (`vignesh-manel/burr#1`), and later contributions. The original author is credited explicitly. Some intermediate local commits used placeholder or unverified identities; the single aggregate commit uses `xihaian251 <[email protected]>` and preserves Vignesh with `Co-authored-by`. The identity behind `grape7 <[email protected]>` remains **unconfirmed**; no attribution claim is made from the email/account alone. Squash/merge and author mapping are left to maintainers. Analysis, deterministic experiments, patch preparation, regression runs and drafting of this description were assisted by **WorkBuddy AI (Tencent Hunyuan Hy)**. This is a voluntary disclosure; no repository-specific AI-disclosure rule is asserted. Whether to add a `Generated-by:` trailer is left to maintainers. A D-1 architecture question has already been posted on #931. This Draft PR is the resulting proposal; it does not resolve any original review thread and does not claim hosted CI results. -- 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]
