Skip to content

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/Docgen-filename-not-path-safe · L-261012-05877c (#1424)

Louis Choquel9887a5c5b5f1
diff --git a/.test_durations b/.test_durations
index 540bbdd2e..a10e049bb 100644
--- a/.test_durations
+++ b/.test_durations
@@ -12269,12 +12269,6 @@
"tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_pipe_doc_gen_blueprint.py::TestPipeDocGenBlueprint::test_the_refusal_of_a_template_file_outside_its_bundle_never_repeats_it[../srv/methods/invoice.docx]": 0.0007,
"tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_pipe_doc_gen_blueprint.py::TestPipeDocGenBlueprint::test_the_refusal_of_a_template_file_outside_its_bundle_never_repeats_it[/srv/methods/invoice.docx]": 0.0011,
"tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_pipe_doc_gen_blueprint.py::TestPipeDocGenBlueprint::test_the_refusal_of_a_template_file_outside_its_bundle_never_repeats_it[C:/srv/methods/invoice.docx]": 0.001,
- "tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_safe_filename.py::TestSafeFilename::test_the_rendered_name_becomes_one_safe_segment[ ../../etc/passwd -etc-passwd.pdf]": 0.0003,
- "tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_safe_filename.py::TestSafeFilename::test_the_rendered_name_becomes_one_safe_segment[-render_invoice.pdf]": 0.0003,
- "tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_safe_filename.py::TestSafeFilename::test_the_rendered_name_becomes_one_safe_segment[...-render_invoice.pdf]": 0.0008,
- "tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_safe_filename.py::TestSafeFilename::test_the_rendered_name_becomes_one_safe_segment[invoice INV/2026:0142-invoice-INV-2026-0142.pdf]": 0.0004,
- "tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_safe_filename.py::TestSafeFilename::test_the_rendered_name_becomes_one_safe_segment[invoice-INV-2026-0142-invoice-INV-2026-0142.pdf]": 0.0705,
- "tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_safe_filename.py::TestSafeFilename::test_the_rendered_name_becomes_one_safe_segment[report.pdf-report.pdf]": 0.0009,
"tests/unit/pipelex/pipe_operators/pipe_extract/test_pipe_extract_blueprint.py::TestPipeExtractBlueprint::test_valid_blueprints[valid_image_input-blueprint0]": 0.7553,
"tests/unit/pipelex/pipe_operators/pipe_extract/test_pipe_extract_blueprint.py::TestPipeExtractBlueprint::test_valid_blueprints[valid_image_with_captions-blueprint4]": 0.0008,
"tests/unit/pipelex/pipe_operators/pipe_extract/test_pipe_extract_blueprint.py::TestPipeExtractBlueprint::test_valid_blueprints[valid_image_with_max_page_images-blueprint2]": 0.0007,
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 504da3d50..645223c79 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog
+## [Unreleased]
+
+### Fixed
+
+- **A `PipeDocGen` document's name is one the hosted API serves**: a rendered `filename` holding a letter outside ASCII or a dot, such as `Zoë Ångström — Q3.2026`, was stored under a `pipelex-storage://` URI the hosted API refuses to serve, so the completed document could never be downloaded. The name is now spelled in ASCII where it can be, accents dropped and letters such as `ø`, `æ`, `ł`, `ß`, `đ`, `þ`, `œ` and `ı` transliterated, every other character, an inner dot included, becomes a hyphen, repeated separators collapse, and a name that leaves nothing, one written wholly in Greek, Cyrillic, Han or Arabic for one, falls back to the pipe's code, so that name is `Zoe-Angstrom-Q3-2026.pdf`, on a local run as on a hosted one.
+- **The files a run stores from what it was sent are named and typed for their readers**: the copy of a `.docx`, `.xlsx` or `.pptx` template file a run stores under `assets/bundle/` before it is dispatched now carries its Office Open XML content type, named in code, where a host whose `mimetypes` table did not know the extension stored it as `binary/octet-stream`, and its name follows the rule a document's name follows, so `Modèle trimestriel.v2.docx` is stored as `Modele-trimestriel-v2.docx`. A local file input stored under `assets/` that its bytes and type do not identify keeps its own suffix only when it is plainly letters and digits, and is stored as `.bin` otherwise.
+- **The refusals of the files sent with a bundle say a retry cannot succeed**: `BundleResourceNotNamedError`, `BundleResourcesTooLargeError` and `BundleResourcePathError` now carry `retryable: false` in their error report, and so in the API server's problem document, as `InvalidResourcePath` already did. A `PipelexError` subclass declares it with the new class attribute `retryable`, which its report carries and the generated error reference shows; a wrapper raised from such an error inherits it, as it does `error_domain`.
+
## [v0.85.0] - 2026-10-12
### Highlights
diff --git a/api/tests/unit/test_bundle_resources_routes.py b/api/tests/unit/test_bundle_resources_routes.py
index 0c112a04e..5e9234d27 100644
--- a/api/tests/unit/test_bundle_resources_routes.py
+++ b/api/tests/unit/test_bundle_resources_routes.py
@@ -193,9 +193,12 @@ class TestBundleResourcesRoutes:
_stub_the_document_engine(mocker)
body = _contents_body(route=route, resources={_TEMPLATE_PATH: _b64(_TEMPLATE_BYTES), "templates/logo.png": _b64(b"png")})
- detail = _assert_problem(_build_client().post(route, json=body), status=422, error_type="BundleResourceNotNamedError")
+ response = _build_client().post(route, json=body)
+ detail = _assert_problem(response, status=422, error_type="BundleResourceNotNamedError")
assert "'templates/logo.png'" in detail
+ # A deterministic refusal of what the caller sent, as InvalidResourcePath is: the same request fails again.
+ assert response.json()["retryable"] is False
@pytest.mark.parametrize("route", ["/v1/validate", "/v1/execute", "/v1/pipe-io", "/v1/resolve", "/v1/codegen"])
def test_html_templates_over_the_load_stage_bound_are_refused_with_a_413_naming_the_limit(self, mocker: MockerFixture, route: str) -> None:
@@ -205,10 +208,12 @@ class TestBundleResourcesRoutes:
html_mthds = _INVOICE_MTHDS.replace('format = "docx"', 'format = "pdf"').replace(_TEMPLATE_PATH, "invoice.html")
body = _contents_body(route=route, resources={"invoice.html": _b64(b"x" * 1025)}, mthds=html_mthds)
- detail = _assert_problem(_build_client().post(route, json=body), status=413, error_type="BundleResourcesTooLargeError")
+ response = _build_client().post(route, json=body)
+ detail = _assert_problem(response, status=413, error_type="BundleResourcesTooLargeError")
assert "('invoice.html')" in detail
assert "1 KiB limit" in detail
+ assert response.json()["retryable"] is False
@pytest.mark.parametrize(
("path", "reason"),
diff --git a/docs/api-server/error-responses.md b/docs/api-server/error-responses.md
index 26ea40195..534514e3b 100644
--- a/docs/api-server/error-responses.md
+++ b/docs/api-server/error-responses.md
@@ -30,7 +30,7 @@ A failure response looks like this:
- `error_type` — stable class name of the originating error (`ValidateBundleError`, `EnvVarNotFoundError`, `WorkflowExecutionError`, …). The same identifier the `type` URI is derived from.
- `error_domain` — one of `input`, `config`, `runtime`. See [Status codes](#status-codes). Absent for domain-less pipelex errors (some pipelex tool errors, e.g. `EnvVarNotFoundError`, do not classify a domain — the HTTP status still defaults to **500**).
-- `retryable` — whether retrying the same request can plausibly succeed. Always emitted for API-authored 4xx/5xx (always `false`). For pipelex-originated errors, present only when the source error populates it — `true` only when the originating error explicitly classifies itself as transient (e.g. inference provider rate limits); absent on pipelex errors that don't set it (e.g. `EnvVarNotFoundError`, `PipelexConfigError`).
+- `retryable` — whether retrying the same request can plausibly succeed. Always emitted for API-authored 4xx/5xx (always `false`). For pipelex-originated errors, present only when the source error populates it — `true` only when the originating error explicitly classifies itself as transient (e.g. inference provider rate limits), `false` when it declares itself a deterministic refusal of what the caller sent (e.g. `BundleResourceNotNamedError`, `BundleResourcesTooLargeError`, as for the API-authored `InvalidResourcePath`); absent on pipelex errors that don't set it (e.g. `EnvVarNotFoundError`, `PipelexConfigError`).
- `request_id` — server-correlated identifier for the request. Echoed from inbound `X-Request-ID` if provided, otherwise generated. Use this when reporting issues.
- `error_category` — finer classification when the originating error provides one (currently used by inference errors — see [`InferenceErrorCategory`](https://docs.pipelex.com/latest/errors/) upstream).
- `user_action` — structured suggestion of what the caller should do next, when the error can author one.
@@ -174,7 +174,7 @@ A pipe selection the server cannot make is an input **422** named for its failur
The 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`.
-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 `.html` template files that total more than the 512 KiB the files read when the method loads may carry a **413** `BundleResourcesTooLargeError`, on every route, the diagnostic ones included: both are the request's fault, not the bundle's.
+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 `.html` template files that total more than the 512 KiB the files read when the method loads may carry a **413** `BundleResourcesTooLargeError`, 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.
The HTTP status is the source of truth for success vs failure — there is no `success: true/false` field anywhere in the envelope.
diff --git a/docs/building-methods/pipes/pipe-operators/PipeDocGen.md b/docs/building-methods/pipes/pipe-operators/PipeDocGen.md
index 5cc4c2b14..5494b8cc4 100644
--- a/docs/building-methods/pipes/pipe-operators/PipeDocGen.md
+++ b/docs/building-methods/pipes/pipe-operators/PipeDocGen.md
@@ -82,7 +82,18 @@ To print the same invoice on the plugin's `pipelex-pdf`, the step names it: `mod
| `model` | string | The document engine that prints the file, a `doc_gen` model, alias or preset, such as `reportlab-pdf` or, with the plugin, `pipelex-pdf`. It defaults to the model deck's engine for the format and source. | No |
| `template` | string | An inline HTML and Jinja2 template, for `pdf` only. A `pdf` with a template is printed by the plugin. | No |
| `template_file` | string | A template file relative to the bundle's file, inside its bundle and written with forward slashes: `.html` for `pdf`, `.xlsx`, `.docx` or `.pptx`. An empty or absolute path, a `..` segment, a backslash and a colon are refused, the rule the files sent with a bundle are keyed by, so any template file can be sent with its bundle. Read beside the bundle when it is loaded from a directory, and from the files sent with it when it is loaded from a string. It excludes `template`. `pptx` requires one. | No |
-| `filename` | string | A Jinja expression over the inputs for the file's name, without its suffix, such as `invoice-{{ invoice.number }}`. It defaults to the pipe's code. | No |
+| `filename` | string | A Jinja expression over the inputs for the file's name, without its suffix, such as `invoice-{{ invoice.number }}`. It defaults to the pipe's code. The rendered name is made into one every storage reader serves, the hosted API's included, spelled in ASCII with hyphens for the rest: see [The file's name](#the-files-name). | No |
+
+### The file's name
+
+The document is stored, and downloaded, under its `filename` plus the format's suffix. A storage URI names it, and the hosted API serves a stored file only when its name is ASCII letters, digits, hyphens and underscores, one dot and the suffix, so the step makes every rendered name into one of those before it stores the file:
+
+- **Letters are spelled in ASCII where they can be.** Accents are dropped (`Bäckerei Müller` gives `Backerei-Muller`, `İstanbul` gives `Istanbul`), and the letters that carry no accent to drop are spelled as a reader would type them: `ø` as `o`, `æ` as `ae`, `œ` as `oe`, `ł` as `l`, `đ` and `ð` as `d`, `þ` as `th`, `ß` as `ss`, `ı` as `i`.
+- **Every other character becomes a hyphen**: a space, punctuation, a dot inside the name, and a letter of a script with no ASCII spelling here, such as Greek, Cyrillic, Han, Hangul, Arabic or Hebrew. A run of hyphens and underscores collapses into one, and none is kept at either end.
+- **A name already ending in the suffix keeps it once**: `report.pdf` stays `report.pdf`.
+- **The name is cut at 120 characters**, and a name that leaves nothing falls back to the pipe's code.
+
+So `Halden Brook Review Q3 2026 — Zoë Ångström · Ærøskøbing · Москва · 東京都` is stored as `Halden-Brook-Review-Q3-2026-Zoe-Angstrom-AEroskobing.docx`. Keep a name you want to read whole to Latin letters and digits.
### An LLM report as a PDF
@@ -139,7 +150,7 @@ When a bundle is sent as content rather than read from a directory, as it is thr
- **Every file sent must be one a step names.** A file no step reads is refused, so a misspelled key fails loudly rather than leaving its step without a template.
- **The files are checked like files on disk.** An `.html` template file is checked against the inputs when the method loads, and the engine's template check runs on an office template file at validation and in the dry run.
-A run that a remote orchestrator such as Temporal executes, a dry run included, stores each office template file in the run's storage before the run leaves the process, so the run carries a reference rather than the bytes, and the step reads the file back under the run's read scope, to print it or to check it. An HTML template file travels with the method, since it is read while the method loads, so the HTML template files sent with a bundle may total 512 KiB at most: keep images and fonts out of them, at URLs they reference.
+A run that a remote orchestrator such as Temporal executes, a dry run included, stores each office template file in the run's storage before the run leaves the process, so the run carries a reference rather than the bytes, and the step reads the file back under the run's read scope, to print it or to check it. The stored copy is named by the rule a document's name follows (see [The file's name](#the-files-name)), so `Modèle trimestriel.v2.docx` is stored as `Modele-trimestriel-v2.docx`, and it carries its Office content type, whatever the host's own table of types knows; the step still names the file by its own path. An HTML template file travels with the method, since it is read while the method loads, so the HTML template files sent with a bundle may total 512 KiB at most: keep images and fonts out of them, at URLs they reference.
From Python, the same files are passed as `bundle_resources`, built with `make_bundle_resources`:
diff --git a/docs/errors/bundle-resource-not-named-error.md b/docs/errors/bundle-resource-not-named-error.md
index 928b0268d..7bb3c7086 100644
--- a/docs/errors/bundle-resource-not-named-error.md
+++ b/docs/errors/bundle-resource-not-named-error.md
@@ -17,5 +17,6 @@ Raised when a file submitted with a bundle is named by none of its steps.
| `error_domain` | `input` |
| Defined in | `pipelex.core.bundle_resources.exceptions` |
| Parent class | [`PipelexError`](pipelex-error.md) |
+| `retryable` | `false` |
[Back to Error Reference](index.md)
diff --git a/docs/errors/bundle-resource-path-error.md b/docs/errors/bundle-resource-path-error.md
index 3514bfa9e..3936000f1 100644
--- a/docs/errors/bundle-resource-path-error.md
+++ b/docs/errors/bundle-resource-path-error.md
@@ -17,5 +17,6 @@ Raised when a file submitted with a bundle is keyed by a path that cannot name a
| `error_domain` | `input` |
| Defined in | `pipelex.core.bundle_resources.exceptions` |
| Parent class | [`PipelexError`](pipelex-error.md) |
+| `retryable` | `false` |
[Back to Error Reference](index.md)
diff --git a/docs/errors/bundle-resources-too-large-error.md b/docs/errors/bundle-resources-too-large-error.md
index 837a0a9a0..9a72f65a8 100644
--- a/docs/errors/bundle-resources-too-large-error.md
+++ b/docs/errors/bundle-resources-too-large-error.md
@@ -17,5 +17,6 @@ Raised when the files a bundle's steps read when the method loads, such as HTML
| `error_domain` | `input` |
| Defined in | `pipelex.core.bundle_resources.exceptions` |
| Parent class | [`PipelexError`](pipelex-error.md) |
+| `retryable` | `false` |
[Back to Error Reference](index.md)
diff --git a/docs/under-the-hood/distributed-content-generation.md b/docs/under-the-hood/distributed-content-generation.md
index f3c130b09..bc3e6a96b 100644
--- a/docs/under-the-hood/distributed-content-generation.md
+++ b/docs/under-the-hood/distributed-content-generation.md
@@ -154,7 +154,7 @@ async def generate_and_store_images(img_gen_assignment):
)
```
-Each object is stored under `{storage_scope}/generated/<filename>`, the filename rendered from the storage method's `uri_format` (`{hash}.{extension}` by default). The extension follows the MIME type the object is stored under, so the key and the stored content type always agree: `jpg` for `image/jpeg`, `svg` for `image/svg+xml`, and `bin` for a type with no extension of its own.
+Each object is stored under `{storage_scope}/generated/<filename>`, the filename rendered from the storage method's `uri_format` (`{hash}.{extension}` by default). The extension follows the MIME type the object is stored under, so the key and the stored content type always agree: `jpg` for `image/jpeg`, `svg` for `image/svg+xml`, and `bin` for a type with no extension of its own. A document a `PipeDocGen` step prints is stored under `{storage_scope}/generated/<hash>/<filename>` instead, so that every download carries its readable name, and that name is held to the grammar every `pipelex-storage://` reader accepts, the hosted platform's included: a stem of `[A-Za-z0-9_-]`, one dot and an alphanumeric extension (`path_safe_file_name` in `pipelex/tools/storage/storage_file_name.py`). A name holding a letter outside ASCII or an inner dot stores without complaint and is then refused by such a reader, so the file could never be downloaded.
!!! info "What crosses the boundary"
`ImageContent` carries `url` (storage URI), `public_url`, `mime_type`, paired `width`/`height`, and `caption` — but never raw bytes. The `url` can be an S3 URI, HTTP URL, or local file path depending on storage configuration.
@@ -172,7 +172,7 @@ What gets stored vs. what crosses the boundary, by content type:
| Search structured | Nothing (JSON is small) | Raw `dict`, re-validated against the output class on the submitter |
| Judgment answers | Nothing (verdicts are small) | `dict[str, JudgmentAnswer]` keyed as the questions were |
-The traffic also runs the other way. A template file sent with a bundle loaded from content strings, such as a `PipeDocGen` step's `.docx` template, travels in the run's `LibraryCrate` as a `BundleResource`, keyed by the path the step names. Before a run, live or dry, is handed to an orchestrator that runs it outside the process, the submitter stores each file a step reads only when it runs under `{storage_scope}/assets/bundle/<sha256>/<name>` and replaces its bytes in the crate with the `pipelex-storage://` URI (`prepare_job_for_remote_dispatch` in `pipelex/pipe_run/remote_dispatch.py`, over `relocate_run_resources` in `pipelex/libraries/bundle_resources.py`). Every dispatcher calls it as the job leaves: `PipelexMTHDSProtocol.execute` when the hub's pipe run is a boot orchestrator's, which the interpreter hub records when the plugin claims the slot (`does_pipe_run_leave_process`), and the API server for every orchestration mode but `direct`. The worker's library holds the reference, the step's composition carries it, and the print stage reads the bytes back through the storage provider, checking them against their digest, after the read scope has authorized the URI like any other the composition declares; a dry run's template check authorizes it the same way before it reads. An `.html` template file stays inline, since it is read while the crate loads, where the workflow may do no IO, so the files read at load are bounded when the bundle loads: `MAX_LOAD_STAGE_RESOURCES_BYTES`, 512 KiB in total, well under Temporal's 2 MB payload limit, refused with `BundleResourcesTooLargeError`. An in-process run keeps every file inline and stores nothing, and so does a run whose storage scope is the dry-run placeholder.
+The traffic also runs the other way. A template file sent with a bundle loaded from content strings, such as a `PipeDocGen` step's `.docx` template, travels in the run's `LibraryCrate` as a `BundleResource`, keyed by the path the step names. Before a run, live or dry, is handed to an orchestrator that runs it outside the process, the submitter stores each file a step reads only when it runs under `{storage_scope}/assets/bundle/<sha256>/<name>`, its own name held to the same grammar and its content type the one its extension names, the Office Open XML types being named in `pipelex/tools/misc/filetype_utils.py` rather than read from the host's `mimetypes` table, which may not know them, and replaces its bytes in the crate with the `pipelex-storage://` URI (`prepare_job_for_remote_dispatch` in `pipelex/pipe_run/remote_dispatch.py`, over `relocate_run_resources` in `pipelex/libraries/bundle_resources.py`). Every dispatcher calls it as the job leaves: `PipelexMTHDSProtocol.execute` when the hub's pipe run is a boot orchestrator's, which the interpreter hub records when the plugin claims the slot (`does_pipe_run_leave_process`), and the API server for every orchestration mode but `direct`. The worker's library holds the reference, the step's composition carries it, and the print stage reads the bytes back through the storage provider, checking them against their digest, after the read scope has authorized the URI like any other the composition declares; a dry run's template check authorizes it the same way before it reads. An `.html` template file stays inline, since it is read while the crate loads, where the workflow may do no IO, so the files read at load are bounded when the bundle loads: `MAX_LOAD_STAGE_RESOURCES_BYTES`, 512 KiB in total, well under Temporal's 2 MB payload limit, refused with `BundleResourcesTooLargeError`. An in-process run keeps every file inline and stores nothing, and so does a run whose storage scope is the dry-run placeholder.
Each host-runtime plugin dispatches these through its own activities and queue routing; for the Temporal realization (the `act_*` activity set, per-activity task queues), see our Temporal plugin's own docs.
diff --git a/docs/under-the-hood/error-model.md b/docs/under-the-hood/error-model.md
index b8190100c..6fe1ef63e 100644
--- a/docs/under-the-hood/error-model.md
+++ b/docs/under-the-hood/error-model.md
@@ -55,7 +55,7 @@ Classification happens once, at **Layer 1**. Layers 2–5 are wrappers: they att
| `type_uri` | `str` | Per-class documentation URI — the RFC 7807 `type` |
| `error_category` | `str \| None` | `InferenceErrorCategory` value (inference errors only) |
| `error_domain` | `str \| None` | `ErrorDomain` value — `input` / `config` / `runtime`. Declared per class, except on the `CogtError` family where it is [derived from `error_category`](#the-cogterror-family-derives-its-domain-from-its-category) |
-| `retryable` | `bool \| None` | Whether a retry could succeed |
+| `retryable` | `bool \| None` | Whether a retry could succeed. Declared per class, `retryable = False` on a deterministic refusal of what the caller sent (`BundleResourceNotNamedError`, `BundleResourcesTooLargeError`), except on the `CogtError` family where it is derived from `error_category`; left `None`, it is taken from the cause chain, or absent |
| `user_action` | `UserAction \| None` | Typed advice — `kind` + free-form `detail` |
| `model` | `str \| None` | Model handle, when the failure is attributable to one |
| `provider` | `str \| None` | Backend name, when attributable |
diff --git a/pipelex/base_exceptions.py b/pipelex/base_exceptions.py
index 953800e49..f40604d3a 100644
--- a/pipelex/base_exceptions.py
+++ b/pipelex/base_exceptions.py
@@ -611,6 +611,11 @@ def _humanize_class_name(class_name: str) -> str:
class PipelexError(Exception):
error_domain: ErrorDomain | None = None
user_action: UserAction | None = None
+ # Whether running the same request again could succeed, declared by a class whose every instance answers the
+ # same: ``False`` on a deterministic refusal of what the caller sent. ``None`` says nothing, and the report then
+ # takes the answer from the ``__cause__`` chain, or carries none. The ``CogtError`` family derives it from its
+ # ``error_category`` instead.
+ retryable: bool | None = None
# When declared *directly in a subclass body*, ``title()`` returns this
# verbatim instead of auto-deriving from the class name. Use to fix awkward
@@ -735,6 +740,7 @@ class PipelexError(Exception):
title=type(self).title(),
type_uri=type(self).type_uri(),
error_domain=self.error_domain,
+ retryable=self.retryable,
user_action=self.user_action,
caller_facing_message=self._authors_caller_facing_message or self._raised_as_caller_fault,
)
diff --git a/pipelex/cogt/content_generation/generated_content_factory.py b/pipelex/cogt/content_generation/generated_content_factory.py
index 1815bbec7..22deb596e 100644
--- a/pipelex/cogt/content_generation/generated_content_factory.py
+++ b/pipelex/cogt/content_generation/generated_content_factory.py
@@ -127,7 +127,8 @@ class GeneratedContentFactory:
The key is `{storage_scope}/generated/{hash}/{filename}`: the hash keeps two different files with the
same name apart, and ending in the human filename means every backend's URL, and so every download, is
called `invoice-INV-2026-0142.pdf` rather than a hash. The caller owns the filename's safety: it must be
- one path segment.
+ one name every `pipelex-storage://` reader accepts, as `path_safe_file_name` makes it, or a host that
+ checks the key, such as the hosted platform, refuses to serve the file.
"""
hash_digest = hashlib.sha256(data).hexdigest()[:16]
storage_key = f"{storage_scope}/{GENERATED_CONTENT_LEAF}/{hash_digest}/{filename}"
diff --git a/pipelex/core/bundle_resources/exceptions.py b/pipelex/core/bundle_resources/exceptions.py
index 0e11952bf..4ad56959f 100644
--- a/pipelex/core/bundle_resources/exceptions.py
+++ b/pipelex/core/bundle_resources/exceptions.py
@@ -10,10 +10,11 @@ class BundleResourcePathError(PipelexError):
A resource's key is the path a step names, relative to the bundle and written with forward slashes: an absolute
path, a `..` segment, a backslash, a drive colon and an empty path are refused, and so are two keys naming the
- same file. The path is the caller's own, so the message is theirs to read.
+ same file. The path is the caller's own, so the message is theirs to read, and the same request is refused again.
"""
error_domain = ErrorDomain.INPUT
+ retryable = False
_authors_caller_facing_message = True
@@ -21,10 +22,12 @@ class BundleResourceNotNamedError(PipelexError):
"""Raised when a file submitted with a bundle is named by none of its steps.
Every file a caller submits must be one a step reads, such as a `PipeDocGen` step's `template_file`, so a
- misspelt key fails loudly rather than leaving the step without its file. The message names the caller's paths.
+ misspelt key fails loudly rather than leaving the step without its file. The message names the caller's paths, and
+ the same request is refused again.
"""
error_domain = ErrorDomain.INPUT
+ retryable = False
_authors_caller_facing_message = True
@@ -33,8 +36,9 @@ class BundleResourcesTooLargeError(PipelexError):
They travel inline with the method wherever it runs, so their total is bounded (`MAX_LOAD_STAGE_RESOURCES_BYTES`),
whereas a file read only when its step runs, such as an office template, travels by reference to the run's storage.
- The message names the caller's paths and the limit.
+ The message names the caller's paths and the limit, and the same request is refused again.
"""
error_domain = ErrorDomain.INPUT
+ retryable = False
_authors_caller_facing_message = True
diff --git a/pipelex/errors/error_pages_generator.py b/pipelex/errors/error_pages_generator.py
index 15ea75275..a63a4b852 100644
--- a/pipelex/errors/error_pages_generator.py
+++ b/pipelex/errors/error_pages_generator.py
@@ -203,7 +203,8 @@ def render_error_page(cls: type[PipelexError]) -> str:
Includes the class identity (title, type URI, defining module), the
declared error domain (or ``(inherited from parent)`` for subclasses that
don't override it), a link to the parent class's page when the parent is
- itself a ``PipelexError``, and a back-link to the Error Reference index.
+ itself a ``PipelexError``, the ``retryable`` and ``user_action`` the class
+ declares in its own body, if any, and a back-link to the Error Reference index.
"""
title = cls.title()
type_uri = cls.type_uri()
@@ -219,6 +220,9 @@ def render_error_page(cls: type[PipelexError]) -> str:
("Defined in", f"`{cls.__module__}`"),
("Parent class", parent_link),
]
+ declared_retryable = cls.__dict__.get("retryable")
+ if isinstance(declared_retryable, bool):
+ rows.append(("`retryable`", f"`{str(declared_retryable).lower()}`"))
declared_action = _resolve_class_level_user_action(cls)
if declared_action is not None:
rows.append(("`user_action`", declared_action))
diff --git a/pipelex/libraries/bundle_resources.py b/pipelex/libraries/bundle_resources.py
index 00f4102eb..8672f4a57 100644
--- a/pipelex/libraries/bundle_resources.py
+++ b/pipelex/libraries/bundle_resources.py
@@ -6,8 +6,6 @@ read only when a step runs to the run's storage before the run leaves the proces
receives carries references rather than the bytes.
"""
-import mimetypes
-import re
from collections.abc import Iterable, Mapping
from pathlib import PurePosixPath
@@ -20,11 +18,14 @@ from pipelex.core.bundle_resources.bundle_resource import (
from pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError, BundleResourcesTooLargeError
from pipelex.libraries.library_crate import LibraryCrate
from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipeBlueprintUnion, PipelexBundleBlueprint
+from pipelex.tools.misc.filetype_utils import mime_type_of_file_name
+from pipelex.tools.storage.storage_file_name import path_safe_file_name
from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract
# The run's storage leaf for the files its caller supplied, under which the bundle's files are stored by digest.
BUNDLE_RESOURCES_STORAGE_PREFIX = "assets/bundle"
-_UNSAFE_KEY_CHARACTERS = re.compile(r"[^A-Za-z0-9._-]+")
+# The stem a stored file takes when its own name leaves none, such as a name written wholly in Han.
+_FALLBACK_STORED_STEM = "file"
def bundle_resource_reads(*, pipe_blueprints: Iterable[PipeBlueprintUnion]) -> dict[str, BundleResourceReadStage]:
@@ -89,6 +90,11 @@ async def relocate_run_resources(*, crate: LibraryCrate, storage_provider: Stora
file read when the method loads stays inline, since the remote side reads it while it loads the crate, where it may
do no IO. The files are stored by digest, so a run that submits the same file twice stores it once, and a file
already stored is kept as it is.
+
+ Each is stored under a name every `pipelex-storage://` reader accepts (`path_safe_file_name`), so `modèle.v2.docx`
+ is stored as `modele-v2.docx`, and with the content type its extension names, the Office Open XML types named in
+ code rather than read from the host's `mimetypes` table, which may not know them and would leave the object typed
+ `binary/octet-stream`.
"""
if not crate.bundle_resources:
return crate
@@ -98,11 +104,12 @@ async def relocate_run_resources(*, crate: LibraryCrate, storage_provider: Stora
if path not in run_stage_paths or not resource.is_inline:
relocated[path] = resource
continue
- file_name = _UNSAFE_KEY_CHARACTERS.sub("-", PurePosixPath(path).name).strip(".-") or "file"
+ submitted_name = PurePosixPath(path)
+ file_name = path_safe_file_name(name=submitted_name.name, fallback=_FALLBACK_STORED_STEM, extension=submitted_name.suffix.removeprefix("."))
uri = await storage_provider.store(
resource.inline_bytes(),
key=f"{storage_scope}/{BUNDLE_RESOURCES_STORAGE_PREFIX}/{resource.sha256}/{file_name}",
- content_type=mimetypes.guess_type(file_name)[0],
+ content_type=mime_type_of_file_name(file_name=file_name),
)
relocated[path] = resource.stored_at(uri=uri)
return crate.model_copy(update={"bundle_resources": relocated})
diff --git a/pipelex/pipe_operators/doc_gen/pipe_doc_gen.py b/pipelex/pipe_operators/doc_gen/pipe_doc_gen.py
index 8db53efab..59f11a990 100644
--- a/pipelex/pipe_operators/doc_gen/pipe_doc_gen.py
+++ b/pipelex/pipe_operators/doc_gen/pipe_doc_gen.py
@@ -1,5 +1,4 @@
import asyncio
-import re
from pathlib import Path
from typing import Any, Literal
@@ -45,22 +44,11 @@ from pipelex.tools.jinja2.exceptions import Jinja2TemplateRenderError
from pipelex.tools.jinja2.jinja2_required_variables import detect_jinja2_required_variables
from pipelex.tools.jinja2.template_category import TemplateCategory
from pipelex.tools.misc.string_utils import get_root_from_dotted_path
+from pipelex.tools.storage.storage_file_name import path_safe_file_name
from pipelex.tools.templating.templating_style import TemplatingStyle
from pipelex.tools.uri.uri_read_scope import UriReference
from pipelex.validation_error_types import TemplateCheckErrorType
-_UNSAFE_FILENAME_CHARACTERS = re.compile(r"[^\w.\-]+")
-_MAX_FILENAME_STEM_LENGTH = 120
-
-
-def safe_filename(*, rendered: str, fallback: str, suffix: str) -> str:
- """One storage-safe path segment ending in the format's suffix, from whatever the filename template rendered."""
- stem = _UNSAFE_FILENAME_CHARACTERS.sub("-", rendered.strip()).strip(".-_")
- if stem.lower().endswith(f".{suffix}"):
- stem = stem[: -(len(suffix) + 1)]
- stem = stem[:_MAX_FILENAME_STEM_LENGTH].strip(".-_") or fallback
- return f"{stem}.{suffix}"
-
class PipeDocGenOutput(PipeOutput):
pass
@@ -232,7 +220,8 @@ class PipeDocGen(PipeOperator[PipeDocGenOutput]):
label="filename",
templating_style=resolve_templating_style(authored=None),
)
- filename = safe_filename(rendered=rendered_filename, fallback=self.code, suffix=self.doc_gen_format.suffix)
+ # Stored under a name every `pipelex-storage://` reader serves, the hosted platform's included.
+ filename = path_safe_file_name(name=rendered_filename, fallback=self.code, extension=self.doc_gen_format.suffix)
named_contents = self._named_contents(working_memory)
title = self._title(named_contents)
source = self.source
diff --git a/pipelex/pipeline/input_normalizer.py b/pipelex/pipeline/input_normalizer.py
index 30ed1e840..f07da3717 100644
--- a/pipelex/pipeline/input_normalizer.py
+++ b/pipelex/pipeline/input_normalizer.py
@@ -57,6 +57,7 @@ from pipelex.tools.misc.filetype_utils import (
)
from pipelex.tools.misc.http_utils import validate_http_url_syntax
from pipelex.tools.storage.exceptions import StorageFileNotFoundError, StorageInvalidUriError
+from pipelex.tools.storage.storage_file_name import path_safe_extension
from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract
from pipelex.tools.uri.resolved_uri import ResolvedBase64DataUrl, ResolvedHttpUrl, ResolvedLocalPath, ResolvedPipelexStorage, UriKind
from pipelex.tools.uri.uri_read_scope import authorize_uri_read
@@ -582,7 +583,8 @@ def _storage_key_extension(*, raw_bytes: bytes, mime_type: str | None, fallback_
"""The extension a relocated file's storage key ends with.
The sniffed extension when the bytes were identified, else the extension of the declared type,
- else the local file's own suffix, else `bin`.
+ else the local file's own suffix when it is plainly letters and digits (`path_safe_extension`), so
+ every reader of the key accepts it, the hosted platform's included, else `bin`.
"""
sniffed = guess_file_type_from_bytes(raw_bytes=raw_bytes)
if sniffed is not None and sniffed.mime == mime_type:
@@ -591,4 +593,4 @@ def _storage_key_extension(*, raw_bytes: bytes, mime_type: str | None, fallback_
extension = mime_type_to_extension(mime_type)
if extension != UNKNOWN_FILE_TYPE:
return extension
- return fallback_suffix or "bin"
+ return path_safe_extension(extension=fallback_suffix or "")
diff --git a/pipelex/tools/misc/filetype_utils.py b/pipelex/tools/misc/filetype_utils.py
index f2b3a7626..3000dcbc6 100644
--- a/pipelex/tools/misc/filetype_utils.py
+++ b/pipelex/tools/misc/filetype_utils.py
@@ -23,13 +23,20 @@ _MIME_OVERRIDES: Final[dict[str, str]] = {
"application/json": "json",
}
-# Initialize MIME database with additional types
+# The Office Open XML types, named here because neither Python's built-in table nor a slim server image's `mime.types`
+# is sure to know them, and an object stored with no content type is served as `binary/octet-stream`.
+OFFICE_MIME_TYPES_BY_EXTENSION: Final[dict[str, str]] = {
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+}
+
+# A table of our own: a `MimeTypes` instance starts from Python's built-in table, never from the host's `mime.types`
+# files or registry, which only the module-level functions of `mimetypes` read, and it gets the types added here.
_MIME_DB: Final[mimetypes.MimeTypes] = mimetypes.MimeTypes()
_MIME_DB.add_type("application/json", ".json", strict=True)
-# Office Open XML formats (not always in default mimetypes DB)
-_MIME_DB.add_type("application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx", strict=True)
-_MIME_DB.add_type("application/vnd.openxmlformats-officedocument.presentationml.presentation", ".pptx", strict=True)
-_MIME_DB.add_type("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx", strict=True)
+for office_extension, office_mime_type in OFFICE_MIME_TYPES_BY_EXTENSION.items():
+ _MIME_DB.add_type(office_mime_type, office_extension, strict=True)
class FileType(BaseModel):
@@ -112,6 +119,22 @@ def detect_file_type_from_base64(base64_data: str | bytes) -> FileType:
return detect_file_type_from_bytes(raw_bytes=raw)
+def mime_type_of_file_name(*, file_name: str) -> str | None:
+ """The MIME type a file's name implies by its extension, or None when the extension is not known.
+
+ Read from this module's own table, which names the Office Open XML types, so an `.xlsx`, `.docx` or `.pptx` file is
+ stored under its type whatever the host's `mimetypes` table holds, and never from the host's own files.
+
+ Args:
+ file_name: The file's name, or a path or storage key ending in it.
+
+ Returns:
+ The MIME type, such as `application/vnd.openxmlformats-officedocument.wordprocessingml.document` for a `.docx`
+ file, or None when the extension is absent or unknown.
+ """
+ return _MIME_DB.guess_type(file_name, strict=False)[0]
+
+
def mime_type_to_extension(mime_type: str) -> str:
"""Convert MIME type to file extension using the mimetypes database.
diff --git a/pipelex/tools/storage/storage_file_name.py b/pipelex/tools/storage/storage_file_name.py
new file mode 100644
index 000000000..d6d0d9034
--- /dev/null
+++ b/pipelex/tools/storage/storage_file_name.py
@@ -0,0 +1,132 @@
+"""The file name an object is stored under, held to the grammar every `pipelex-storage://` reader accepts.
+
+A host that serves a run's files by their `pipelex-storage://` URI checks each key before it reads it, and the hosted
+Pipelex platform's check is the strictest this runtime writes for: every segment of the key is `[A-Za-z0-9_-]+`, and the
+last one is a stem of those characters, one dot and an alphanumeric extension. A name holding any other character, a
+letter outside ASCII or a second dot, stores without complaint and is then refused by every reader holding that
+grammar, so the file can never be downloaded. A name a method renders, such as a `PipeDocGen` step's `filename`, or a
+name a caller sends, such as a template file's, is therefore made into one the grammar accepts before anything is
+stored under it.
+"""
+
+import re
+import unicodedata
+from typing import Final
+
+# The grammar of a stored file's name: a stem, one dot, an extension. Restated from the hosted platform's storage URI
+# parser, which the runtime does not import.
+STORAGE_FILE_STEM_PATTERN: Final[re.Pattern[str]] = re.compile(r"^[A-Za-z0-9_-]+$")
+STORAGE_FILE_EXTENSION_PATTERN: Final[re.Pattern[str]] = re.compile(r"^[A-Za-z0-9]+$")
+
+# Long enough for any name a person reads, short enough that a key stays far below a store's own limit.
+MAX_STORAGE_FILE_STEM_LENGTH: Final[int] = 120
+# How much of a name is read at all, cut before any pass over it: well above the stem's cap, so no name a person writes
+# loses anything to it, and a bound on the work a name rendered from a caller's text can ask of a worker.
+_MAX_READ_NAME_LENGTH: Final[int] = 8 * MAX_STORAGE_FILE_STEM_LENGTH
+
+# The stem when neither the name nor its fallback leaves anything, and the extension when the given one is not plain.
+_LAST_RESORT_STEM: Final[str] = "file"
+_LAST_RESORT_EXTENSION: Final[str] = "bin"
+
+# Letters that NFKD leaves whole, since Unicode treats each as a letter of its own rather than a base letter carrying a
+# mark, spelled with the Latin letters a reader would type for them.
+_LETTERS_NFKD_KEEPS_WHOLE: Final[dict[str, str]] = {
+ "ø": "o",
+ "Ø": "O",
+ "æ": "ae",
+ "Æ": "AE",
+ "œ": "oe",
+ "Œ": "OE",
+ "ł": "l",
+ "Ł": "L",
+ "đ": "d",
+ "Đ": "D",
+ "ð": "d",
+ "Ð": "D",
+ "þ": "th",
+ "Þ": "Th",
+ "ß": "ss",
+ "ẞ": "SS",
+ "ı": "i",
+ "ħ": "h",
+ "Ħ": "H",
+ "ŧ": "t",
+ "Ŧ": "T",
+ "ŋ": "ng",
+ "Ŋ": "NG",
+ "ĸ": "k",
+}
+_TRANSLITERATION_TABLE: Final[dict[int, str]] = str.maketrans(_LETTERS_NFKD_KEEPS_WHOLE)
+
+# Dots are kept until a name already ending in its extension has had it removed, then go with everything else.
+_NOT_STEM_OR_DOT_CHARACTERS: Final[re.Pattern[str]] = re.compile(r"[^A-Za-z0-9_.-]+")
+_NOT_STEM_CHARACTERS: Final[re.Pattern[str]] = re.compile(r"[^A-Za-z0-9_-]+")
+# A run of separators, read once: it becomes one hyphen when it holds a hyphen, one underscore when it is underscores alone.
+_SEPARATOR_RUNS: Final[re.Pattern[str]] = re.compile(r"[-_]+")
+_EDGE_CHARACTERS: Final[str] = ".-_"
+
+
+def fold_to_ascii(*, text: str) -> str:
+ """`text` with each letter spelled in ASCII where it has a spelling there, and every other character kept as it is.
+
+ NFKD splits a letter from its marks and a compatibility character into its plain form (`ë` into `e` and a
+ diaeresis, `fi` into `fi`), the marks are dropped, and the letters NFKD leaves whole are spelled from a table (`ø`
+ as `o`, `ß` as `ss`). A script with no Latin spelling here, such as Greek, Cyrillic or Han, is kept for the caller
+ to replace.
+ """
+ decomposed = unicodedata.normalize("NFKD", text)
+ without_marks = "".join(char for char in decomposed if not unicodedata.combining(char))
+ return without_marks.translate(_TRANSLITERATION_TABLE)
+
+
+def _path_safe_stem(*, name: str, extension: str) -> str:
+ """The stem `name` gives once folded to ASCII and held to the grammar, or the empty string when nothing is left."""
+ stem = _NOT_STEM_OR_DOT_CHARACTERS.sub("-", fold_to_ascii(text=name[:_MAX_READ_NAME_LENGTH])).strip(_EDGE_CHARACTERS)
+ if stem.lower().endswith(f".{extension}"):
+ stem = stem[: -(len(extension) + 1)]
+ stem = _NOT_STEM_CHARACTERS.sub("-", stem)
+ stem = _SEPARATOR_RUNS.sub(lambda separator_run: "-" if "-" in separator_run.group() else "_", stem)
+ return stem[:MAX_STORAGE_FILE_STEM_LENGTH].strip(_EDGE_CHARACTERS)
+
+
+def path_safe_extension(*, extension: str) -> str:
+ """`extension` as every `pipelex-storage://` reader accepts it: spelled in ASCII and lowercased, or `bin`.
+
+ The hosted platform keys its own uploads by the same rule: an extension that is not then plainly letters and digits,
+ such as `v1_draft` or `tar-gz`, names no type worth keeping, so the file is stored as `bin` rather than under a key
+ a reader refuses. The extension is a convenience for the content type, never the file's identity.
+
+ Args:
+ extension: The extension, with or without its leading dot.
+
+ Returns:
+ An extension matching `STORAGE_FILE_EXTENSION_PATTERN`.
+ """
+ folded = fold_to_ascii(text=extension.removeprefix(".")).lower()
+ if STORAGE_FILE_EXTENSION_PATTERN.fullmatch(folded):
+ return folded
+ return _LAST_RESORT_EXTENSION
+
+
+def path_safe_file_name(*, name: str, fallback: str, extension: str) -> str:
+ """One file name every `pipelex-storage://` reader accepts, ending in `.{extension}`, from whatever `name` holds.
+
+ Each letter is spelled in ASCII where it can be (`fold_to_ascii`), and every other character, a dot inside the
+ stem included, becomes a hyphen, a run of separators collapsing into one. A name already ending in the extension
+ is not given it twice, the stem is cut at `MAX_STORAGE_FILE_STEM_LENGTH` characters, and a separator left at either
+ end is dropped. When nothing is left, a name written wholly in Greek or Han for one, the stem is `fallback` held to
+ the same rule, then `file`. So a `PipeDocGen` step's `Zoë Ångström — Q3.2026` is stored as
+ `Zoe-Angstrom-Q3-2026.docx`. Only the name's first characters are read, eight times the stem's cap, so a name
+ rendered from a caller's text costs a bounded amount of work whatever its length.
+
+ Args:
+ name: The name to store the file under, as rendered or as sent: any text.
+ fallback: The stem to use when `name` leaves none, such as the pipe's code.
+ extension: The file's extension, held to `path_safe_extension`: `bin` unless it is plainly letters and digits.
+
+ Returns:
+ A name whose stem matches `STORAGE_FILE_STEM_PATTERN` and whose extension matches `STORAGE_FILE_EXTENSION_PATTERN`.
+ """
+ safe_extension = path_safe_extension(extension=extension)
+ stem = _path_safe_stem(name=name, extension=safe_extension) or _path_safe_stem(name=fallback, extension=safe_extension) or _LAST_RESORT_STEM
+ return f"{stem}.{safe_extension}"
diff --git a/tests/unit/pipelex/core/bundle_resources/test_bundle_resource_exceptions.py b/tests/unit/pipelex/core/bundle_resources/test_bundle_resource_exceptions.py
new file mode 100644
index 000000000..e960b4090
--- /dev/null
+++ b/tests/unit/pipelex/core/bundle_resources/test_bundle_resource_exceptions.py
@@ -0,0 +1,41 @@
+import pytest
+
+from pipelex.base_exceptions import DisclosureMode, ErrorDomain, PipelexError
+from pipelex.core.bundle_resources.exceptions import (
+ BundleResourceNotNamedError,
+ BundleResourcePathError,
+ BundleResourcesTooLargeError,
+)
+
+
+class TestBundleResourceExceptions:
+ @pytest.mark.parametrize("error_class", [BundleResourceNotNamedError, BundleResourcesTooLargeError, BundleResourcePathError])
+ def test_a_refusal_of_the_files_sent_says_running_it_again_cannot_succeed(self, error_class: type[PipelexError]) -> None:
+ """Deterministic refusals of what the caller sent, so their problem documents carry `retryable: false`."""
+ report = error_class("The files sent are refused.").to_error_report()
+
+ assert report.retryable is False
+ assert report.error_domain == ErrorDomain.INPUT
+ assert report.caller_facing_message is True
+ assert report.to_dict()["retryable"] is False
+ assert report.to_dict(disclosure_mode=DisclosureMode.STRICT)["retryable"] is False
+
+ def test_a_wrapper_raised_from_one_carries_its_retryable(self) -> None:
+ try:
+ try:
+ cause_msg = "A file no step names."
+ raise BundleResourceNotNamedError(cause_msg)
+ except BundleResourceNotNamedError as exc:
+ msg = "The library could not be loaded."
+ raise PipelexError(msg) from exc
+ except PipelexError as wrapper:
+ report = wrapper.to_error_report()
+
+ assert report.error_type == "PipelexError"
+ assert report.retryable is False
+
+ def test_an_error_that_declares_nothing_carries_no_retryable(self) -> None:
+ report = PipelexError("Something failed.").to_error_report()
+
+ assert report.retryable is None
+ assert "retryable" not in report.to_dict()
diff --git a/tests/unit/pipelex/errors/test_error_pages_generator.py b/tests/unit/pipelex/errors/test_error_pages_generator.py
index 59620061f..c5d65a7b8 100644
--- a/tests/unit/pipelex/errors/test_error_pages_generator.py
+++ b/tests/unit/pipelex/errors/test_error_pages_generator.py
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING
import pytest
from pipelex.base_exceptions import PipelexError
+from pipelex.core.bundle_resources.exceptions import BundleResourceError, BundleResourceNotNamedError
from pipelex.errors.error_pages_generator import (
_MACRO_SECTIONS, # pyright: ignore[reportPrivateUsage]
AUTHORED_MARKER,
@@ -19,6 +20,7 @@ from pipelex.errors.error_pages_generator import (
has_authored_marker,
iter_pipelex_error_subclasses,
page_slug,
+ render_error_page,
)
from pipelex.tools.misc.string_utils import pascal_case_to_kebab
@@ -123,6 +125,10 @@ class TestErrorPagesGenerator:
body_with_standalone_marker = f"some content\n{AUTHORED_MARKER}\nmore content\n"
assert has_authored_marker(body_with_standalone_marker) is True
+ def test_a_class_declaring_retryable_shows_it_and_one_declaring_nothing_does_not(self) -> None:
+ assert "| `retryable` | `false` |" in render_error_page(BundleResourceNotNamedError)
+ assert "`retryable`" not in render_error_page(BundleResourceError)
+
def test_report_total_sums_four_populations(self) -> None:
"""``total`` should equal the sum of ``written`` + ``unchanged`` + ``preserved`` + ``removed``."""
report = ErrorPagesReport(
diff --git a/tests/unit/pipelex/libraries/test_bundle_resources.py b/tests/unit/pipelex/libraries/test_bundle_resources.py
index 697d8e6b9..3978ebbd4 100644
--- a/tests/unit/pipelex/libraries/test_bundle_resources.py
+++ b/tests/unit/pipelex/libraries/test_bundle_resources.py
@@ -1,4 +1,8 @@
+import mimetypes
+import re
+
import pytest
+from pytest_mock import MockerFixture
from pipelex.core.bundle_resources.bundle_resource import MAX_LOAD_STAGE_RESOURCES_BYTES, BundleResourceReadStage, make_bundle_resources
from pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError, BundleResourcesTooLargeError
@@ -43,6 +47,31 @@ template_file = "summary.html"
"""
+# A template file whose own name the hosted plane would refuse to serve: a letter outside ASCII and inner dots.
+_UNSAFE_NAME_BUNDLE = """
+domain = "bundle_resources_tests"
+main_pipe = "print_review"
+
+[concept.Review]
+description = "A review"
+
+[pipe.print_review]
+type = "PipeDocGen"
+description = "Print the review in Word"
+inputs = { review = "Review" }
+output = "Document"
+format = "docx"
+template_file = "templates/Modèle trimestriel.v2.docx"
+"""
+
+# The hosted platform's grammar for the last segment of a `pipelex-storage://` URI, copied from `_SEGMENT_PATTERN` and
+# `_EXTENSION_PATTERN` in pipelex-server's `shared/src/pipelex_shared/domain/storage/storage_uri.py` (`parse_storage_uri`).
+_HOSTED_STEM_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$")
+_HOSTED_EXTENSION_PATTERN = re.compile(r"^[A-Za-z0-9]+$")
+
+_DOCX_MIME_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+
+
def _blueprint() -> PipelexBundleBlueprint:
return MthdsParser.make_pipelex_bundle_blueprint(mthds_content=_BUNDLE)
@@ -104,6 +133,39 @@ class TestBundleResources:
assert crate.bundle_resources["templates/report.docx"].is_inline
assert relocated.fingerprint == crate.fingerprint
+ @pytest.mark.asyncio
+ async def test_a_stored_office_template_carries_its_office_content_type(self, mocker: MockerFixture) -> None:
+ """Named in code, so a host whose `mimetypes` table knows no `.docx` does not leave it `binary/octet-stream`."""
+ mocker.patch.object(mimetypes, "guess_type", return_value=(None, None))
+ store_spy = mocker.spy(InMemoryStorageProvider, "store")
+ resources = make_bundle_resources(files={"templates/report.docx": b"docx bytes", "summary.html": b"<h1></h1>"})
+ crate = LibraryCrateFactory.make_from_blueprints([_blueprint()], bundle_resources=resources)
+
+ await relocate_run_resources(crate=crate, storage_provider=InMemoryStorageProvider(), storage_scope="org/method/run")
+
+ assert store_spy.call_count == 1
+ assert store_spy.call_args.kwargs["content_type"] == _DOCX_MIME_TYPE
+
+ @pytest.mark.asyncio
+ async def test_a_template_whose_name_is_not_path_safe_is_stored_under_one_that_is(self) -> None:
+ """The key's last segment is one the hosted plane serves; the step still finds the file by the path it names."""
+ storage_provider = InMemoryStorageProvider()
+ template_path = "templates/Modèle trimestriel.v2.docx"
+ blueprint = MthdsParser.make_pipelex_bundle_blueprint(mthds_content=_UNSAFE_NAME_BUNDLE)
+ resources = make_bundle_resources(files={template_path: b"docx bytes"})
+ crate = LibraryCrateFactory.make_from_blueprints([blueprint], bundle_resources=resources)
+
+ relocated = await relocate_run_resources(crate=crate, storage_provider=storage_provider, storage_scope="org/method/run")
+
+ stored = relocated.bundle_resources[template_path]
+ stored_uri = stored.uri
+ assert stored_uri is not None
+ assert stored_uri == f"pipelex-storage://org/method/run/{BUNDLE_RESOURCES_STORAGE_PREFIX}/{stored.sha256}/Modele-trimestriel-v2.docx"
+ stem, extension = stored_uri.rsplit("/", 1)[1].rsplit(".", 1)
+ assert _HOSTED_STEM_PATTERN.match(stem)
+ assert _HOSTED_EXTENSION_PATTERN.match(extension)
+ assert await stored.read_bytes(storage_provider=storage_provider) == b"docx bytes"
+
@pytest.mark.asyncio
async def test_a_crate_without_resources_is_returned_as_it_is(self) -> None:
crate = LibraryCrateFactory.make_from_blueprints([_blueprint()])
diff --git a/tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_safe_filename.py b/tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_safe_filename.py
deleted file mode 100644
index 9780e53b1..000000000
--- a/tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_safe_filename.py
+++ /dev/null
@@ -1,19 +0,0 @@
-import pytest
-
-from pipelex.pipe_operators.doc_gen.pipe_doc_gen import safe_filename
-
-
-class TestSafeFilename:
- @pytest.mark.parametrize(
- ("rendered", "expected"),
- [
- ("invoice-INV-2026-0142", "invoice-INV-2026-0142.pdf"),
- ("invoice INV/2026:0142", "invoice-INV-2026-0142.pdf"),
- ("report.pdf", "report.pdf"),
- (" ../../etc/passwd ", "etc-passwd.pdf"),
- ("", "render_invoice.pdf"),
- ("...", "render_invoice.pdf"),
- ],
- )
- def test_the_rendered_name_becomes_one_safe_segment(self, rendered: str, expected: str) -> None:
- assert safe_filename(rendered=rendered, fallback="render_invoice", suffix="pdf") == expected
diff --git a/tests/unit/pipelex/pipeline/test_input_normalizer_identification.py b/tests/unit/pipelex/pipeline/test_input_normalizer_identification.py
index f214d3146..e3db21e47 100644
--- a/tests/unit/pipelex/pipeline/test_input_normalizer_identification.py
+++ b/tests/unit/pipelex/pipeline/test_input_normalizer_identification.py
@@ -213,6 +213,20 @@ class TestFileInputIdentification:
assert stored.public_url is None
assert _stored_keys(tmp_path=tmp_path) == {"org/uploads/c.docx"}
+ async def test_a_local_file_whose_suffix_is_not_plain_is_stored_as_bin(self, storage: LocalStorageProvider, tmp_path: Path): # ruff: ignore[unused-method-argument]
+ """The suffix `v1_draft` names no type, and a key ending in it is one the hosted platform refuses to serve."""
+ local_notes = tmp_path / "notes.v1_draft"
+ local_notes.write_bytes(b"Plain notes that no sniffer recognises.")
+ memory = _memory(notes=DocumentContent(url=str(local_notes)))
+
+ await prepare_file_inputs(memory, storage_scope=STORAGE_SCOPE, read_scope=None, is_relocation_enabled=True)
+
+ content = memory.get_stuff("notes").content
+ assert isinstance(content, DocumentContent)
+ assert content.url.startswith("pipelex-storage://test/scope/assets/")
+ assert content.url.endswith(".bin")
+ assert _stored_bytes(tmp_path=tmp_path, uri=content.url) == b"Plain notes that no sniffer recognises."
+
async def test_a_missing_stored_object_is_an_input_error(self, storage: LocalStorageProvider): # ruff: ignore[unused-method-argument]
memory = _memory(transcript=DocumentContent(url="pipelex-storage://org/uploads/never-uploaded.docx"))
diff --git a/tests/unit/pipelex/tools/misc/test_mime_type_of_file_name.py b/tests/unit/pipelex/tools/misc/test_mime_type_of_file_name.py
new file mode 100644
index 000000000..4d9421e55
--- /dev/null
+++ b/tests/unit/pipelex/tools/misc/test_mime_type_of_file_name.py
@@ -0,0 +1,36 @@
+import mimetypes
+
+import pytest
+from pytest_mock import MockerFixture
+
+from pipelex.tools.misc.filetype_utils import mime_type_of_file_name
+
+_DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+_XLSX = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
+_PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
+
+
+class TestMimeTypeOfFileName:
+ @pytest.mark.parametrize(
+ ("file_name", "expected"),
+ [
+ ("report.docx", _DOCX),
+ ("budget.XLSX", _XLSX),
+ ("org/run/assets/bundle/abc/deck.pptx", _PPTX),
+ ("summary.html", "text/html"),
+ ("invoice.pdf", "application/pdf"),
+ ("data.json", "application/json"),
+ ("archive.unknown-extension", None),
+ ("no-extension", None),
+ ],
+ )
+ def test_the_type_follows_the_extension(self, file_name: str, expected: str | None) -> None:
+ assert mime_type_of_file_name(file_name=file_name) == expected
+
+ @pytest.mark.parametrize(("file_name", "expected"), [("report.docx", _DOCX), ("budget.xlsx", _XLSX), ("deck.pptx", _PPTX)])
+ def test_the_office_types_never_depend_on_the_hosts_mimetypes_table(self, mocker: MockerFixture, file_name: str, expected: str) -> None:
+ """A host whose `mime.types` knows no office type, as a slim server image's does not, still gets them."""
+ mocker.patch.object(mimetypes, "guess_type", return_value=(None, None))
+ mocker.patch.dict(mimetypes.types_map, {}, clear=True)
+
+ assert mime_type_of_file_name(file_name=file_name) == expected
diff --git a/tests/unit/pipelex/tools/storage/test_storage_file_name.py b/tests/unit/pipelex/tools/storage/test_storage_file_name.py
new file mode 100644
index 000000000..ce0a58bcc
--- /dev/null
+++ b/tests/unit/pipelex/tools/storage/test_storage_file_name.py
@@ -0,0 +1,159 @@
+import re
+
+import pytest
+
+from pipelex.tools.storage.storage_file_name import (
+ MAX_STORAGE_FILE_STEM_LENGTH,
+ STORAGE_FILE_EXTENSION_PATTERN,
+ STORAGE_FILE_STEM_PATTERN,
+ fold_to_ascii,
+ path_safe_file_name,
+)
+
+# The hosted platform's grammar for the last segment of a `pipelex-storage://` URI, copied from `_SEGMENT_PATTERN` and
+# `_EXTENSION_PATTERN` in pipelex-server's `shared/src/pipelex_shared/domain/storage/storage_uri.py`
+# (`parse_storage_uri`): a stem of these characters, one dot, an alphanumeric extension. A name it refuses is never
+# served, so the file can never be downloaded. The runtime restates it rather than importing it, so this pins the two
+# to one rule.
+_HOSTED_STEM_PATTERN = re.compile(r"^[A-Za-z0-9_-]+$")
+_HOSTED_EXTENSION_PATTERN = re.compile(r"^[A-Za-z0-9]+$")
+
+
+def _assert_hosted_grammar_accepts(file_name: str) -> None:
+ assert "." in file_name
+ assert not file_name.startswith(".")
+ assert not file_name.endswith(".")
+ stem, extension = file_name.rsplit(".", 1)
+ assert _HOSTED_STEM_PATTERN.fullmatch(stem), f"stem of {file_name!r} is not path-safe"
+ assert _HOSTED_EXTENSION_PATTERN.fullmatch(extension), f"extension of {file_name!r} is not alphanumeric"
+
+
+class TestStorageFileName:
+ def test_the_runtime_restates_the_hosted_grammar_exactly(self) -> None:
+ assert STORAGE_FILE_STEM_PATTERN.pattern == _HOSTED_STEM_PATTERN.pattern
+ assert STORAGE_FILE_EXTENSION_PATTERN.pattern == _HOSTED_EXTENSION_PATTERN.pattern
+
+ @pytest.mark.parametrize(
+ ("text", "expected"),
+ [
+ ("Zoë Ångström", "Zoe Angstrom"),
+ ("Ærøskøbing", "AEroskobing"),
+ ("file", "file"),
+ ("Москва", "Москва"),
+ ],
+ )
+ def test_letters_are_spelled_in_ascii_where_they_can_be_and_kept_otherwise(self, text: str, expected: str) -> None:
+ assert fold_to_ascii(text=text) == expected
+
+ @pytest.mark.parametrize(
+ ("name", "expected"),
+ [
+ ("invoice-INV-2026-0142", "invoice-INV-2026-0142.pdf"),
+ ("invoice INV/2026:0142", "invoice-INV-2026-0142.pdf"),
+ ("report.pdf", "report.pdf"),
+ ("Report.PDF", "Report.pdf"),
+ (" ../../etc/passwd ", "etc-passwd.pdf"),
+ ("", "render_invoice.pdf"),
+ ("...", "render_invoice.pdf"),
+ # Accents are dropped from their letters.
+ ("Bäckerei Müller & Söhne", "Backerei-Muller-Sohne.pdf"),
+ ("Zoë Ångström — Q3.2026", "Zoe-Angstrom-Q3-2026.pdf"),
+ ("İstanbul Çiğköfte", "Istanbul-Cigkofte.pdf"),
+ # Letters NFKD leaves whole are spelled from the table.
+ ("Ærøskøbing", "AEroskobing.pdf"),
+ ("Łukasiewicz straße", "Lukasiewicz-strasse.pdf"),
+ ("Đorđe Þórr ðe œuvre ı", "Dorde-Thorr-de-oeuvre-i.pdf"),
+ # A script with no Latin spelling becomes a separator, and is dropped at either end.
+ ("Ελληνικά report", "report.pdf"),
+ ("Москва 2026", "2026.pdf"),
+ ("東京都 Q3", "Q3.pdf"),
+ ("مرحبا Q3", "Q3.pdf"),
+ # A name that leaves nothing falls back to the step's code.
+ ("ελληνικά", "render_invoice.pdf"),
+ ("Москва", "render_invoice.pdf"),
+ ("東京都", "render_invoice.pdf"),
+ ("مرحبا", "render_invoice.pdf"),
+ ("서울", "render_invoice.pdf"),
+ # Inner dots leave the stem, and repeated separators collapse.
+ ("report.v2.final", "report-v2-final.pdf"),
+ ("report.v2.pdf", "report-v2.pdf"),
+ ("a -- b __ c", "a-b-c.pdf"),
+ ("a_-_b", "a-b.pdf"),
+ ("snake__case", "snake_case.pdf"),
+ ],
+ )
+ def test_a_rendered_document_name_becomes_one_the_hosted_plane_serves(self, name: str, expected: str) -> None:
+ """A `PipeDocGen` step's rendered `filename`, with its code as the fallback and its format as the extension."""
+ file_name = path_safe_file_name(name=name, fallback="render_invoice", extension="pdf")
+
+ assert file_name == expected
+ _assert_hosted_grammar_accepts(file_name)
+
+ def test_the_proof_lab_name_the_hosted_plane_refused_is_now_served(self) -> None:
+ """The file name of the run the hosted plane would not serve, as its method's template rendered it."""
+ name = "Halden Brook Review Q3 2026 — Zoë Ångström Łukasiewicz · Ærøskøbing · İstanbul · Ελληνικά · Москва · 東京都 · 서울 · مرحبا · שלום"
+
+ file_name = path_safe_file_name(name=name, fallback="render_review", extension="docx")
+
+ assert file_name == "Halden-Brook-Review-Q3-2026-Zoe-Angstrom-Lukasiewicz-AEroskobing-Istanbul.docx"
+ _assert_hosted_grammar_accepts(file_name)
+
+ @pytest.mark.parametrize("extension", ["pdf", "xlsx", "docx", "pptx"])
+ def test_a_stem_already_ending_in_the_extension_is_not_given_it_twice(self, extension: str) -> None:
+ file_name = path_safe_file_name(name=f"quarterly-review.{extension.upper()}", fallback="render_review", extension=extension)
+
+ assert file_name == f"quarterly-review.{extension}"
+ _assert_hosted_grammar_accepts(file_name)
+
+ def test_the_stem_is_cut_at_its_length_cap_and_never_ends_on_a_separator(self) -> None:
+ name = "a" * (MAX_STORAGE_FILE_STEM_LENGTH - 1) + "-tail-past-the-cap"
+
+ file_name = path_safe_file_name(name=name, fallback="render_invoice", extension="pdf")
+
+ assert file_name == "a" * (MAX_STORAGE_FILE_STEM_LENGTH - 1) + ".pdf"
+ _assert_hosted_grammar_accepts(file_name)
+
+ def test_a_long_name_of_accented_letters_is_cut_after_its_letters_are_spelled(self) -> None:
+ file_name = path_safe_file_name(name="é" * (MAX_STORAGE_FILE_STEM_LENGTH * 2), fallback="render_invoice", extension="pdf")
+
+ assert file_name == "e" * MAX_STORAGE_FILE_STEM_LENGTH + ".pdf"
+ _assert_hosted_grammar_accepts(file_name)
+
+ @pytest.mark.parametrize(
+ ("name", "expected"),
+ [
+ pytest.param("_" * 200_000, "render_invoice.pdf", id="underscores_alone"),
+ pytest.param("report" + "_" * 200_000 + "end", "report.pdf", id="underscores_after_a_word"),
+ pytest.param("-_" * 100_000 + "report", "render_invoice.pdf", id="mixed_separators"),
+ pytest.param("é" * 200_000, "e" * MAX_STORAGE_FILE_STEM_LENGTH + ".pdf", id="accented_letters"),
+ ],
+ )
+ def test_a_very_long_name_is_handled_in_bounded_work(self, name: str, expected: str) -> None:
+ """A name rendered from a caller's text can be any length; only its first characters are read, in one pass each."""
+ file_name = path_safe_file_name(name=name, fallback="render_invoice", extension="pdf")
+
+ assert file_name == expected
+ _assert_hosted_grammar_accepts(file_name)
+
+ @pytest.mark.parametrize(
+ ("name", "fallback", "extension", "expected"),
+ [
+ # A template file's own name, with its own extension.
+ ("modèle.v2.docx", "file", "docx", "modele-v2.docx"),
+ ("Invoice Template.DOCX", "file", "DOCX", "Invoice-Template.docx"),
+ # An extension is spelled in ASCII and lowercased, `bin` when it is not then plainly letters and digits.
+ ("template", "file", "", "template.bin"),
+ ("template", "file", ".PDF", "template.pdf"),
+ ("photo", "file", "jpég", "photo.jpeg"),
+ ("notes", "file", "v1_draft", "notes.bin"),
+ ("template", "file", "東京", "template.bin"),
+ # A fallback is held to the same rule, and `file` stands in when it leaves nothing either.
+ ("東京都", "Pipe Code.v2", "pdf", "Pipe-Code-v2.pdf"),
+ ("東京都", "Москва", "pdf", "file.pdf"),
+ ],
+ )
+ def test_extensions_and_fallbacks_are_held_to_the_hosted_grammar(self, name: str, fallback: str, extension: str, expected: str) -> None:
+ file_name = path_safe_file_name(name=name, fallback=fallback, extension=extension)
+
+ assert file_name == expected
+ _assert_hosted_grammar_accepts(file_name)