Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
feature/Runner-blob-store-follow-ups · L-261016-359aa1 (#1441)
Louis Choquel18622c189ad2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3785dfd44..a22cde1e6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,20 @@# Changelog+## [Unreleased]++### Added++- **`crate_fingerprint` on the run answers**: the API server's `POST /v1/start` acknowledgement and `POST /v1/execute` result, `PipelexRunResultStart` and `PipelexRunResultExecute`, carry the fingerprint of the library crate the run's method was loaded into, so a host records it on its run beside the digest of the method tree that ran; it is `null` for a run built from no crate.+- **`StorageProviderAbstract.store_if_absent`**: a storage provider creates an object only when its key holds none and answers whether it did, never replacing an object already there, and checks the bytes against `checksum_sha256_hex` before writing, raising the new `StorageChecksumMismatchError` on a mismatch. S3 makes the condition with `If-None-Match: *`, sends the SHA-256 as `x-amz-checksum-sha256` for S3 to check, and retries a `409 ConditionalRequestConflict` a bounded number of times, GCS uploads on generation 0, and the local provider hard-links a temporary file to the key; a provider that does not override `_store_if_absent`, such as an external storage plugin, looks the key up and then stores.++### Changed++- **The API server's blob store writes create-only (Breaking)**: every blob and tree listing the server writes is created only when its key is free, with its SHA-256 as its checksum, so a bucket refusing unconditional writes under `blobs/` and `trees/` refuses none of them. A blob held at another size than the bytes uploaded under its hash is no longer written over: the upload is a `500` `BlobStoreCorrupted` that leaves the object for the deployment's operator to remove, and the local storage's folder must sit on a filesystem that supports hard links.++### Fixed++- **`POST /v1/validate` without a `read_scope` stores nothing**: a validation of a `files` map records its tree in the blob store only under the `read_scope` its request carries, where it used to record the tree's blobs and listing under the caller's own id, a prefix no host lists or erases; hash entries still resolve in the caller's own scope.+## [v0.87.0] - 2026-10-16### Highlightsdiff --git a/api/pipelex_api/blob_store.py b/api/pipelex_api/blob_store.pyindex 2267fd67c..13b98f6e5 100644--- a/api/pipelex_api/blob_store.py+++ b/api/pipelex_api/blob_store.py@@ -17,18 +17,27 @@ full, and never by an upload: `PUT /v1/blobs/{sha256}` writes under `blobs/` alobe a well-formed listing proves nothing. A listing present means the whole tree is present, which lets`POST /v1/blobs/missing` answer a tree's digest with one lookup.+Every write is create-only and checksummed, as the hosted platform writes the same keys: a blob or a listing is created+only when its key holds nothing (`If-None-Match: *` on S3, generation 0 on GCS, a hard link on the local filesystem),+so nothing written there is ever replaced, and with its SHA-256 as its checksum, which S3 checks against the body it+receives. A key already holding an object is the object already held, never an error. The checksum of a blob is its+hash, and that of a listing the hexadecimal part of its tree's digest, which is the listing's own hash, so every object+under `blobs/<hex>` or `trees/<hex>` holds bytes whose SHA-256 is that `<hex>`, and a bucket refusing every+unconditional write under those prefixes refuses none of this runner's.+Every object under `blobs/<sha256>` holds, whole, the bytes whose SHA-256 is that hash: the key is the hash this runnercomputes from the bytes it writes, the runner's own `PUT /v1/blobs/{sha256}` writes only bytes it checked against the-path's hash, and every built-in storage provider publishes a write whole or not at all (the local one through a-temporary file renamed onto the key). So an object's stored size, read from its metadata without reading its bytes, is-the size of that hash's bytes, and nothing deletes or rewrites a blob. A listing, written once each of its files was-held at its size, therefore stays true.+path's hash, and every built-in storage provider publishes a write whole or not at all. So an object's stored size,+read from its metadata without reading its bytes, is the size of that hash's bytes, and nothing deletes or rewrites a+blob. A listing, written once each of its files was held at its size, therefore stays true.From this the blob store answers without reading what it does not need:- `POST /v1/blobs/missing` lists a hash this runner does not hold at the size the sender states, an object held at- another size included, which only a storage that does not publish writes whole could leave short, and which the- upload then writes over.+ another size included. The upload then tells the two cases apart, holding the bytes: bytes of the size held are the+ ones held, and nothing is written, while bytes of another size mean the object held is damaged, which only a storage+ that does not publish writes whole could leave, a 500 `BlobStoreCorrupted`, since nothing writes over a blob and its+ operator must remove the object.- A run looks up each hash's stored size first. A hash held at another size than an entry states is a 422`BlobMismatch`, never `MissingBlobs`, since uploading those bytes again would change nothing: the entry is wrong.Only a blob held at the size its entries state is read, so the bytes read are bounded by the sizes the request@@ -101,10 +110,6 @@ class RunnerBlobStore:except StorageFileNotFoundError:return None- async def holds_blob(self, *, sha256: str, size: int) -> bool:- """Whether the bytes whose SHA-256 is `sha256` are held at `size`, an object of another size being no blob."""- return await self.stored_size(sha256=sha256) == size-async def stored_sizes(self, *, sha256s: Iterable[str]) -> dict[str, int | None]:"""Each hash's stored size, None for a hash not held, looked up a bounded number at a time."""hashes = list(sha256s)@@ -138,16 +143,33 @@ class RunnerBlobStore:return InMemoryBlobStore(blobs)async def store_blob(self, *, data: bytes) -> str:- """Hold `data` under its SHA-256, writing it unless it is held at its size already, and return the hash.+ """Hold `data` under its SHA-256, creating the blob unless it is held already, and return the hash.++ The blob is looked up first, so bytes already held are not sent again, then created only if its key is still+ free, with its hash as its checksum: a writer that created it meanwhile wrote the same bytes, and the key+ holding an object is the blob held.- An object under the hash at another size, which only a storage that does not publish writes whole could leave,- is written over.+ Raises (as a problem document): a 500 `BlobStoreCorrupted` when an object of another size is held under the+ hash, which only damaged storage could hold and which this runner never writes over."""sha256 = sha256_hex(data)- if not await self.holds_blob(sha256=sha256, size=len(data)):- await self._storage.store(data, key=self._blob_key(sha256=sha256), content_type=_BLOB_CONTENT_TYPE)+ await self._store_hashed_blob(sha256=sha256, data=data)return sha256+ async def _store_hashed_blob(self, *, sha256: str, data: bytes) -> None:+ """Hold `data`, whose SHA-256 is `sha256`, as `store_blob` does, for a caller that hashed it already."""+ held_size = await self.stored_size(sha256=sha256)+ if held_size is None:+ await self._storage.store_if_absent(+ data=data, key=self._blob_key(sha256=sha256), content_type=_BLOB_CONTENT_TYPE, checksum_sha256_hex=sha256+ )+ elif held_size != len(data):+ msg = (+ f"This runner's blob store holds {held_size} bytes under {sha256}, whose bytes are {len(data)} long: its "+ "storage is damaged, and its operator must remove that object for the blob to be uploaded again."+ )+ raise_internal_server_error(message=msg, error_type=ErrorType.BLOB_STORE_CORRUPTED)+async def holds_tree(self, *, tree_digest: str) -> bool:"""Whether the listing of the tree `tree_digest` names is held, which means every file of the tree is."""return await self._holds_key(key=self._tree_key(tree_digest=tree_digest))@@ -173,16 +195,29 @@ class RunnerBlobStore:"""Hold every file of a tree read in full, then its listing, so a later request can send it by hash.The listing is written last, once every file it names is held, so a listing present always means its whole- tree is, and a tree whose listing is held already is left as it is, without a lookup per file.+ tree is, and a tree whose listing is held already is left as it is, without a lookup per file. The listing is+ created only if its key is free, with the hexadecimal part of the tree's digest as its checksum, which is the+ listing's own hash: a listing held already, whoever wrote it, is the same bytes.Args:tree: The tree, as a map of file entries made it.- contents: Each file's bytes by tree path.+ contents: Each file's bytes by tree path. Files of the same bytes are held as one blob, written once."""if await self.holds_tree(tree_digest=tree.digest):return- await gather_bounded([partial(self.store_blob, data=data) for data in contents.values()], max_concurrency=MAX_CONCURRENT_BLOB_TRANSFERS)- await self._storage.store(tree_listing(tree.files), key=self._tree_key(tree_digest=tree.digest), content_type=_LISTING_CONTENT_TYPE)+ # One write per distinct blob: two files of the same bytes, such as two empty files, name one key, and two+ # concurrent creates of one key would race each other for nothing.+ blobs_by_hash = {sha256_hex(data): data for data in contents.values()}+ await gather_bounded(+ [partial(self._store_hashed_blob, sha256=sha256, data=data) for sha256, data in blobs_by_hash.items()],+ max_concurrency=MAX_CONCURRENT_BLOB_TRANSFERS,+ )+ await self._storage.store_if_absent(+ data=tree_listing(tree.files),+ key=self._tree_key(tree_digest=tree.digest),+ content_type=_LISTING_CONTENT_TYPE,+ checksum_sha256_hex=tree.digest.removeprefix(DIGEST_PREFIX),+ )async def missing_blobs(self, *, sizes: Mapping[str, int]) -> list[str]:"""The hashes of `sizes` not held at their size, in the mapping's order."""diff --git a/api/pipelex_api/routes/blob_upload.py b/api/pipelex_api/routes/blob_upload.pyindex 978b23071..5c7dfb0b2 100644--- a/api/pipelex_api/routes/blob_upload.py+++ b/api/pipelex_api/routes/blob_upload.py@@ -3,10 +3,11 @@This router mounts OUTSIDE the authenticated composite `/v1` router, like `/v1/version`: the upload is authorized bythe signed query of its target (`pipelex_api.blob_upload`), which only a caller who passed the deployment'sauthentication on `POST /v1/blobs/missing` holds, so a sender uploads with exactly the headers the target names. The-bytes are written under the scope the signature binds, whole: a blob is never changed, so uploading bytes the runner-already holds at their size succeeds and changes nothing, and only bytes held short, which a storage that does not-publish writes whole could leave, are written over. Only `blobs/` is ever written here, never a tree's listing under `trees/`,-so an uploaded file that happens to read as a listing proves nothing.+bytes are written under the scope the signature binds, whole and create-only (`pipelex_api.blob_store`): a blob is never+changed, so uploading bytes the runner already holds succeeds and changes nothing, and bytes of another size than the+object held under their hash, which only damaged storage could hold, are a 500 `BlobStoreCorrupted` rather than written+over it. Only `blobs/` is ever written here, never a tree's listing under `trees/`, so an uploaded file that happens to+read as a listing proves nothing."""from typing import Annotated@@ -55,7 +56,8 @@ async def put_blob(403 `BlobUploadNotAuthorized`, as is a query that is not one this runner signs, such as an expiry that is not adecimal integer; a body past `MAX_METHOD_TREE_FILE_KIB` a 422 `MethodTreeTooLarge`; and a body whose SHA-256 is notthe path's a 422 `BlobMismatch`. A blob is never changed: uploading bytes the runner already holds answers 204 and- changes nothing.+ changes nothing, and uploading bytes whose hash names an object of another size, which only damaged storage could+ hold, is a 500 `BlobStoreCorrupted` that leaves the object as it is."""if not is_upload_authorized(scope=scope, sha256=sha256, expires=expires, signature=signature) or scope is None:msg = "This upload carries no valid target: ask POST /v1/blobs/missing for one, and upload to the URL it names before it expires."diff --git a/api/pipelex_api/routes/pipelex/blobs.py b/api/pipelex_api/routes/pipelex/blobs.pyindex 4222aaa89..7b1c4fd7b 100644--- a/api/pipelex_api/routes/pipelex/blobs.py+++ b/api/pipelex_api/routes/pipelex/blobs.py@@ -105,8 +105,10 @@ async def find_missing_blobs() -> MissingBlobsResult:"""List every blob of the request this runner does not hold, each with a signed upload target (MTHDS Protocol).- A blob it holds at the stated size is left out, and an empty list means there is nothing to upload; bytes held- under a hash at another size are listed, for the upload to write over. When the request names the tree the blobs+ A blob it holds at the stated size is left out, and an empty list means there is nothing to upload; a hash held+ at another size than the one stated is listed too, and its upload tells the two cases apart: bytes of the size held+ change nothing, and bytes of another size mean the object held is damaged, a 500 `BlobStoreCorrupted`, since nothing+ writes over a blob. When the request names the tree the blobsmake up by its `digest`, this runner has recorded that tree as held in full, which it does only after reading everyfile of a tree a request sent, and every listed blob is a file of that tree, the answer is an empty list at once.A hash given twice with different sizes is a 422 `BlobMismatch`, and a blob or a set of blobs past this runner'sdiff --git a/api/pipelex_api/routes/pipelex/pipeline.py b/api/pipelex_api/routes/pipelex/pipeline.pyindex 215dd0f4c..722424316 100644--- a/api/pipelex_api/routes/pipelex/pipeline.py+++ b/api/pipelex_api/routes/pipelex/pipeline.py@@ -489,6 +489,8 @@ class ApiRunner(PipelexMTHDSProtocol):created_at=created_at,state=RunState.STARTED,workflow_id=dispatch_ack.workflow_id,+ # The crate the job was built from, which a host records beside the run's tree digest.+ crate_fingerprint=pipe_job.job_metadata.run_metadata.crate_fingerprint,)async def _ensure_served_method_requirements_met(self) -> None:diff --git a/api/pipelex_api/routes/pipelex/validate.py b/api/pipelex_api/routes/pipelex/validate.pyindex d9ec01f58..d539958d5 100644--- a/api/pipelex_api/routes/pipelex/validate.py+++ b/api/pipelex_api/routes/pipelex/validate.py@@ -140,7 +140,8 @@ class ValidateRequest(MthdsContentsRequest, CallerAnalyticsGroupsMixin):description=("PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the scope of the blob store a hash entry of `files` ""resolves in, as a run's `read_scope`: a multi-tenant host sends the one of the organization it serves. Omit it "- "and the caller's own id is the scope."+ "and the caller's own id is the scope. Only a validation carrying it records the tree it read in the blob "+ "store, so a dry run without one leaves nothing stored."),)@@ -419,7 +420,10 @@ async def validate_mthds(request: Request, request_data: ValidateRequest) -> JSOmethod_label = REQUEST_METHOD_LABELensure_method_holds_a_bundle(request_method=request_method, label="This method")ensure_python_allowed(request_method=request_method, label="This method")- await record_request_method(request_method=request_method, blob_store=blob_store)+ # A dry run records the tree only under the scope a host named: without one, the fallback scope is the+ # caller's own id, a prefix no host lists or erases, and a validation must leave nothing stored there.+ if request_data.read_scope is not None:+ await record_request_method(request_method=request_method, blob_store=blob_store)validated_contents = _bundle_texts(request_method=request_method)# The entry pipe of the tree, the one a selector-less run executes, is the graph's pipe and the default the# verdict reports; a tree with none still validates.diff --git a/api/tests/unit/test_blob_routes.py b/api/tests/unit/test_blob_routes.pyindex e4811c055..49aea294b 100644--- a/api/tests/unit/test_blob_routes.py+++ b/api/tests/unit/test_blob_routes.py@@ -185,14 +185,48 @@ class TestBlobRoutes:client = _build_client()contents = {"main.mthds": VALID_MTHDS.encode("utf-8"), "notes.txt": _NOTES}digest = digest_of_contents(contents)- assert len(_missing(client, *contents.values(), digest=digest)) == 2+ assert len(_missing(client, *contents.values(), digest=digest, read_scope="org-a")) == 2- validated = client.post("/v1/validate", json={"files": {"main.mthds": VALID_MTHDS, "notes.txt": _NOTES.decode("utf-8")}})+ validated = client.post(+ "/v1/validate", json={"files": {"main.mthds": VALID_MTHDS, "notes.txt": _NOTES.decode("utf-8")}, "read_scope": "org-a"}+ )assert validated.status_code == 200, validated.textassert validated.json()["is_valid"] is True, validated.text- assert _missing(client, *contents.values(), digest=digest) == []- assert _missing(client, *contents.values()) == []+ assert _missing(client, *contents.values(), digest=digest, read_scope="org-a") == []+ assert _missing(client, *contents.values(), read_scope="org-a") == []++ def test_a_validation_records_its_tree_only_under_a_read_scope_it_was_sent(self, blob_storage: InMemoryStorageProvider) -> None:+ """A dry run without a read scope leaves nothing stored, since its fallback scope, the caller's id, no host erases."""+ client = _build_client()+ files = {"main.mthds": VALID_MTHDS, "notes.txt": _NOTES.decode("utf-8")}+ contents = {"main.mthds": VALID_MTHDS.encode("utf-8"), "notes.txt": _NOTES}++ unscoped = client.post("/v1/validate", json={"files": files})++ assert unscoped.status_code == 200, unscoped.text+ assert unscoped.json()["is_valid"] is True, unscoped.text+ assert blob_storage.root == {}++ scoped = client.post("/v1/validate", json={"files": files, "read_scope": "org-a"})++ assert scoped.status_code == 200, scoped.text+ digest_hex = digest_of_contents(contents).removeprefix("sha256:")+ assert sorted(blob_storage.root) == sorted([f"org-a/blobs/{sha256_hex(data)}" for data in contents.values()] + [f"org-a/trees/{digest_hex}"])+ assert blob_storage.root[f"org-a/trees/{digest_hex}"] == tree_listing(tree_files_from_contents(contents))++ def test_a_validation_without_a_read_scope_still_reads_the_caller_s_blobs(self, blob_storage: InMemoryStorageProvider) -> None:+ """Only the recording waits on a read scope: hash entries resolve in the caller's own scope, as before."""+ client = _build_client()+ (target,) = _missing(client, _NOTES)+ assert _upload(client, target=target, data=_NOTES).status_code == 204+ held_before = dict(blob_storage.root)++ validated = client.post("/v1/validate", json={"files": {"main.mthds": VALID_MTHDS, "notes.txt": _blob_ref(_NOTES)}})++ assert validated.status_code == 200, validated.text+ assert validated.json()["is_valid"] is True, validated.text+ assert blob_storage.root == held_beforedef test_an_uploaded_listing_never_records_its_tree(self) -> None:"""Anyone can upload bytes that happen to form a listing, so an upload never stands for a tree held in full."""@@ -253,25 +287,26 @@ class TestBlobRoutes:_assert_problem(response, status=500, error_type="ServerMisconfigured")- def test_a_blob_held_at_another_size_is_listed_for_its_upload_to_write_over(self, blob_storage: InMemoryStorageProvider) -> None:- """Bytes held short, as a storage that does not publish writes whole could leave them, are asked for again and repaired."""+ def test_a_blob_held_at_another_size_is_listed_and_its_upload_never_writes_over_it(self, blob_storage: InMemoryStorageProvider) -> None:+ """Bytes held short are damaged storage: they are asked for, and their upload is a 500 that leaves the object as it is."""client = _build_client()blob_storage.root[f"single-tenant/blobs/{sha256_hex(_TEMPLATE)}"] = _TEMPLATE[:5](target,) = _missing(client, _TEMPLATE)uploaded = _upload(client, target=target, data=_TEMPLATE)- assert uploaded.status_code == 204, uploaded.text- assert blob_storage.root[f"single-tenant/blobs/{sha256_hex(_TEMPLATE)}"] == _TEMPLATE- assert _missing(client, _TEMPLATE) == []+ _assert_problem(uploaded, status=500, error_type="BlobStoreCorrupted")+ assert blob_storage.root[f"single-tenant/blobs/{sha256_hex(_TEMPLATE)}"] == _TEMPLATE[:5]def test_a_held_digest_answers_alone_only_for_blobs_of_its_tree(self) -> None:"""A digest the runner holds says nothing of blobs outside its tree, which are looked up one by one."""client = _build_client()contents = {"main.mthds": VALID_MTHDS.encode("utf-8"), "notes.txt": _NOTES}- validated = client.post("/v1/validate", json={"files": {"main.mthds": VALID_MTHDS, "notes.txt": _NOTES.decode("utf-8")}})+ validated = client.post(+ "/v1/validate", json={"files": {"main.mthds": VALID_MTHDS, "notes.txt": _NOTES.decode("utf-8")}, "read_scope": "org-a"}+ )assert validated.status_code == 200, validated.text- missing = _missing(client, *contents.values(), _TEMPLATE, digest=digest_of_contents(contents))+ missing = _missing(client, *contents.values(), _TEMPLATE, digest=digest_of_contents(contents), read_scope="org-a")assert [blob["sha256"] for blob in missing] == [sha256_hex(_TEMPLATE)]diff --git a/api/tests/unit/test_blob_store.py b/api/tests/unit/test_blob_store.pyindex f23fb55a8..de5a27bf1 100644--- a/api/tests/unit/test_blob_store.py+++ b/api/tests/unit/test_blob_store.py@@ -1,8 +1,9 @@"""The runner's blob store over a storage provider: what it looks up by size, what it reads, and how many at once.The storage here counts its calls and the ones in flight, so these pin what the routes cannot show: a blob held at-another size than an entry states is never read, reads and lookups run a bounded number at a time, a short object is-written over by the next upload, and a tree whose listing is held is recorded without a lookup per file.+another size than an entry states is never read, reads and lookups run a bounded number at a time, every write is+create-only with its checksum, a short object is never written over, and a tree whose listing is held is recorded+without a lookup per file."""import asyncio@@ -12,6 +13,7 @@ import pytestfrom mthds.method_tree.digest import digest_of_contents, sha256_hex, tree_files_from_contents, tree_listingfrom pipelex.tools.storage.exceptions import StorageFileNotFoundErrorfrom pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract, StoredData+from pytest_mock import MockerFixturefrom typing_extensions import overridefrom pipelex_api.blob_store import MAX_CONCURRENT_BLOB_LOOKUPS, MAX_CONCURRENT_BLOB_TRANSFERS, RunnerBlobStore@@ -28,6 +30,9 @@ class _CountingStorage(StorageProviderAbstract):self.objects: dict[str, bytes] = {}self.loaded_keys: list[str] = []self.sized_keys: list[str] = []+ self.created: list[tuple[str, str | None]] = []+ self.create_attempts: list[str] = []+ self.unconditional_keys: list[str] = []self.most_loads_at_once = 0self.most_lookups_at_once = 0self._loads_in_flight = 0@@ -64,8 +69,20 @@ class _CountingStorage(StorageProviderAbstract):@overrideasync def _store(self, data: bytes, *, key: str, content_type: str | None) -> None:+ self.unconditional_keys.append(key)self.objects[key] = data+ @override+ async def _store_if_absent(self, *, data: bytes, key: str, content_type: str | None, checksum_sha256_hex: str | None) -> bool:+ self.create_attempts.append(key)+ # Yield, so every create the store started at once is in flight together.+ await asyncio.sleep(0)+ if key in self.objects:+ return False+ self.created.append((key, checksum_sha256_hex))+ self.objects[key] = data+ return True+@overrideasync def public_url(self, uri: str) -> str | None:return None@@ -146,18 +163,74 @@ class TestRunnerBlobStore:assert storage.most_lookups_at_once == MAX_CONCURRENT_BLOB_LOOKUPSassert storage.most_loads_at_once == MAX_CONCURRENT_BLOB_TRANSFERS- async def test_a_short_object_is_not_held_and_the_next_upload_writes_it_over(self) -> None:- """A storage that does not publish writes whole may leave a blob cut short: it is asked for again, then repaired."""+ async def test_a_short_object_is_asked_for_and_its_upload_is_a_server_fault_that_writes_nothing(self) -> None:+ """A blob cut short is damaged storage, which no write repairs: nothing writes over a blob, so its operator must."""storage = _CountingStorage()blob_store = RunnerBlobStore(scope=_SCOPE, storage=storage)data = b"the whole blob, of which a failed write kept only a part"storage.objects[_blob_key(data)] = data[:10]assert await blob_store.missing_blobs(sizes={sha256_hex(data): len(data)}) == [sha256_hex(data)]- await blob_store.store_blob(data=data)+ with pytest.raises(ApiError) as exc_info:+ await blob_store.store_blob(data=data)++ assert exc_info.value.status_code == 500+ assert _problem_of(exc_info)["error_type"] == "BlobStoreCorrupted"+ assert storage.objects[_blob_key(data)] == data[:10]+ assert storage.created == []+ assert storage.unconditional_keys == []++ async def test_blobs_and_listings_are_created_only_with_their_checksums(self) -> None:+ """Every write names its SHA-256, the blob's hash or the listing's digest, and none is unconditional."""+ storage = _CountingStorage()+ blob_store = RunnerBlobStore(scope=_SCOPE, storage=storage)+ contents = {"main.mthds": b"domain = 'a'", "notes.txt": b"some notes"}+ request_tree = RequestTree.make_from_contents(contents=contents)++ await blob_store.record_tree(tree=request_tree.tree, contents=request_tree.contents)+ await blob_store.store_blob(data=contents["notes.txt"])++ digest_hex = digest_of_contents(contents).removeprefix("sha256:")+ assert sorted(storage.created) == sorted(+ [(_blob_key(data), sha256_hex(data)) for data in contents.values()] + [(f"{_SCOPE}/trees/{digest_hex}", digest_hex)]+ )+ assert storage.unconditional_keys == []++ async def test_files_of_the_same_bytes_are_one_blob_written_once(self) -> None:+ """Two empty `__init__.py` files name one blob key, which a tree records with one lookup and one create."""+ storage = _CountingStorage()+ blob_store = RunnerBlobStore(scope=_SCOPE, storage=storage)+ contents = {"main.mthds": b"domain = 'a'", "pkg/__init__.py": b"", "pkg/sub/__init__.py": b""}+ request_tree = RequestTree.make_from_contents(contents=contents)++ await blob_store.record_tree(tree=request_tree.tree, contents=request_tree.contents)++ empty_key = _blob_key(b"")+ assert storage.sized_keys.count(empty_key) == 1+ assert storage.create_attempts.count(empty_key) == 1+ assert storage.objects[empty_key] == b""+ digest_hex = digest_of_contents(contents).removeprefix("sha256:")+ assert sorted(storage.created) == sorted(+ [(_blob_key(b"domain = 'a'"), sha256_hex(b"domain = 'a'")), (empty_key, sha256_hex(b"")), (f"{_SCOPE}/trees/{digest_hex}", digest_hex)]+ )++ async def test_a_blob_another_writer_created_meanwhile_is_held(self, mocker: MockerFixture) -> None:+ """The lookup found nothing, then the create found the key taken: the same bytes are held, and that is no error."""+ storage = _CountingStorage()+ blob_store = RunnerBlobStore(scope=_SCOPE, storage=storage)+ data = b"bytes two writers send at once"++ async def _absent_then_created(key: str) -> int:+ # The lookup misses, and the other writer's object lands before this writer's create.+ storage.objects[key] = data+ msg = f"File not found: '{key}'"+ raise StorageFileNotFoundError(msg)++ mocker.patch.object(storage, "_load_size", side_effect=_absent_then_created)+ assert await blob_store.store_blob(data=data) == sha256_hex(data)+ assert storage.created == []assert storage.objects[_blob_key(data)] == data- assert await blob_store.missing_blobs(sizes={sha256_hex(data): len(data)}) == []async def test_a_tree_whose_listing_is_held_is_recorded_without_a_lookup_per_file(self) -> None:storage = _CountingStorage()diff --git a/api/tests/unit/test_execute_dispatch.py b/api/tests/unit/test_execute_dispatch.pyindex 3c444f042..071afaa20 100644--- a/api/tests/unit/test_execute_dispatch.py+++ b/api/tests/unit/test_execute_dispatch.py@@ -80,6 +80,7 @@ class _StubOrchestrator:"pipe_code": pipe_job.pipe.code,"delivery_assignment": delivery_assignment,"request_id": pipe_job.job_metadata.run_metadata.request_id,+ "crate_fingerprint": pipe_job.job_metadata.run_metadata.crate_fingerprint,})# A completed run always delivers a main stuff (pipelex invariant; enforced by@@ -182,6 +183,22 @@ class TestExecuteDispatch:assert len(stub.calls) == 1assert stub.calls[0]["delivery_assignment"] is None+ def test_the_result_reports_the_crate_the_job_was_built_from(self, mocker: MockerFixture) -> None:+ """`crate_fingerprint` is the fingerprint the dispatched job's `RunMetadata` carries, which a host records."""+ stub = _StubOrchestrator()+ _register_stub(mocker, mode="direct", stub=stub)++ response = _build_client().post(+ "/v1/execute",+ json={"pipe_code": "echo", "mthds_contents": [VALID_MTHDS], "inputs": {"text": "hello"}},+ )++ assert response.status_code == 200, response.text+ fingerprint = stub.calls[0]["crate_fingerprint"]+ assert isinstance(fingerprint, str)+ assert fingerprint+ assert response.json()["crate_fingerprint"] == fingerprint+def test_graph_spec_survives_strict_false_rehydration(self, mocker: MockerFixture) -> None:"""A non-None graph_spec round-trips through the helper's `strict=False` reverse of `model_dump(mode="json")`.diff --git a/api/tests/unit/test_start_dispatch.py b/api/tests/unit/test_start_dispatch.pyindex cf08e41c5..72e5394cb 100644--- a/api/tests/unit/test_start_dispatch.py+++ b/api/tests/unit/test_start_dispatch.py@@ -46,7 +46,12 @@ class _RecordingStub:raise NotImplementedError(msg)async def start(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeDispatchAck:- self.calls.append({"delivery_assignment": delivery_assignment})+ self.calls.append(+ {+ "delivery_assignment": delivery_assignment,+ "crate_fingerprint": pipe_job.job_metadata.run_metadata.crate_fingerprint,+ }+ )return PipelexPipeDispatchAck(pipeline_run_id=pipe_job.job_metadata.run_metadata.pipeline_run_id,workflow_id=self._workflow_id,@@ -90,6 +95,11 @@ class TestStartCapabilityGate:assert body["workflow_id"] == "wf-123"# /start drives the fire-and-forget `start` arm exactly once — the caller never chooses delivery.assert len(stub.calls) == 1+ # The ack reports the crate the dispatched job was built from, which a host records on its run.+ fingerprint = stub.calls[0]["crate_fingerprint"]+ assert isinstance(fingerprint, str)+ assert fingerprint+ assert body["crate_fingerprint"] == fingerprintdef test_start_honestly_400s_when_orchestrator_is_blocking_only(self, mocker: MockerFixture) -> None:# The orchestrator-agnostic base (`direct`) is blocking-only: /start refuses honestly with adiff --git a/docs/api-server/error-responses.md b/docs/api-server/error-responses.mdindex dce911102..41f3c35a3 100644--- a/docs/api-server/error-responses.md+++ b/docs/api-server/error-responses.md@@ -177,7 +177,7 @@ A pipe selection the server cannot make is an input **422** named for its failurThe run routes' extension fields are validated before any method is fetched or any library loaded, and a failure there is a **422** whose `error_type` names the field that failed: `InvalidCallbackUrls` for `callback_urls`, `InvalidStorageScope` for `storage_scope`, `InvalidReadScope` for `read_scope`, `InvalidAnalyticsGroups` for `analytics_groups` (see [Pipe Run](pipe-run.md#host-supplied-run-context-storage_scope-and-analytics_groups)). A storage scope that does not lie under the run's read scope, whether either was sent or defaulted, is an `InvalidReadScope` as well. A failure on another extension field, or on more than one at once, carries the generic `ValidationError`, and the `detail` names every field that failed. `POST /v1/validate` takes `analytics_groups` too and classifies it the same way: a body failing on that field alone answers `InvalidAnalyticsGroups`, and one failing on it and another field answers `ValidationError`.-A method sent as a tree, in `files` or `bundle_b64`, is read under the MTHDS standard's tree rule before anything loads, on the run routes and `/validate` alike (see [Pipe Run](pipe-run.md#sending-a-method-as-a-tree)). A key or an entry the rule refuses, two shipped packages a reference could not tell apart, or `dependencies` that do not fit the request is a **422** `InvalidMethodFiles` carrying `tree_refusal` when the standard's reader refused it; a hash entry this runner does not hold is a **422** `MissingBlobs` carrying `missing_blobs`, and one it holds at another size than the entry states a **422** `BlobMismatch` carrying `mismatched_blobs`; a tree past `MAX_METHOD_TREE_FILES`, `MAX_METHOD_TREE_FILE_KIB` or `MAX_METHOD_TREE_TOTAL_KIB`, or a method past `MAX_METHOD_DEPENDENCIES` or `MAX_METHOD_REQUEST_TOTAL_KIB` across its trees, is a **422** `MethodTreeTooLarge`. The blob routes answer in the same vocabulary: a body whose SHA-256 is not the one its path names, or one hash listed with two sizes, is a **422** `BlobMismatch`, and a blob past the per-file limit a **422** `MethodTreeTooLarge`. Every one of these carries `retryable: false`. Bytes the blob store holds under a hash that do not hash to it are a **500** `BlobStoreCorrupted`: the deployment's storage is damaged, and its operator removes the object for the blob to be uploaded again.+A method sent as a tree, in `files` or `bundle_b64`, is read under the MTHDS standard's tree rule before anything loads, on the run routes and `/validate` alike (see [Pipe Run](pipe-run.md#sending-a-method-as-a-tree)). A key or an entry the rule refuses, two shipped packages a reference could not tell apart, or `dependencies` that do not fit the request is a **422** `InvalidMethodFiles` carrying `tree_refusal` when the standard's reader refused it; a hash entry this runner does not hold is a **422** `MissingBlobs` carrying `missing_blobs`, and one it holds at another size than the entry states a **422** `BlobMismatch` carrying `mismatched_blobs`; a tree past `MAX_METHOD_TREE_FILES`, `MAX_METHOD_TREE_FILE_KIB` or `MAX_METHOD_TREE_TOTAL_KIB`, or a method past `MAX_METHOD_DEPENDENCIES` or `MAX_METHOD_REQUEST_TOTAL_KIB` across its trees, is a **422** `MethodTreeTooLarge`. The blob routes answer in the same vocabulary: a body whose SHA-256 is not the one its path names, or one hash listed with two sizes, is a **422** `BlobMismatch`, and a blob past the per-file limit a **422** `MethodTreeTooLarge`. Every one of these carries `retryable: false`. Bytes the blob store holds under a hash that do not hash to it, or an upload whose bytes hash to an object held at another size, are a **500** `BlobStoreCorrupted`: the deployment's storage is damaged, the runner never writes over a blob, and its operator removes the object for the blob to be uploaded again.The files a request sends in `resources` are checked before the bundle loads and again once it is parsed (see [Pipe Validate](pipe-validate.md#sending-the-files-the-steps-read-resources)). A key that cannot name a file inside the bundle is a **422** `InvalidResourcePath`, a value that is not base64 a **400** `InvalidBase64`, a file none of the bundle's steps names a **422** `BundleResourceNotNamedError`, and files that cannot make one method tree, such as two keys equal once case-folded, a **422** `BundleResourcePathError`, on every route, the diagnostic ones included: both are the request's fault, not the bundle's, and every one of these refusals carries `retryable: false`, since the same request is refused again.diff --git a/docs/api-server/openapi/pipelex-api.openapi.yaml b/docs/api-server/openapi/pipelex-api.openapi.yamlindex 0e15985ca..b2f248a57 100644--- a/docs/api-server/openapi/pipelex-api.openapi.yaml+++ b/docs/api-server/openapi/pipelex-api.openapi.yaml@@ -91,7 +91,9 @@ paths:the path''s a 422 `BlobMismatch`. A blob is never changed: uploading bytes the runner already holds answers 204 and- changes nothing.'+ changes nothing, and uploading bytes whose hash names an object of another size, which only damaged storage could++ hold, is a 500 `BlobStoreCorrupted` that leaves the object as it is.'operationId: put_blob_v1_blobs__sha256__putparameters:- name: sha256@@ -1507,9 +1509,13 @@ paths:description: 'List every blob of the request this runner does not hold, each with a signed upload target (MTHDS Protocol).- A blob it holds at the stated size is left out, and an empty list means there is nothing to upload; bytes held+ A blob it holds at the stated size is left out, and an empty list means there is nothing to upload; a hash held++ at another size than the one stated is listed too, and its upload tells the two cases apart: bytes of the size held- under a hash at another size are listed, for the upload to write over. When the request names the tree the blobs+ change nothing, and bytes of another size mean the object held is damaged, a 500 `BlobStoreCorrupted`, since nothing++ writes over a blob. When the request names the tree the blobsmake up by its `digest`, this runner has recorded that tree as held in full, which it does only after reading every@@ -6424,6 +6430,14 @@ components:main_stuff_name:type: stringtitle: Main Stuff Name+ crate_fingerprint:+ anyOf:+ - type: string+ - type: 'null'+ title: Crate Fingerprint+ description: PIPELEX EXTENSION (not part of the MTHDS Protocol) — the fingerprint of the library crate the run's+ method was loaded into, the identity of its concepts and pipes, which changes with their meaning and not with+ their formatting or comments. Null when the run was built from no crate.method_provenance:anyOf:- $ref: '#/components/schemas/MethodProvenance'@@ -6473,6 +6487,14 @@ components:- type: string- type: 'null'title: Workflow Id+ crate_fingerprint:+ anyOf:+ - type: string+ - type: 'null'+ title: Crate Fingerprint+ description: PIPELEX EXTENSION (not part of the MTHDS Protocol) — the fingerprint of the library crate the run's+ method was loaded into, the identity of its concepts and pipes, which changes with their meaning and not with+ their formatting or comments. Null when the run was built from no crate.method_provenance:anyOf:- $ref: '#/components/schemas/MethodProvenance'@@ -8260,7 +8282,8 @@ components:title: Read Scopedescription: 'PIPELEX-API EXTENSION (not part of the MTHDS Protocol) — the scope of the blob store a hash entryof `files` resolves in, as a run''s `read_scope`: a multi-tenant host sends the one of the organization it serves.- Omit it and the caller''s own id is the scope.'+ Omit it and the caller''s own id is the scope. Only a validation carrying it records the tree it read in the blob+ store, so a dry run without one leaves nothing stored.'type: objecttitle: ValidateRequestdescription: 'The shared `mthds_contents` + `allow_signatures` payload, plus optional per-file sources.diff --git a/docs/api-server/pipe-run.md b/docs/api-server/pipe-run.mdindex a5e28f663..534976a17 100644--- a/docs/api-server/pipe-run.md+++ b/docs/api-server/pipe-run.md@@ -60,6 +60,7 @@ Execute a Pipelex pipeline with flexible inputs and wait for completion."state": "COMPLETED","finished_at": "2026-01-15T12:00:05Z","main_stuff_name": "result",+ "crate_fingerprint": "9f2c41…","pipe_output": {"working_memory": {"root": { "result": { "content": { "...": "..." } } },@@ -76,6 +77,7 @@ Execute a Pipelex pipeline with flexible inputs and wait for completion.- `state` (string): One of `"RUNNING"`, `"COMPLETED"`, `"FAILED"`, `"CANCELLED"`, `"ERROR"`, `"STARTED"`.- `finished_at` (string | null): ISO timestamp when the pipeline finished, or `null` if still running.- `main_stuff_name` (string | null): Key under `pipe_output.working_memory.root` where the main result lives. Use this to extract the typed output: `pipe_output.working_memory.root[main_stuff_name].content`.+- `crate_fingerprint` (string | null): **Pipelex extension.** The fingerprint of the library crate the run's method was loaded into, the identity of its concepts and pipes, which changes with their meaning and not with their formatting or comments; a host records it on its run beside the digest of the method tree that ran. `null` when the run was built from no crate.- `pipe_output` (object): Result of the pipeline execution. Contains `working_memory` with `root` (every named stuff produced during the run) and `aliases` (built-in name mappings such as `main_stuff`).- `pipe_output.tokens_usages` (array | null): Per-inference-call token usage in the client wire shape (`TokensUsageRecord`): `model_type`, model name/id, `pipe_code`, job-kind fields, `nb_tokens_by_category`, computed USD `cost` (`null` when the model has no rate table), and ISO timestamps. `null` when usage assembly was off for the run, `[]` when no inference happened. `pipe_output.usage_assembly_error` (string | null) is non-null when usage assembly failed. See the pipelex runtime's [TokensUsage Wire Records](https://docs.pipelex.com/under-the-hood/tokens-usage-wire-records/) for the full field reference.- `pipe_output.graph_spec` (object | null): Best-effort execution graph of the run — the nodes and edges the run actually traversed. `null` when graph generation was off for the run, which is the `interpreter.pipeline_execution.is_generate_graph` setting (`true` in the packaged config); it does not depend on `runtime.tracing`, whose `is_enabled` selects a trace-emission backend rather than gating assembly. `pipe_output.graph_assembly_error` (string | null) is non-null when assembly ran and failed, which is what distinguishes a failed assembly from generation having been off.@@ -150,7 +152,8 @@ Start a pipeline execution and get its `pipeline_run_id` back with a `202` ack."finished_at": null,"main_stuff_name": null,"pipe_output": null,- "workflow_id": "pipeline-abc123..."+ "workflow_id": "pipeline-abc123...",+ "crate_fingerprint": "9f2c41…"}```@@ -164,6 +167,7 @@ Start a pipeline execution and get its `pipeline_run_id` back with a `202` ack.- `pipe_output` (null): Always `null`; the result isn't ready yet.- `workflow_id` (string | null): The async orchestrator's workflow ID. A `202` ack is only ever returned by an async-capable backend (e.g. a Temporal flavor), so this carries that orchestrator's id; the in-process `direct` base never acks here — it returns a `400` (`StartRequiresAsyncOrchestration`) instead.- `method_provenance` (object | null): `{address, tag, commit_sha}` for a `method_ref` run — see [Running a method by address](#running-a-method-by-address-method_ref); `null` for runs from inline source or a bundle.+- `crate_fingerprint` (string | null): **Pipelex extension.** The fingerprint of the library crate the run's job was built from, as on the `/execute` result, known as soon as the run is queued, so a host records it from the acknowledgement.**Errors** follow the same convention as `/execute`: HTTP 4xx/5xx with an [RFC 7807 `application/problem+json`](error-responses.md) body.@@ -257,9 +261,11 @@ This runner keeps a **blob store**, declared by `blob_store: true` in [`GET /v1/The answer is `{"missing": [{"sha256": "…", "size": n, "upload": {"method": "PUT", "url": "…", "headers": {"content-type": "application/octet-stream"}}}, …]}`, listing only the blobs the runner does not hold; an empty list means there is nothing to upload. Each target is the runner's own `PUT /v1/blobs/{sha256}`, its query signed for that hash and the caller's scope and valid for `BLOB_UPLOAD_URL_TTL_SECONDS` (default an hour). The target starts with `PUBLIC_BASE_URL` when the deployment sets it, the address its clients reach the API at, which a deployment behind a proxy terminating TLS or adding a path prefix sets, and otherwise with the URL the request arrived at. The upload route needs no bearer token, since the signed target is its authorization: a missing, malformed, forged or expired signature is a `403 BlobUploadNotAuthorized`, a body whose SHA-256 is not the path's a `422 BlobMismatch`, and a body past `MAX_METHOD_TREE_FILE_KIB` a `422 MethodTreeTooLarge`. A blob is written whole and never changed, so uploading bytes the runner holds answers `204` and changes nothing. On `POST /v1/blobs/missing`, one hash listed with two sizes is a `422 BlobMismatch`, and blobs past the tree limits a `422 MethodTreeTooLarge`, both before anything is uploaded.-**Sizes.** A blob is held at a size, which the runner reads from the storage's metadata without reading the bytes. `POST /v1/blobs/missing` lists a blob the runner does not hold at the size the sender states, bytes held short included, which only a storage that does not publish a write whole could leave and which the upload then writes over. On a run or a validation, every hash entry is looked up by size before any byte is read: a hash the runner holds at another size than the entry states is a `422 BlobMismatch` whose `mismatched_blobs` member gives each hash with its `held_size`, since the bytes under a hash have one size and uploading them again would change nothing, so the entry's size is the one to correct. Only bytes held at the size their entry states are read, a bounded number at a time, and checked against their hash; bytes that do not hash to their key mean the deployment's storage is damaged, a `500 BlobStoreCorrupted` that its operator repairs by removing the object, for it to be uploaded again.+**Writes are create-only.** The runner creates a blob, or a tree's listing, only when its key holds nothing, and never replaces an object already there: on S3 the write carries `If-None-Match: *` and its SHA-256 as `x-amz-checksum-sha256`, which S3 checks against the body, on GCS it is conditional on generation 0, and on the local filesystem the file is created through a hard link, so the local storage's folder must sit on a filesystem that supports them. A key already holding an object is the object already held, the same bytes since the key is their hash, and the write succeeds without changing it. A deployment's bucket can therefore refuse every unconditional write under `blobs/` and `trees/` without refusing any of the runner's, as the hosted platform's does.-**The digest shortcut.** Once the runner has read a request's tree in full, it records the tree's listing beside its blobs, after every file it names is held, and an upload never records one. Asking `POST /v1/blobs/missing` with the digest of a recorded tree then answers an empty list in one lookup, however many files the tree has, when every blob listed is a file of that tree; a blob outside it is looked up as if no digest were sent.+**Sizes.** A blob is held at a size, which the runner reads from the storage's metadata without reading the bytes. `POST /v1/blobs/missing` lists a blob the runner does not hold at the size the sender states, an object held at another size included. Its upload then tells the two cases apart: bytes of the size held are the ones held, and change nothing, while bytes of another size mean the object held is damaged, which only a storage that does not publish a write whole could leave, a `500 BlobStoreCorrupted`, since nothing writes over a blob and the deployment's operator removes the object for it to be uploaded again. On a run or a validation, every hash entry is looked up by size before any byte is read: a hash the runner holds at another size than the entry states is a `422 BlobMismatch` whose `mismatched_blobs` member gives each hash with its `held_size`, since the bytes under a hash have one size and uploading them again would change nothing, so the entry's size is the one to correct. Only bytes held at the size their entry states are read, a bounded number at a time, and checked against their hash; bytes that do not hash to their key mean the deployment's storage is damaged, a `500 BlobStoreCorrupted` that its operator repairs by removing the object, for it to be uploaded again.++**The digest shortcut.** Once the runner has read a request's tree in full, it records the tree's listing beside its blobs, after every file it names is held, and an upload never records one. A validation records it only when its request carries a `read_scope`: without one, its scope would be the caller's own id, where a dry run must leave nothing stored. Asking `POST /v1/blobs/missing` with the digest of a recorded tree then answers an empty list in one lookup, however many files the tree has, when every blob listed is a file of that tree; a blob outside it is looked up as if no digest were sent.**Scopes.** Blobs live in the deployment's configured storage, under `<scope>/blobs/<sha256>`, and recorded listings under `<scope>/trees/<digest>`. The scope is the request's `read_scope`, which a multi-tenant host sends for the organization it serves (a query parameter on `POST /v1/blobs/missing`, a body field on the run and validate routes), else the caller's own id, so a hash entry resolves only in the caller's own blobs and asking whether a hash is held tells a caller nothing of another's files. A hash entry the runner does not hold, at the size it states, is a `422 MissingBlobs` whose `missing_blobs` member lists the hashes to upload before sending the request again.diff --git a/docs/api-server/pipe-validate.md b/docs/api-server/pipe-validate.mdindex 069522768..4293c9a20 100644--- a/docs/api-server/pipe-validate.md+++ b/docs/api-server/pipe-validate.md@@ -20,7 +20,7 @@ Validate MTHDS content by parsing, loading, and dry-running pipes without execut- `files` (object, optional): The method as a map of file entries, the MTHDS standard's method tree, each value the file's text, `{"base64": "…"}` or `{"sha256": "…", "size": n}`, read as on a run — see [Validating a method tree](#validating-a-method-tree). Exactly one of `mthds_contents` / `files` / `method_ref`- `dependencies` (object, optional): **Pipelex-API extension.** The method packages the method calls by address that the runner cannot fetch, each a map of file entries keyed by its address, as on a [run](pipe-run.md#sending-the-method-packages-the-method-calls). Accompanies `files`- `method_ref` (string, optional): **Pipelex-API extension.** Validate a published method by address — `github.com/<owner>/<repo>` plus an optional package selector and `@<tag>` — resolved by this server through the same fetch path as a [`method_ref` run](pipe-run.md#running-a-method-by-address-method_ref): the repository is fetched at the tag, the package located by manifest identity, and its tree read from the commit's git objects and validated as a tree sent in `files` is — see [Validating a method tree](#validating-a-method-tree). Exactly one of `mthds_contents` / `files` / `method_ref`; `mthds_sources` cannot accompany it. A package holding Python and a `requirements.txt` has its requirements checked on this server against the package set of the deployment's PipeFunc sandbox before anything is validated, and a requirement the sandbox does not meet, or a line the standard refuses, makes the verdict `is_valid: false` with one item per line, whose `source` is `requirements.txt` and whose `line` is the line's number-- `read_scope` (string, optional): **Pipelex-API extension.** The scope of the blob store a hash entry of `files` resolves in, as a run's `read_scope`; omitted, the caller's own id is the scope — see [Sending files by hash](pipe-run.md#sending-files-by-hash)+- `read_scope` (string, optional): **Pipelex-API extension.** The scope of the blob store a hash entry of `files` resolves in, as a run's `read_scope`; omitted, the caller's own id is the scope — see [Sending files by hash](pipe-run.md#sending-files-by-hash). Only a validation carrying it records the tree it read in the blob store, so a dry run without one leaves nothing stored- `allow_signatures` (boolean, optional, default `false`): controls only the **sweep mechanics** for `PipeSignature` placeholders — whether signature pipes are mock-run during the dry-run sweep and therefore listed in `validated_pipes`. It does **not** change the verdict: an unimplemented signature is never a rejection, it is a *runnability fact* reported via `pending_signatures` + `is_runnable` in both modes- `mthds_sources` (list[str] | null, optional): per-file sources, parallel to `mthds_contents` — see [Sourcing submitted files](#sourcing-submitted-files). When present it must match `mthds_contents` in length (a mismatch is a 422 request error), and it accompanies `mthds_contents` alone, since a tree's files are named by their tree paths- `resources` (object | null, optional): **Pipelex-API extension.** The files the bundle's steps read, such as a `PipeDocGen` step's `template_file`, as a map from the path the step names to the file's bytes in standard base64 — see [Sending the files the steps read](#sending-the-files-the-steps-read-resources). It accompanies `mthds_contents` or `files`, whose tree each file joins; beside `method_ref` it is a 422diff --git a/docs/errors/platform-and-tooling.md b/docs/errors/platform-and-tooling.mdindex 437ac9982..2486727d5 100644--- a/docs/errors/platform-and-tooling.md+++ b/docs/errors/platform-and-tooling.md@@ -45,6 +45,7 @@ own page. Classes are grouped by subsystem.- [`RemoteFileFetchError`](remote-file-fetch-error.md) — Remote file could not be fetched- [`SecretNotFoundError`](secret-not-found-error.md) — Secret not found- [`SsrfBlockedError`](ssrf-blocked-error.md) — Outbound request blocked (SSRF guard)+- [`StorageChecksumMismatchError`](storage-checksum-mismatch-error.md) — Storage checksum mismatch- [`StorageConfigError`](storage-config-error.md) — Storage config- [`StorageError`](storage-error.md) — Storage error- [`StorageFileNotFoundError`](storage-file-not-found-error.md) — Storage file not founddiff --git a/docs/errors/storage-checksum-mismatch-error.md b/docs/errors/storage-checksum-mismatch-error.mdnew file mode 100644index 000000000..4a8610190--- /dev/null+++ b/docs/errors/storage-checksum-mismatch-error.md@@ -0,0 +1,21 @@+---+title: "Storage checksum mismatch"+description: "Reference for the `StorageChecksumMismatchError` Pipelex error class."+---++<!-- pipelex:generated -->++# Storage checksum mismatch++Raised when the bytes a create-only write was handed do not hash to the checksum it was handed with them.++| Field | Value |+|---|---|+| `error_type` | `StorageChecksumMismatchError` |+| `title` | Storage checksum mismatch |+| `type_uri` | `https://docs.pipelex.com/latest/errors/storage-checksum-mismatch-error/` |+| `error_domain` | _(inherited from parent)_ |+| Defined in | `pipelex.tools.storage.exceptions` |+| Parent class | [`StorageError`](storage-error.md) |++[Back to Error Reference](index.md)diff --git a/docs/under-the-hood/storage-provider-plugins.md b/docs/under-the-hood/storage-provider-plugins.mdindex a9a1584d6..4dd49c842 100644--- a/docs/under-the-hood/storage-provider-plugins.md+++ b/docs/under-the-hood/storage-provider-plugins.md@@ -147,7 +147,7 @@ The duplicate detection is the same fail-loud `_add` helper the inference/orchesA third-party storage plugin is a distribution that:-1. implements a `StorageProviderAbstract` subclass — the three hooks `_load_with_metadata`, `_store`, and `public_url` — deferring any SDK import into those methods (import-light); `_store` publishes the bytes whole or not at all, never leaving an object cut short under its key, and a provider that can read a byte range or an object's size without its bytes also overrides `_load_head` and `_load_size`, whose defaults load the whole object;+1. implements a `StorageProviderAbstract` subclass — the three hooks `_load_with_metadata`, `_store`, and `public_url` — deferring any SDK import into those methods (import-light); `_store` publishes the bytes whole or not at all, never leaving an object cut short under its key, and a provider that can read a byte range or an object's size without its bytes also overrides `_load_head` and `_load_size`, whose defaults load the whole object, and one that can create an object only when its key is free also overrides `_store_if_absent` (see [Create-only writes](#create-only-writes));2. defines a plugin class (`name`, `targets_api`, `register`) whose `register` calls `add_storage_provider(method="<token>", factory=...)` — and nothing else;3. advertises itself under the `pipelex.plugins.kernel` entry-point group — a storage provider is kernel-layer, and the group is how a plugin declares that (see [Inference Backend Plugins](inference-backend-plugins.md#shipping-it-as-an-out-of-tree-plugin) for what each group means and what happens if you pick the wrong one; the pre-split `pipelex.plugins` group is retired and now fails startup):@@ -161,6 +161,12 @@ Installing the distribution makes the method selectable (`runtime.storage.methodUse `pipelex plugins list` to see every discovered plugin, the entry-point group it was found under, what each contributed, and its denylist state. The **Group** column is the first thing to read when a plugin is missing: a built-in shows `—`, and an external plugin that resolved to the wrong layer shows it there.+### Create-only writes++`store_if_absent(data=…, key=…, content_type=…, checksum_sha256_hex=…)` creates an object only when its key holds none, and answers whether this call created it: an object already there is never replaced, and the answer is then `False`. With a checksum, the bytes are checked against it before anything is written, a mismatch raising `StorageChecksumMismatchError`, and the provider sends it on when its storage can check it. The API server's blob store writes every blob and tree listing this way, so a bucket refusing unconditional writes under those prefixes refuses none of them.++Each built-in provider makes the condition atomic in its storage: S3 sends `If-None-Match: *` with the SHA-256 as `x-amz-checksum-sha256` and reads a `412` as the key held, and on a `409`, which S3 answers while another write or delete of the key is in flight, sends the write again after a short pause, a bounded number of times, failing once the conflict outlasts them; GCS uploads on generation 0; the local provider writes a temporary file and hard-links it to the key, which fails when the name is taken, and fails loudly when something other than a file is there or a file stands where one of the key's folders should be; the in-memory one checks its dict. A provider that does not override `_store_if_absent`, such as an external plugin written before it existed, keeps working through the default, which looks the key up with `_load_size` and then calls `_store`, so two writers racing on one free key may both write, which a caller keying objects by their content can live with since both write the same bytes, but which a storage refusing unconditional writes would refuse.+### A provider is not the tenant boundaryA provider reads any key it is handed with the process's own credentials, and it should: it has no notion of whose run asked. On a host serving several tenants, what bounds a run's reads is the **read scope** the host passes with the run, which the content-generation leaves and the input seam check before they call a provider. A key outside that prefix, and any local path, is refused there, so a provider never sees it. A self-hosted deployment serving one tenant passes no read scope and reads as before. See [Distributed Content Generation](distributed-content-generation.md#what-a-leaf-may-read-the-read-scope) for the rule and where it runs.diff --git a/pipelex/pipeline/pipeline_response.py b/pipelex/pipeline/pipeline_response.pyindex 53ebc9a1c..7a85e3580 100644--- a/pipelex/pipeline/pipeline_response.py+++ b/pipelex/pipeline/pipeline_response.py@@ -3,6 +3,7 @@ from __future__ import annotationsfrom enum import StrEnumfrom mthds.protocol.models import RunResultExecute, RunResultStart+from pydantic import Fieldfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.runtime_bridge.serialization import resolve_main_stuff_root_key@@ -19,13 +20,20 @@ class RunState(StrEnum):ERROR = "ERROR"+CRATE_FINGERPRINT_DESCRIPTION = (+ "PIPELEX EXTENSION (not part of the MTHDS Protocol) — the fingerprint of the library crate the run's method was "+ "loaded into, the identity of its concepts and pipes, which changes with their meaning and not with their "+ "formatting or comments. Null when the run was built from no crate."+)++class PipelexRunResultExecute(RunResultExecute[PipeOutput]):"""Pipelex's `/execute` response — the completed run.The protocol's `RunResultExecute` carries `pipeline_run_id` + `pipe_output`- (both always present); `state`, `created_at`, `finished_at`, and- `main_stuff_name` are pipelex extension fields, documented by this- implementation's own API schema.+ (both always present); `state`, `created_at`, `finished_at`,+ `main_stuff_name` and `crate_fingerprint` are pipelex extension fields,+ documented by this implementation's own API schema."""created_at: str@@ -35,6 +43,7 @@ class PipelexRunResultExecute(RunResultExecute[PipeOutput]):# the working-memory root key the value lives under — or, when the output resolved absent, the# declared slot the absence record is keyed by (consumers branch on the record).main_stuff_name: str+ crate_fingerprint: str | None = Field(default=None, description=CRATE_FINGERPRINT_DESCRIPTION)@classmethoddef from_pipe_output(@@ -45,6 +54,7 @@ class PipelexRunResultExecute(RunResultExecute[PipeOutput]):created_at: str = "",state: RunState = RunState.COMPLETED,finished_at: str | None = None,+ crate_fingerprint: str | None = None,) -> PipelexRunResultExecute:return cls(pipeline_run_id=pipeline_run_id,@@ -53,6 +63,7 @@ class PipelexRunResultExecute(RunResultExecute[PipeOutput]):finished_at=finished_at,pipe_output=pipe_output,main_stuff_name=resolve_main_stuff_root_key(pipe_output=pipe_output),+ crate_fingerprint=crate_fingerprint,)@@ -60,10 +71,12 @@ class PipelexRunResultStart(RunResultStart):"""Pipelex's `/start` response — just the authoritative `pipeline_run_id`.The protocol's `RunResultStart` carries `pipeline_run_id` only; `state`,- `created_at`, `finished_at`, and `workflow_id` are pipelex extension fields.+ `created_at`, `finished_at`, `workflow_id` and `crate_fingerprint` are+ pipelex extension fields."""created_at: strstate: RunStatefinished_at: str | None = Noneworkflow_id: str | None = None+ crate_fingerprint: str | None = Field(default=None, description=CRATE_FINGERPRINT_DESCRIPTION)diff --git a/pipelex/pipeline/runner.py b/pipelex/pipeline/runner.pyindex 7419a4da1..2926a8513 100644--- a/pipelex/pipeline/runner.py+++ b/pipelex/pipeline/runner.py@@ -455,6 +455,7 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):created_at=created_at,state=RunState.COMPLETED,finished_at=finished_at,+ crate_fingerprint=pipe_job.job_metadata.run_metadata.crate_fingerprint,)@overridediff --git a/pipelex/tools/storage/exceptions.py b/pipelex/tools/storage/exceptions.pyindex 6bc51116c..176ea3d78 100644--- a/pipelex/tools/storage/exceptions.py+++ b/pipelex/tools/storage/exceptions.py@@ -24,6 +24,12 @@ class StorageInvalidKeyError(StorageError):"""Raised when a storage key is invalid (e.g., contains scheme prefix)."""+class StorageChecksumMismatchError(StorageError):+ """Raised when the bytes a create-only write was handed do not hash to the checksum it was handed with them."""++ _declared_title = "Storage checksum mismatch"++class StorageLocalError(StorageError):"""Raised when a local filesystem storage operation fails."""diff --git a/pipelex/tools/storage/gcp_storage_provider.py b/pipelex/tools/storage/gcp_storage_provider.pyindex 02494ac97..4701cb479 100644--- a/pipelex/tools/storage/gcp_storage_provider.py+++ b/pipelex/tools/storage/gcp_storage_provider.py@@ -259,6 +259,52 @@ class GcpStorageProvider(StorageProviderAbstract):"""await asyncio.to_thread(self._store_sync, data, key=key, content_type=content_type)+ def _store_if_absent_sync(self, *, data: bytes, key: str, content_type: str | None) -> bool:+ """Synchronous implementation of the create-only store for use with to_thread.++ Raises:+ StorageGcpError: If the GCS operation fails other than on the key already holding an object.+ """+ bucket = self._get_bucket()++ from google.api_core.exceptions import ( # type: ignore[import-untyped] # ruff: ignore[import-outside-top-level] - optional dependency, lazy import+ GoogleAPIError,+ PreconditionFailed,+ )++ try:+ blob = bucket.blob(key)+ # Generation 0 matches only an object that does not exist, so GCS creates it or answers 412.+ blob.upload_from_string(data, content_type=content_type, if_generation_match=0)+ except PreconditionFailed: # pyright: ignore[reportUnknownVariableType]+ return False+ except GoogleAPIError as exc: # pyright: ignore[reportUnknownVariableType]+ msg = f"Failed to store object to GCS: '{key}': {exc}"+ raise StorageGcpError(msg) from exc+ return True++ @override+ async def _store_if_absent(self, *, data: bytes, key: str, content_type: str | None, checksum_sha256_hex: str | None) -> bool:+ """Create a GCS object unless one exists at the key, with GCS checking the condition.++ The upload is conditional on the object's generation being 0, which only a key holding no object matches, so+ GCS creates it or refuses with `412`, the key already held. GCS checks no SHA-256: the bytes were checked+ against it before this call, and the client library checks the upload's own CRC32C or MD5 on the way.++ Args:+ data: The bytes to store, already checked against their checksum.+ key: Storage key (without scheme prefix).+ content_type: Optional MIME type for the object.+ checksum_sha256_hex: Checked before this call; GCS takes no SHA-256 checksum.++ Returns:+ True when this call created the object, False when the key already held one.++ Raises:+ StorageGcpError: If the GCS operation fails.+ """+ return await asyncio.to_thread(self._store_if_absent_sync, data=data, key=key, content_type=content_type)+def _make_public_url(self, key: str) -> str:"""Build a public URL for a GCS object.diff --git a/pipelex/tools/storage/in_memory_storage_provider.py b/pipelex/tools/storage/in_memory_storage_provider.pyindex 7486e9e94..593b04ebf 100644--- a/pipelex/tools/storage/in_memory_storage_provider.py+++ b/pipelex/tools/storage/in_memory_storage_provider.py@@ -66,6 +66,24 @@ class InMemoryStorageProvider(RootModel[InMemoryStorageRoot], StorageProviderAbs"""self.root[key] = data+ @override+ async def _store_if_absent(self, *, data: bytes, key: str, content_type: str | None, checksum_sha256_hex: str | None) -> bool:+ """Hold the bytes under `key` unless it holds some already, never replacing them.++ Args:+ data: The bytes to store, already checked against their checksum.+ key: Storage key (without scheme prefix).+ content_type: Ignored for in-memory storage.+ checksum_sha256_hex: Checked before this call; memory has no checksum of its own to send it to.++ Returns:+ True when this call stored the bytes, False when the key already held some.+ """+ if key in self.root:+ return False+ self.root[key] = data+ return True+@overrideasync def public_url(self, uri: str) -> str | None:"""In-memory storage cannot generate a public URL.diff --git a/pipelex/tools/storage/local_storage_provider.py b/pipelex/tools/storage/local_storage_provider.pyindex 1af6e967d..646682fad 100644--- a/pipelex/tools/storage/local_storage_provider.py+++ b/pipelex/tools/storage/local_storage_provider.py@@ -125,6 +125,23 @@ class LocalStorageProvider(StorageProviderAbstract):raise StorageLocalError(msg)return stat_result.st_size+ @staticmethod+ def _temporary_path_beside(*, file_path: Path) -> Path:+ return file_path.with_name(f".{file_path.name}.{uuid4().hex}.tmp")++ @staticmethod+ async def _write_temporary(*, temporary_path: Path, data: bytes) -> None:+ """Write the bytes to a temporary file beside their target, creating its folders, and flush them to disk.++ Raises:+ OSError: If the filesystem write fails.+ """+ temporary_path.parent.mkdir(parents=True, exist_ok=True)+ async with aiofiles.open(temporary_path, "wb") as file_handle: # pyright: ignore[reportUnknownMemberType]+ await file_handle.write(data)+ await file_handle.flush()+ os.fsync(file_handle.fileno())+@overrideasync def _store(self, data: bytes, *, key: str, content_type: str | None) -> None:"""Store bytes to a file, published whole or not at all.@@ -144,16 +161,10 @@ class LocalStorageProvider(StorageProviderAbstract):StorageLocalError: If the filesystem write fails (e.g. disk full, permission denied)."""file_path = self._validate_key(key)- temporary_path = file_path.with_name(f".{file_path.name}.{uuid4().hex}.tmp")+ temporary_path = self._temporary_path_beside(file_path=file_path)try:- # Create parent directories if they don't exist- file_path.parent.mkdir(parents=True, exist_ok=True)-- async with aiofiles.open(temporary_path, "wb") as file_handle: # pyright: ignore[reportUnknownMemberType]- await file_handle.write(data)- await file_handle.flush()- os.fsync(file_handle.fileno())+ await self._write_temporary(temporary_path=temporary_path, data=data)temporary_path.replace(file_path)except OSError as exc:msg = f"Failed to write file '{key}': {exc}"@@ -163,6 +174,56 @@ class LocalStorageProvider(StorageProviderAbstract):with contextlib.suppress(OSError):temporary_path.unlink(missing_ok=True)+ @override+ async def _store_if_absent(self, *, data: bytes, key: str, content_type: str | None, checksum_sha256_hex: str | None) -> bool:+ """Create a file unless one exists at the key, published whole or not at all, and never over another.++ The bytes are written to a temporary file beside the target and flushed to disk, as `_store` writes them, then+ hard-linked to the target, which the filesystem creates only when the name is free, atomically: of two writers+ of one key, exactly one creates it, and neither replaces a file already there. A reader never sees a file cut+ short. The temporary file is removed either way.++ Args:+ data: The bytes to store, already checked against their checksum.+ key: Storage key (relative path, without scheme prefix).+ content_type: Ignored for local storage.+ checksum_sha256_hex: Checked before this call; a file has no checksum of its own to send it to.++ Returns:+ True when this call created the file, False when the key already held one.++ Raises:+ StorageInvalidUriError: If the key is invalid.+ StorageLocalError: If the filesystem write fails, including on a filesystem that cannot make a hard link, or+ when the key names something that is not a file, or a path through a file.+ """+ file_path = self._validate_key(key)+ temporary_path = self._temporary_path_beside(file_path=file_path)++ created: bool+ try:+ await self._write_temporary(temporary_path=temporary_path, data=data)+ # Only the link reads an existing name as the key held: the same error while preparing the temporary file,+ # from a file standing where a folder of the key should be, is a failure like any other.+ try:+ file_path.hardlink_to(temporary_path)+ except FileExistsError:+ created = False+ else:+ created = True+ if not created and not file_path.is_file():+ msg = f"Failed to create file '{key}': something that is not a file is there"+ raise StorageLocalError(msg)+ except OSError as exc:+ msg = f"Failed to create file '{key}': {exc}"+ raise StorageLocalError(msg) from exc+ finally:+ # The target is its own link once created, and a write that failed leaves the temporary file behind:+ # removing it is best effort.+ with contextlib.suppress(OSError):+ temporary_path.unlink(missing_ok=True)+ return created+@overrideasync def public_url(self, uri: str) -> str:"""Return a file:// URI for this storage URI.diff --git a/pipelex/tools/storage/s3_storage_provider.py b/pipelex/tools/storage/s3_storage_provider.pyindex 87ab659cc..7ac3e27e9 100644--- a/pipelex/tools/storage/s3_storage_provider.py+++ b/pipelex/tools/storage/s3_storage_provider.py@@ -1,4 +1,6 @@+import base64import importlib.util+from asyncio import sleepfrom typing import Anyfrom urllib.parse import quote@@ -11,6 +13,23 @@ from pipelex.tools.storage.exceptions import ()from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract, StoredData+# What S3 answers a conditional write whose condition fails: `412` when the key holds an object (`If-None-Match: *`),+# `409 ConditionalRequestConflict` when another conditional write to the same key is in flight.+_PRECONDITION_FAILED_CODES = frozenset({"412", "PreconditionFailed"})+_CONDITIONAL_CONFLICT_CODES = frozenset({"409", "ConditionalRequestConflict"})+# S3 documents a `409` on a conditional write as retryable: the write is sent again after each of these pauses, and a+# conflict still answered after the last one is an error.+CONDITIONAL_CONFLICT_RETRY_DELAYS_SECONDS: tuple[float, ...] = (0.1, 0.25, 0.5, 1.0, 2.0)+++def checksum_sha256_header_value(*, sha256_hex: str) -> str:+ """The `x-amz-checksum-sha256` value of bytes whose SHA-256 is `sha256_hex`: the raw digest in base64.++ Raises:+ ValueError: `sha256_hex` is not hexadecimal.+ """+ return base64.b64encode(bytes.fromhex(sha256_hex)).decode("ascii")+class S3StorageProvider(StorageProviderAbstract):"""Storage provider implementation for AWS S3 storage.@@ -266,6 +285,79 @@ class S3StorageProvider(StorageProviderAbstract):msg = f"S3 backend error for key '{key}': {type(exc).__name__}"raise StorageS3Error(msg) from exc+ @override+ async def _store_if_absent(self, *, data: bytes, key: str, content_type: str | None, checksum_sha256_hex: str | None) -> bool:+ """Create an S3 object unless one exists at the key, with S3 checking the condition and the checksum.++ The PUT carries `If-None-Match: *`, so S3 writes it only when the key holds no object and answers `412`+ otherwise, which is the key already held. With a checksum, it carries the SHA-256 as `x-amz-checksum-sha256`,+ and S3 refuses a body whose hash differs, so the object holds exactly the bytes the checksum names.++ A `409 ConditionalRequestConflict` means another operation on the key, a conditional write or a delete, was+ in flight, and S3's answer to it is to retry: the PUT is sent again after a short pause, a bounded number of+ times. The PUT is retried rather than the key looked up, because the other operation may leave the key free,+ when it fails or deletes, and a retried PUT tells every outcome apart: a `412` is the object the other write+ created, held, and a success is this call's own object.++ Args:+ data: The bytes to store, already checked against their checksum.+ key: Storage key (without scheme prefix).+ content_type: Optional MIME type for the object.+ checksum_sha256_hex: The SHA-256 of `data` in lowercase hexadecimal, sent for S3 to check, or None.++ Returns:+ True when this call created the object, False when the key already held one.++ Raises:+ StorageS3Error: If the S3 operation fails (any other ClientError, a `409` still answered once the retries+ ran out, or a BotoCoreError).+ """+ from botocore.exceptions import ( # ruff: ignore[import-outside-top-level] - optional dependency, lazy import+ BotoCoreError,+ ClientError,+ )++ session = self._get_session()+ client_config = self._get_client_config()++ put_params: dict[str, Any] = {+ "Bucket": self._bucket_name,+ "Key": key,+ "Body": data,+ "IfNoneMatch": "*",+ }+ if content_type:+ put_params["ContentType"] = content_type+ if checksum_sha256_hex is not None:+ put_params["ChecksumSHA256"] = checksum_sha256_header_value(sha256_hex=checksum_sha256_hex)++ retry_delays = CONDITIONAL_CONFLICT_RETRY_DELAYS_SECONDS+ conditional_conflict: ClientError | None = None+ async with session.create_client(**client_config) as client:+ for index_attempt in range(len(retry_delays) + 1):+ if index_attempt > 0:+ await sleep(retry_delays[index_attempt - 1])+ try:+ await client.put_object(**put_params)+ except client.exceptions.NoSuchBucket as exc:+ msg = f"Bucket not found in S3: '{self._bucket_name}'"+ raise StorageS3Error(msg) from exc+ except ClientError as exc:+ error_code = (exc.response.get("Error") or {}).get("Code", "Unknown")+ if error_code in _PRECONDITION_FAILED_CODES:+ return False+ if error_code not in _CONDITIONAL_CONFLICT_CODES:+ msg = f"S3 ClientError ({error_code}) for key '{key}'"+ raise StorageS3Error(msg) from exc+ conditional_conflict = exc+ continue+ except BotoCoreError as exc:+ msg = f"S3 backend error for key '{key}': {type(exc).__name__}"+ raise StorageS3Error(msg) from exc+ return True+ msg = f"S3 ClientError (ConditionalRequestConflict) for key '{key}' on each of {len(retry_delays) + 1} attempts"+ raise StorageS3Error(msg) from conditional_conflict+def _make_public_url(self, key: str) -> str:"""Build an unsigned public URL for an S3 object, on the same host and path a signed one would name.diff --git a/pipelex/tools/storage/storage_provider_abstract.py b/pipelex/tools/storage/storage_provider_abstract.pyindex 6eea7c643..8d31eae39 100644--- a/pipelex/tools/storage/storage_provider_abstract.py+++ b/pipelex/tools/storage/storage_provider_abstract.py@@ -1,7 +1,8 @@+import hashlibfrom abc import ABC, abstractmethodfrom typing import NamedTuple-from pipelex.tools.storage.exceptions import StorageFileNotFoundError, StorageInvalidKeyError+from pipelex.tools.storage.exceptions import StorageChecksumMismatchError, StorageFileNotFoundError, StorageInvalidKeyErrorPIPELEX_STORAGE_SCHEME = "pipelex-storage://"@@ -177,6 +178,68 @@ class StorageProviderAbstract(ABC):content_type: Optional MIME type for the data."""+ async def store_if_absent(+ self,+ *,+ data: bytes,+ key: str,+ content_type: str | None = None,+ checksum_sha256_hex: str | None = None,+ ) -> bool:+ """Create the object at `key` unless one exists there, and say whether this call created it.++ A create-only write never replaces an object: when the key already holds one, nothing is written and the+ answer is False, whatever the object holds. With `checksum_sha256_hex`, the bytes are checked against it+ before anything is sent, and a provider whose storage can check a write's checksum itself sends it too, so+ the object holds exactly the bytes the checksum names (S3 checks `x-amz-checksum-sha256` against the body it+ receives).++ Args:+ data: The bytes to store.+ key: Storage key (without scheme prefix).+ content_type: Optional MIME type for the data (used by cloud providers).+ checksum_sha256_hex: The SHA-256 of `data` in lowercase hexadecimal, or None to send no checksum.++ Returns:+ True when this call created the object, False when the key already held one.++ Raises:+ StorageInvalidKeyError: If the key includes the scheme prefix.+ StorageChecksumMismatchError: If `data` does not hash to `checksum_sha256_hex`.+ """+ self._add_scheme(key)+ if checksum_sha256_hex is not None and hashlib.sha256(data).hexdigest() != checksum_sha256_hex:+ msg = f"The bytes to store under '{key}' do not hash to the checksum {checksum_sha256_hex!r} given with them: nothing was stored."+ raise StorageChecksumMismatchError(msg)+ return await self._store_if_absent(data=data, key=key, content_type=content_type, checksum_sha256_hex=checksum_sha256_hex)++ async def _store_if_absent(self, *, data: bytes, key: str, content_type: str | None, checksum_sha256_hex: str | None) -> bool:+ """Create the object at `key` unless one exists there, by key.++ This default looks the key up, then stores the bytes when it holds nothing, so a provider that cannot make a+ write conditional, an external storage plugin included, keeps working. Two writers racing on one free key may+ then both store, the last one winning, which a caller keying objects by their content, as a blob store does,+ can live with, since both write the same bytes. A provider that can create an object only when its key is+ free overrides it, and a storage that refuses unconditional writes needs that override.++ Args:+ data: The bytes to store, already checked against `checksum_sha256_hex`.+ key: Storage key (without scheme prefix).+ content_type: Optional MIME type for the data.+ checksum_sha256_hex: The SHA-256 of `data`, or None. This default sends it nowhere.++ Returns:+ True when this call stored the object, False when the key already held one.+ """+ # A plain store has nowhere to send a checksum: `store_if_absent` checked the bytes against it already.+ _ = checksum_sha256_hex+ try:+ await self._load_size(key)+ except StorageFileNotFoundError:+ await self._store(data=data, key=key, content_type=content_type)+ return True+ return False+@abstractmethodasync def public_url(self, uri: str) -> str | None:"""Return human-readable link for this URI.diff --git a/tests/data/errors/error_identity.txt b/tests/data/errors/error_identity.txtindex 46e2030b4..dd46cbfe0 100644--- a/tests/data/errors/error_identity.txt+++ b/tests/data/errors/error_identity.txt@@ -320,6 +320,7 @@ SearchModelNotFoundError | Search model not found | https://docs.pipelex.com/latSecretNotFoundError | Secret not found | https://docs.pipelex.com/latest/errors/secret-not-found-error/SecurityError | Security policy violation | https://docs.pipelex.com/latest/errors/security-error/SsrfBlockedError | Outbound request blocked (SSRF guard) | https://docs.pipelex.com/latest/errors/ssrf-blocked-error/+StorageChecksumMismatchError | Storage checksum mismatch | https://docs.pipelex.com/latest/errors/storage-checksum-mismatch-error/StorageConfigError | Storage config | https://docs.pipelex.com/latest/errors/storage-config-error/StorageDeliveryError | Storage delivery | https://docs.pipelex.com/latest/errors/storage-delivery-error/StorageError | Storage error | https://docs.pipelex.com/latest/errors/storage-error/diff --git a/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.py b/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.pyindex 21c53a019..8a5a14b6d 100644--- a/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.py+++ b/tests/unit/pipelex/tools/storage/test_gcp_storage_provider.py@@ -8,6 +8,7 @@ from pytest_mock import MockerFixturefrom pipelex.tools.storage.exceptions import (StorageFileNotFoundError,StorageGcpCredentialsError,+ StorageGcpError,StorageInvalidKeyError,)from pipelex.tools.storage.gcp_storage_provider import GCS_SIGNED_URL_VERSION, GcpStorageProvider@@ -346,3 +347,42 @@ class TestGcpStorageProvider:with pytest.raises(StorageFileNotFoundError, match=r"missing/file\.pdf"):await gcp_provider_no_signed_urls.load_size(uri=f"{PIPELEX_STORAGE_SCHEME}missing/file.pdf")++ async def test_store_if_absent_uploads_only_over_no_object(+ self,+ gcp_provider_no_signed_urls: GcpStorageProvider,+ mock_gcp_storage: dict[str, Any],+ ) -> None:+ """Generation 0 matches only a key holding no object, so GCS itself refuses to replace one."""+ created = await gcp_provider_no_signed_urls.store_if_absent(+ data=b"blob bytes", key="scope/blobs/one", content_type="application/octet-stream"+ )++ assert created is True+ mock_gcp_storage["bucket"].blob.assert_called_with("scope/blobs/one")+ mock_gcp_storage["blob"].upload_from_string.assert_called_once_with(+ b"blob bytes", content_type="application/octet-stream", if_generation_match=0+ )++ async def test_store_if_absent_over_a_held_object_is_no_error(+ self,+ gcp_provider_no_signed_urls: GcpStorageProvider,+ mock_gcp_storage: dict[str, Any],+ ) -> None:+ from google.api_core.exceptions import PreconditionFailed # type: ignore[import-untyped] # ruff: ignore[import-outside-top-level]++ mock_gcp_storage["blob"].upload_from_string.side_effect = PreconditionFailed("conditionNotMet")++ assert await gcp_provider_no_signed_urls.store_if_absent(data=b"blob bytes", key="scope/blobs/one") is False++ async def test_store_if_absent_maps_other_failures(+ self,+ gcp_provider_no_signed_urls: GcpStorageProvider,+ mock_gcp_storage: dict[str, Any],+ ) -> None:+ from google.api_core.exceptions import Forbidden # type: ignore[import-untyped] # ruff: ignore[import-outside-top-level]++ mock_gcp_storage["blob"].upload_from_string.side_effect = Forbidden("denied")++ with pytest.raises(StorageGcpError, match="denied"):+ await gcp_provider_no_signed_urls.store_if_absent(data=b"blob bytes", key="scope/blobs/one")diff --git a/tests/unit/pipelex/tools/storage/test_s3_storage_provider.py b/tests/unit/pipelex/tools/storage/test_s3_storage_provider.pyindex 87a527b63..737f276c7 100644--- a/tests/unit/pipelex/tools/storage/test_s3_storage_provider.py+++ b/tests/unit/pipelex/tools/storage/test_s3_storage_provider.py@@ -1,3 +1,5 @@+import base64+import hashlibfrom typing import Anyimport pytest@@ -5,7 +7,7 @@ from botocore.exceptions import BotoCoreError, ClientError, EndpointConnectionErfrom pytest_mock import MockerFixturefrom pipelex.tools.storage.exceptions import StorageFileNotFoundError, StorageInvalidKeyError, StorageS3Error-from pipelex.tools.storage.s3_storage_provider import S3StorageProvider+from pipelex.tools.storage.s3_storage_provider import CONDITIONAL_CONFLICT_RETRY_DELAYS_SECONDS, S3StorageProvider, checksum_sha256_header_valuefrom pipelex.tools.storage.storage_provider_abstract import PIPELEX_STORAGE_SCHEME# Test constants@@ -542,3 +544,128 @@ class TestS3StorageProvider:mock_aiobotocore["client"].head_object = mocker.AsyncMock(side_effect=EndpointConnectionError(endpoint_url="https://s3.example.com"))with pytest.raises(StorageS3Error):await s3_provider_no_signed_urls.load_size(uri=f"{PIPELEX_STORAGE_SCHEME}test/file.pdf")++ async def test_store_if_absent_sends_the_condition_and_the_checksum(+ self,+ s3_provider_no_signed_urls: S3StorageProvider,+ mock_aiobotocore: dict[str, Any],+ ) -> None:+ """`If-None-Match: *` makes S3 refuse to replace an object, and the SHA-256 makes it refuse other bytes."""+ data = b"blob bytes"+ sha256 = hashlib.sha256(data).hexdigest()++ created = await s3_provider_no_signed_urls.store_if_absent(+ data=data, key="scope/blobs/one", content_type="application/octet-stream", checksum_sha256_hex=sha256+ )++ assert created is True+ mock_aiobotocore["client"].put_object.assert_called_once_with(+ Bucket=S3_TEST_BUCKET,+ Key="scope/blobs/one",+ Body=data,+ IfNoneMatch="*",+ ContentType="application/octet-stream",+ ChecksumSHA256=base64.b64encode(hashlib.sha256(data).digest()).decode("ascii"),+ )++ async def test_store_if_absent_without_a_checksum_sends_none(+ self,+ s3_provider_no_signed_urls: S3StorageProvider,+ mock_aiobotocore: dict[str, Any],+ ) -> None:+ assert await s3_provider_no_signed_urls.store_if_absent(data=b"bytes", key="scope/blobs/one") is True++ mock_aiobotocore["client"].put_object.assert_called_once_with(Bucket=S3_TEST_BUCKET, Key="scope/blobs/one", Body=b"bytes", IfNoneMatch="*")++ @pytest.mark.parametrize("error_code", ["412", "PreconditionFailed"])+ async def test_store_if_absent_over_a_held_object_is_no_error(+ self,+ mocker: MockerFixture,+ s3_provider_no_signed_urls: S3StorageProvider,+ mock_aiobotocore: dict[str, Any],+ error_code: str,+ ) -> None:+ held = ClientError({"Error": {"Code": error_code, "Message": "At least one of the pre-conditions you specified did not hold"}}, "PutObject")+ mock_aiobotocore["client"].put_object = mocker.AsyncMock(side_effect=held)++ assert await s3_provider_no_signed_urls.store_if_absent(data=b"bytes", key="scope/blobs/one") is False++ @pytest.mark.parametrize(+ ("final_answer", "expected_created"),+ [+ (ClientError({"Error": {"Code": "PreconditionFailed", "Message": "Precondition Failed"}}, "PutObject"), False),+ ({"ETag": '"created"'}, True),+ ],+ )+ async def test_store_if_absent_retries_a_conditional_conflict_until_s3_answers(+ self,+ mocker: MockerFixture,+ s3_provider_no_signed_urls: S3StorageProvider,+ mock_aiobotocore: dict[str, Any],+ final_answer: ClientError | dict[str, str],+ expected_created: bool,+ ) -> None:+ """A `409` is retried: a later `412` is the other write's object, held, and a later success is this call's own.++ The other operation may have failed or deleted the key, leaving it free, so the PUT is sent again rather than+ the key looked up.+ """+ mocked_sleep = mocker.patch("pipelex.tools.storage.s3_storage_provider.sleep", new_callable=mocker.AsyncMock)+ conflict = ClientError({"Error": {"Code": "ConditionalRequestConflict", "Message": "Conflict"}}, "PutObject")+ mock_aiobotocore["client"].put_object = mocker.AsyncMock(side_effect=[conflict, conflict, final_answer])+ mock_aiobotocore["client"].head_object = mocker.AsyncMock()++ created = await s3_provider_no_signed_urls.store_if_absent(+ data=b"bytes", key="scope/blobs/one", checksum_sha256_hex=hashlib.sha256(b"bytes").hexdigest()+ )++ assert created is expected_created+ assert mock_aiobotocore["client"].put_object.await_count == 3+ for put_call in mock_aiobotocore["client"].put_object.await_args_list:+ assert put_call.kwargs["IfNoneMatch"] == "*"+ assert put_call.kwargs["ChecksumSHA256"] == checksum_sha256_header_value(sha256_hex=hashlib.sha256(b"bytes").hexdigest())+ assert [sleep_call.args for sleep_call in mocked_sleep.await_args_list] == [+ (delay,) for delay in CONDITIONAL_CONFLICT_RETRY_DELAYS_SECONDS[:2]+ ]+ mock_aiobotocore["client"].head_object.assert_not_awaited()++ async def test_store_if_absent_whose_conflicts_outlast_the_retries_is_an_error(+ self,+ mocker: MockerFixture,+ s3_provider_no_signed_urls: S3StorageProvider,+ mock_aiobotocore: dict[str, Any],+ ) -> None:+ mocked_sleep = mocker.patch("pipelex.tools.storage.s3_storage_provider.sleep", new_callable=mocker.AsyncMock)+ conflict = ClientError({"Error": {"Code": "409", "Message": "Conflict"}}, "PutObject")+ mock_aiobotocore["client"].put_object = mocker.AsyncMock(side_effect=conflict)+ retry_delays = CONDITIONAL_CONFLICT_RETRY_DELAYS_SECONDS++ with pytest.raises(StorageS3Error, match="ConditionalRequestConflict") as exc_info:+ await s3_provider_no_signed_urls.store_if_absent(data=b"bytes", key="scope/blobs/one")++ assert exc_info.value.__cause__ is conflict+ assert mock_aiobotocore["client"].put_object.await_count == len(retry_delays) + 1+ assert [sleep_call.args for sleep_call in mocked_sleep.await_args_list] == [(delay,) for delay in retry_delays]+ assert sum(retry_delays) < 10++ async def test_store_if_absent_maps_other_errors(+ self,+ mocker: MockerFixture,+ s3_provider_no_signed_urls: S3StorageProvider,+ mock_aiobotocore: dict[str, Any],+ ) -> None:+ refused = ClientError({"Error": {"Code": "AccessDenied", "Message": "Access Denied"}}, "PutObject")+ mock_aiobotocore["client"].put_object = mocker.AsyncMock(side_effect=refused)+ with pytest.raises(StorageS3Error, match="AccessDenied"):+ await s3_provider_no_signed_urls.store_if_absent(data=b"bytes", key="scope/blobs/one")++ mock_aiobotocore["client"].put_object = mocker.AsyncMock(side_effect=NoCredentialsError())+ with pytest.raises(StorageS3Error, match="NoCredentialsError"):+ await s3_provider_no_signed_urls.store_if_absent(data=b"bytes", key="scope/blobs/one")++ async def test_checksum_header_value_is_the_raw_digest_in_base64(self) -> None:+ data = b"blob bytes"++ assert checksum_sha256_header_value(sha256_hex=hashlib.sha256(data).hexdigest()) == base64.b64encode(hashlib.sha256(data).digest()).decode(+ "ascii"+ )diff --git a/tests/unit/pipelex/tools/storage/test_storage_store_if_absent.py b/tests/unit/pipelex/tools/storage/test_storage_store_if_absent.pynew file mode 100644index 000000000..cbf186745--- /dev/null+++ b/tests/unit/pipelex/tools/storage/test_storage_store_if_absent.py@@ -0,0 +1,128 @@+import asyncio+import errno+import hashlib+from pathlib import Path++import pytest+from pytest_mock import MockerFixture+from typing_extensions import override++from pipelex.tools.storage.exceptions import StorageChecksumMismatchError, StorageFileNotFoundError, StorageInvalidKeyError, StorageLocalError+from pipelex.tools.storage.in_memory_storage_provider import InMemoryStorageProvider+from pipelex.tools.storage.local_storage_provider import LocalStorageProvider+from pipelex.tools.storage.storage_provider_abstract import PIPELEX_STORAGE_SCHEME, StorageProviderAbstract, StoredData++PAYLOAD = b"the bytes a blob holds"+OTHER_PAYLOAD = b"other bytes, under the same key"+KEY = "scope/blobs/one"+++class _PlainProvider(StorageProviderAbstract):+ """A provider implementing only the abstract reads and writes, as an external plugin may."""++ def __init__(self) -> None:+ self.objects: dict[str, bytes] = {}++ @override+ async def _load_with_metadata(self, key: str) -> StoredData:+ if key not in self.objects:+ msg = f"File not found: '{key}'"+ raise StorageFileNotFoundError(msg)+ return StoredData(data=self.objects[key], mime_type=None)++ @override+ async def _store(self, data: bytes, *, key: str, content_type: str | None) -> None:+ self.objects[key] = data++ @override+ async def public_url(self, uri: str) -> str | None:+ return None+++def _providers(*, tmp_path: Path) -> list[StorageProviderAbstract]:+ return [InMemoryStorageProvider(), LocalStorageProvider(root_path=tmp_path), _PlainProvider()]++[email protected](loop_scope="class")+class TestStorageStoreIfAbsent:+ async def test_a_free_key_is_created_and_a_held_one_is_never_replaced(self, tmp_path: Path) -> None:+ for provider in _providers(tmp_path=tmp_path):+ assert await provider.store_if_absent(data=PAYLOAD, key=KEY) is True+ assert await provider.store_if_absent(data=OTHER_PAYLOAD, key=KEY) is False++ assert await provider.load(uri=f"{PIPELEX_STORAGE_SCHEME}{KEY}") == PAYLOAD++ async def test_bytes_matching_their_checksum_are_created(self, tmp_path: Path) -> None:+ for provider in _providers(tmp_path=tmp_path):+ created = await provider.store_if_absent(data=PAYLOAD, key=KEY, checksum_sha256_hex=hashlib.sha256(PAYLOAD).hexdigest())++ assert created is True+ assert await provider.load(uri=f"{PIPELEX_STORAGE_SCHEME}{KEY}") == PAYLOAD++ async def test_bytes_not_matching_their_checksum_are_refused_before_any_write(self, tmp_path: Path) -> None:+ for provider in _providers(tmp_path=tmp_path):+ with pytest.raises(StorageChecksumMismatchError, match="do not hash to the checksum"):+ await provider.store_if_absent(data=PAYLOAD, key=KEY, checksum_sha256_hex=hashlib.sha256(OTHER_PAYLOAD).hexdigest())++ with pytest.raises(StorageFileNotFoundError):+ await provider.load_size(uri=f"{PIPELEX_STORAGE_SCHEME}{KEY}")++ async def test_a_key_carrying_the_scheme_is_refused(self, tmp_path: Path) -> None:+ for provider in _providers(tmp_path=tmp_path):+ with pytest.raises(StorageInvalidKeyError):+ await provider.store_if_absent(data=PAYLOAD, key=f"{PIPELEX_STORAGE_SCHEME}{KEY}")++ async def test_of_two_local_writers_of_one_key_exactly_one_creates_it(self, tmp_path: Path) -> None:+ provider = LocalStorageProvider(root_path=tmp_path)++ outcomes = await asyncio.gather(+ provider.store_if_absent(data=PAYLOAD, key=KEY),+ provider.store_if_absent(data=OTHER_PAYLOAD, key=KEY),+ )++ assert sorted(outcomes) == [False, True]+ held = (tmp_path / KEY).read_bytes()+ assert held == (PAYLOAD if outcomes[0] else OTHER_PAYLOAD)+ assert [path.name for path in (tmp_path / KEY).parent.iterdir()] == ["one"]++ async def test_a_local_create_leaves_no_temporary_file(self, tmp_path: Path) -> None:+ provider = LocalStorageProvider(root_path=tmp_path)++ await provider.store_if_absent(data=PAYLOAD, key=KEY)+ await provider.store_if_absent(data=OTHER_PAYLOAD, key=KEY)++ assert [path.name for path in (tmp_path / KEY).parent.iterdir()] == ["one"]++ async def test_a_filesystem_refusing_the_hard_link_is_a_local_storage_error(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """A filesystem that cannot make a hard link cannot create a file only when its name is free: the write fails loudly."""+ provider = LocalStorageProvider(root_path=tmp_path)+ mocker.patch.object(Path, "hardlink_to", autospec=True, side_effect=OSError(errno.EPERM, "Operation not permitted"))++ with pytest.raises(StorageLocalError, match="Operation not permitted"):+ await provider.store_if_absent(data=PAYLOAD, key=KEY)++ assert not (tmp_path / KEY).exists()+ assert list((tmp_path / KEY).parent.iterdir()) == []++ async def test_a_key_through_a_file_is_a_local_storage_error_not_a_key_held(self, tmp_path: Path) -> None:+ """A file standing where a folder of the key should be fails the temporary file's folder, which is no key held."""+ provider = LocalStorageProvider(root_path=tmp_path)+ (tmp_path / "scope").write_bytes(b"a file where a folder should be")++ with pytest.raises(StorageLocalError, match="Failed to create file 'scope/blobs/one'"):+ await provider.store_if_absent(data=PAYLOAD, key="scope/blobs/one")++ with pytest.raises(StorageLocalError, match="Failed to create file 'scope/one'"):+ await provider.store_if_absent(data=PAYLOAD, key="scope/one")++ assert (tmp_path / "scope").read_bytes() == b"a file where a folder should be"++ async def test_a_folder_at_the_key_is_a_local_storage_error_not_a_key_held(self, tmp_path: Path) -> None:+ provider = LocalStorageProvider(root_path=tmp_path)+ (tmp_path / KEY).mkdir(parents=True)++ with pytest.raises(StorageLocalError, match="not a file"):+ await provider.store_if_absent(data=PAYLOAD, key=KEY)++ assert (tmp_path / KEY).is_dir()+ assert [path.name for path in (tmp_path / KEY).parent.iterdir()] == ["one"]