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/Crate-tree-digests · L-261015-1eb734 (#1436)
Louis Choquel51ee234c5efc
diff --git a/.drift/acks/hub-layering-convention.toml b/.drift/acks/hub-layering-convention.tomlindex c6f8a9ce2..b540eb484 100644--- a/.drift/acks/hub-layering-convention.toml+++ b/.drift/acks/hub-layering-convention.toml@@ -1,10 +1,10 @@contract = "hub-layering-convention"-digest = "sha256:b43388e7c97d4a39aadb375cde0f3431d0e9bce1c15adab9d9d4c61e958a403a"+digest = "sha256:79d4e68f7ae4755f1a027bc882f105c1985a5ecf291bd888dd3792269162951b"reviewed_by = "Louis Choquel"-reviewed_at = "2026-10-16T02:32:28Z"-rationale = "real-catch: after merging dev, runtime_hub.py drops FuncRegistry, set_func_registry and get_func_registry with the retired registry, and interpreter_hub.py carries dev's PipeFuncPackageOfferRegistry accessors; docs/contribute/hub-layering.md no longer names get_func_registry among the runtime hub's getters and lists get_pipe_func_package_offer_registry in the pipe func row. No import crosses the boundary."+reviewed_at = "2026-10-16T05:26:39Z"+rationale = "real-catch: runtime_hub.py gains the method file store and the template file stage, and interpreter_hub.py drops does_pipe_run_leave_process with set_pipe_run's leaves_process; docs/contribute/hub-layering.md now lists get_method_file_store and get_template_file_stage, no longer lists does_pipe_run_leave_process, and says how the template file stage is installed by the interpreter's boot and released at teardown. No import crosses the boundary."[trigger_files]"pipelex/cli/dev_cli/commands/hub_layering_guard.py" = "blob:fda2237457fe0b6830ff2ae8f720698735bec4c3"-"pipelex/interpreter_hub.py" = "blob:4efc29ca60c42ca0fe0533c402d7bb246b0bb2c2"-"pipelex/runtime_hub.py" = "blob:87f051f8ab31244ed34c9c5dfc499d5e309edcaf"+"pipelex/interpreter_hub.py" = "blob:e1a4b941820aeb8affbb6c70b7f81eb29e4cc191"+"pipelex/runtime_hub.py" = "blob:ca642e419aeac8eee7bd0dba2b5784feb0059e82"diff --git a/.test_durations b/.test_durationsindex 26b37e5ca..5e51e25bc 100644--- a/.test_durations+++ b/.test_durations@@ -1443,25 +1443,6 @@"tests/integration/pipelex/pipes/operator/pipe_compose_structured/test_pipe_compose_stuff_content_subclasses.py::TestPipeComposeStuffContentSubclasses::test_compose_number_content": 1.375,"tests/integration/pipelex/pipes/operator/pipe_compose_structured/test_pipe_compose_stuff_content_subclasses.py::TestPipeComposeStuffContentSubclasses::test_compose_pdf_content": 1.3321,"tests/integration/pipelex/pipes/operator/pipe_compose_structured/test_pipe_compose_stuff_content_subclasses.py::TestPipeComposeStuffContentSubclasses::test_compose_pdf_list": 1.3397,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_bundle_its_caller_read_from_a_file_here_reads_its_template_beside_that_file[dry]": 0.0538,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_bundle_its_caller_read_from_a_file_here_reads_its_template_beside_that_file[live]": 0.0678,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_bundle_validates_with_its_template_file_and_the_check_runs_on_its_bytes": 0.1604,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_caller_s_source_label_never_reads_beside_it_on_this_host[html]": 0.1592,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_caller_s_source_label_never_reads_beside_it_on_this_host[office]": 0.0525,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_dry_run_checks_the_submitted_template_file_and_prints_nothing": 0.0481,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_file_no_step_names_is_refused_as_the_request_s_fault_not_as_a_verdict": 0.0486,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_run_handed_to_a_remote_worker_reads_its_template_from_the_run_s_storage[dry]": 0.0851,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_run_handed_to_a_remote_worker_reads_its_template_from_the_run_s_storage[dry_run_placeholder_scope]": 0.1459,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_run_handed_to_a_remote_worker_reads_its_template_from_the_run_s_storage[live]": 0.0785,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_run_hands_the_engine_the_submitted_template_file": 0.1977,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_run_prints_with_the_submitted_html_template": 0.1518,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_source_the_bundle_s_text_writes_on_its_step_never_reads_beside_it_on_this_host": 0.0601,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_step_read_from_a_file_here_reads_beside_it_and_never_a_submitted_file[in_process]": 0.2876,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_step_read_from_a_file_here_reads_beside_it_and_never_a_submitted_file[remote_worker]": 0.3436,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_submitted_html_template_is_read_and_checked_when_the_method_loads": 0.1312,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_template_file_not_supplied_is_refused_saying_so": 0.0389,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_a_worker_reads_no_stored_template_outside_the_run_s_read_scope_even_to_check_it": 0.0574,- "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py::TestPipeDocGenBundleResources::test_the_check_s_errors_on_a_submitted_template_fail_the_validation": 0.0533,"tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_dependency_template_file.py::TestPipeDocGenDependencyTemplateFile::test_a_dependency_s_missing_template_file_is_refused_without_the_host_path": 0.028,"tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_dependency_template_file.py::TestPipeDocGenDependencyTemplateFile::test_a_dependency_s_template_file_is_found_beside_its_bundle": 0.0962,"tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_host_template_files.py::TestPipeDocGenHostTemplateFiles::test_a_caller_step_keeps_naming_a_template_file_a_host_step_names_too": 0.095,@@ -1496,6 +1477,21 @@"tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_run.py::TestPipeDocGenRun::test_an_engine_prints_on_the_document_pool_not_the_default_executor": 0.0422,"tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_run.py::TestPipeDocGenRun::test_an_html_template_is_rendered_before_the_engine_prints_it": 0.0529,"tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_run.py::TestPipeDocGenRun::test_an_undeclared_engine_failure_is_a_render_error": 0.0394,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_bundle_its_caller_read_from_a_file_here_reads_its_template_beside_that_file[dry]": 0.0538,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_bundle_its_caller_read_from_a_file_here_reads_its_template_beside_that_file[live]": 0.0678,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_bundle_validates_with_its_template_file_and_the_check_runs_on_its_bytes": 0.1604,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_caller_s_source_label_never_reads_beside_it_on_this_host[html]": 0.1592,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_caller_s_source_label_never_reads_beside_it_on_this_host[office]": 0.0525,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_dry_run_checks_the_submitted_template_file_and_prints_nothing": 0.0481,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_file_no_step_names_is_refused_as_the_request_s_fault_not_as_a_verdict": 0.0486,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_run_hands_the_engine_the_submitted_template_file": 0.1977,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_run_prints_with_the_submitted_html_template": 0.1518,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_source_the_bundle_s_text_writes_on_its_step_never_reads_beside_it_on_this_host": 0.0601,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_step_read_from_a_file_here_reads_beside_it_and_never_a_submitted_file[in_process]": 0.2876,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_step_read_from_a_file_here_reads_beside_it_and_never_a_submitted_file[remote_worker]": 0.3436,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_submitted_html_template_is_read_and_checked_when_the_method_loads": 0.1312,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_a_template_file_not_supplied_is_refused_saying_so": 0.0389,+ "tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py::TestPipeDocGenSubmittedFiles::test_the_check_s_errors_on_a_submitted_template_fail_the_validation": 0.0533,"tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_files.py::TestPipeDocGenTemplateFiles::test_a_template_file_is_found_inside_the_bundle_s_directory[linked_outside_the_bundle]": 0.1627,"tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_files.py::TestPipeDocGenTemplateFiles::test_a_template_file_is_found_inside_the_bundle_s_directory[missing_file]": 0.1045,"tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_files.py::TestPipeDocGenTemplateFiles::test_a_template_file_is_found_inside_the_bundle_s_directory[outside_the_bundle]": 0.0276,diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8c9e27c7f..3d6ade41f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,43 +4,47 @@### Added+- **`[interpreter.method_tree_limits]`**: the limits every method tree is listed under on this machine, `max_files` (10,000) and `max_total_bytes` (1 GiB) by default with `max_file_bytes` unset, so a folder handed over by mistake is refused before any file is hashed, with the advice to run the method's own folder or to raise the limits; these are not the hosted API's limits, which a deployment sets.+- **A run records its method tree**: `pipelex run bundle` prints the digest of the method tree it read with its recap and writes `method_tree.json` (the digest, the tree's root, its entry and each file's path, hash and size) in its output folder, `pipelex-agent run bundle` adds `method_tree_digest` to its output file and to its `--with-memory` output, and every run's `RunMetadata` carries `method_tree_digest`, the digest of the tree its pipe belongs to, which changes with any byte of the method, beside `crate_fingerprint`, which changes only with the meaning of its concepts and pipes.+- **`MethodTreeLoadError`, `MethodEntryError` and `HostLibraryTreeError`**: the `error_type` of a method tree that cannot be listed (a symbolic link, a tree past its limits), of a method folder with no single pipe to start at, and of a server's own library directory whose tree cannot be listed beside the bundles a caller submitted, a configuration fault whose message, naming the server's paths, never reaches the caller.- **`PluginRegistrar.add_pipe_func_package_offer`**: the plugin providing an out-of-process PipeFunc execution mode states, keyed by the same mode, the Python packages and the marker environment its sandbox offers (`PipeFuncPackageOffer`), which a method's `requirements.txt` is checked against; a mode stating none refuses every method declaring requirements with `PipeFuncPackageSetUnstatedError`, a configuration fault. `MethodRequirementsFileError`, `MethodRequirementsNotMetError`, `HostLibraryRequirementsError`, `PipeFuncPackageSetUnstatedError` and `DuplicatePipeFuncPackageOfferError` are new `error_type`s.- **`pipelex fix function-names` and `pipelex-agent fix function-names`**: rewrite every flat `PipeFunc` `function_name` of a method folder as the function's import path and drop the argument of every `@pipe_func(name=...)` marker, reading the files as syntax trees without importing them or booting Pipelex, and keeping every comment and alignment; a flat name no module of the method's tree registers, or that two register, is left as it is and reported with the markers registering it, which keep their argument, and so is a marker whose name is not a string literal, the agent command's `is_complete` being false and both commands exiting `1`, with `--dry-run` to preview.- **`pipe_func_function_refused` and the method-tree Python errors**: a `PipeFunc` whose function cannot be found or proven is refused at validation with the `pipe_func_function_refused` validation error type, located on the step's `function_name`, and the new `PipeFuncFunctionError`, `TreePythonError`, `TreePythonHeldError`, `TreeModuleShadowingError` and `FunctionNamesMigrationError` name the failures of a function, of a tree's Python and of the migration.+- **The method file store**: a step reads a file of its method where reading is allowed, at the moment it uses it, through `MethodFileStoreProtocol`, whose `read_tree_listing(tree_digest=..., read_scope=...)` and `read_blob(sha256=..., read_scope=...)` return a tree's listing and a file's bytes under the run's read scope, each read checked against the tree's digest (`pipelex.core.method_trees.method_files`). The local store, `LOCAL_METHOD_FILES`, serves the trees this process's libraries hold, and a plugin whose activities run apart from the process that loaded the method claims `HubSlot.METHOD_FILE_STORE` with `PluginRegistrar.claim_method_file_store`; a file the store does not hold for the run fails its step with the new `MethodFileUnavailableError`. An orchestrator running a job out of process copies every tree the job's crate names into the store its workers read before its `execute` or `start` returns, since the runner may drop the files as soon as it does, and `read_stored_trees(tree_digests=..., read_scope=...)` reads them for that copy, each as a store keeps it, its listing under its digest and its files under their hashes. The local store finds a file by its hash in one lookup and reads a file on disk off the event loop.### Changed+- **Library directories load through their method trees (Breaking)**: a library directory's `.mthds` files are the bundles of its method tree and of the trees of the nested packages and repositories under it, each loaded as a method of its own, so a hidden, gitignored or virtual-environment `.mthds` file is no longer loaded, a symbolic link in the tree refuses the load, and `[interpreter.scan] excluded_dirs` now applies only to the scan for Python classes and functions; a hosted run sends the same bundles. A directory holding nothing but nested methods loads them, a nested package or repository holding no `.mthds` file is skipped before it is listed, and a dependency package whose tree cannot be listed is refused naming the package by its address, never the directory it was installed into.+- **`-L <subdir>` inside a package loads the whole package (Breaking)**: a library directory is listed as its method tree, which is rooted at the nearest `METHODS.toml` at or above it, so naming a subfolder of a package with `-L`, or as a library directory of a runner, loads every bundle of the package.+- **A `.mthds` file named alone belongs to its method tree (Breaking)**: a bundle file handed to `run bundle`, `validate bundle` or a runner is the member of the tree rooted at the nearest `METHODS.toml` at or above its folder, and with none its method is that one file, so a step naming any other file, such as a `template_file`, is refused with the advice to run the method's folder or to add a `METHODS.toml`.+- **`template_file` resolves in the bundle's method tree (Breaking)**: a PipeDocGen `template_file` read from disk is looked up among the files of its bundle's method tree, where a `..` climbing to another folder of the tree is now allowed, and a file the tree does not hold (above its root, gitignored, hidden or in a nested package) is refused, the message naming each file by its path in the tree; a URL is refused when the bundle parses, and a bundle loaded from a string still reads only the files sent with it.+- **`run bundle <folder>` starts at the method's main pipe (Breaking)**: with no `--pipe`, `pipelex run bundle` and `pipelex-agent run bundle` on a folder, locally as on the hosted API, start at its `METHODS.toml`'s `main_pipe`, or with no manifest at the one `main_pipe` its bundles declare, and refuse none or several, naming each bundle by its path in the tree; a `bundle.mthds` or a single `.mthds` file in the folder is no longer looked for. A hosted run names that pipe as `domain.pipe_code`, so it starts where the local run would when two domains of the method define the same code.+- **Run output folders hold a `.gitignore`**: every folder `pipelex run` creates for a run's outputs holds a `.gitignore` ignoring everything in it, so a run started inside a method's folder leaves the method's tree, and its digest, unchanged; the folder is named after the pipe's own code even when the pipe was named as `domain.pipe_code`, on a hosted run too.+- **`pipelex-agent run` writes into an output folder (Breaking)**: its output file (`live_run.json` or `dry_run.json`) and its graph files go into a new numbered folder, `results/<pipe_code>_output_<NN>/` beside the bundle it ran, else under `mthds-wip/`, holding the same `.gitignore`, instead of beside the bundle itself, so two runs of a method read the same tree, with the same `method_tree_digest`.+- **`mthds` and `pipelex-sdk` versions, MTHDS protocol 1.0.0 and standard 7.0.0 (Breaking)**: the pins move to `mthds==0.22.0`, the release that lists method trees, carries protocol 1.0.0 and implements MTHDS standard 7.0.0, and `pipelex-sdk==0.45.0`, the release built on it, so the runner and `GET /v1/version` report `protocol_version` `1.0.0`, a crate pipelex normalizes is stamped `mthds_version` `7.0.0`, and a `METHODS.toml` declaring `mthds_version = "^5.0.0"` now warns that the engine does not satisfy it. A dependency package fetched before is fetched again into the release's new cache layout, a package's `METHODS.toml` is found only at its root and manifest discovery stops at any `.git` entry; everyone downstream inherits those exact versions.- **A method's `requirements.txt` is checked when it loads (Breaking)**: a method tree holding Python and a `requirements.txt` at its root is refused before any of its Python is imported, naming each requirement, when the environment its PipeFunc steps run in does not meet it, or when the file holds a line the MTHDS standard refuses (a URL, an option such as `-r` or `-e`, a comment after a requirement, a continued line). A package a method calls by its address is checked the same way, named by its address. Locally the environment is the interpreter Pipelex runs in and the refusal gives the `uv pip install` command that fixes it; on a sandbox-hosted deployment it is the package set the deployment states for its sandbox, a run is refused with a `422` and a validation by `method_ref` with an `is_valid: false` verdict located on the line, naming no path on the server. A method of a server's own library directories whose requirements are not met is the server's fault, a `500` `HostLibraryRequirementsError` whose message never reaches the caller. Pipelex never installs anything. A project root loaded as a library directory is such a tree, so hand over the folder holding the methods instead when the root's `requirements.txt` is an application's.- **A `PipeFunc` names its function by import path (Breaking)**: `function_name` is the function's import path from the root of the step's method tree, such as `funcs.totals.compute_totals` for the function `compute_totals` of `funcs/totals.py`, and a flat name is refused as the bundle is read with the advice to run `pipelex fix function-names`. Validation locates the module among the tree's files and proves, without running any Python, that the function is a top-level `def` or `async def` the module defines carrying the `@pipe_func()` marker; the module is imported under its real name, the tree's root first on the import path, when the step first runs, where its signature and return type are checked. A bundle passed as content imports locally from the process's import path, and on a sandbox-hosted deployment from the Python submitted with it. The runner's OpenAPI document gives the `PipeFunc` blueprint's `function_name` its import path pattern and `PipeValidationErrorType` its `pipe_func_function_refused` value.- **One method tree's Python per process (Breaking)**: a run holds the Python of the tree it imports from until its library is torn down, and a step of another tree that would load its Python meanwhile is refused with `TreePythonHeldError` naming both trees by a bundle each holds and the start of its digest, never by a path of the host, so a run whose own steps and a dependency package's steps both call Python is refused locally; once no run holds a tree, its root leaves `sys.path` and the next tree evicts every module imported from a file of it, whatever imported it. A top-level module of a tree named like a standard-library module or like a module importable outside the tree is refused at validation, `structures` excepted, and on a sandbox-hosted deployment, whose sandbox holds its own packages, only a standard-library name is, and while a tree is held, importing a file its membership rule keeps out, such as a `.gitignore`d module, is refused naming the rule, and no bytecode is written into the tree.- **The function registry is retired and `@pipe_func()` takes no argument (Breaking)**: `FuncRegistry`, `func_registry`, `FuncRegistryUtils`, `FuncRegistryError`, `RuntimeHub.get_func_registry` and the `name=` argument of `@pipe_func` are removed, no function is discovered or imported while a library loads, and `is_marked_pipe_func(func=...)` tells a function carrying the marker.- **Kernel func ops take the function (Breaking)**: `pipelex.kernel.func_ops.call_registered_function` becomes `call_function(function=..., memory=...)`, and `run_func` takes the `function` itself in place of `function_name`.-- **`LibraryCrate.pipe_func_files` replaces `python_sources` (Breaking)**: a sandbox-hosted crate carries the files a `PipeFunc` call receives, keyed by Python root, the key of a method tree holding a `PipeFunc` step or `submitted` for the bundles passed as content, then by tree path: every file of the tree except its `.mthds` files and a generated `structures` module, a file that is not UTF-8 text in Base64. They are read as the library loads, so a crate built later reads no file. The `submitted` root holds the files of the library directories whose own tree holds no bundle, such as the directory a server writes a request's Python into; a directory holding a bundle submits nothing, so two methods' `README.md` or `requirements.txt` never clash, and two directories submitting different files at one path refuse the load with `LibraryError`. A structure class is refused in every tree the load lists, a package or repository nested in a library directory included.-- **A `PipeFunc` call carries its tree's files (Breaking)**: `PipeFuncExecutionRequest.files` holds the files of the called step's Python root at their tree paths, and `build_pipe_func_execution_request` moves them there from the crate, which no longer carries `pipe_func_files`. The direct executor's transported run writes them into a temporary directory, generates `structures` unless the method shipped one, imports the function by its import path under the process's hold on that directory and unloads its modules before removing it; `DirectPipeFuncExecutor.run_pipe_func_transported_at` and an optional third argument of the transported entrypoint take a directory a sandbox client filled itself.+- **Plugin API version 7 (Breaking)**: `PLUGIN_API_VERSION` moves to 7, so a plugin declaring `targets_api = 6` is refused at discovery with `PluginApiVersionMismatchError`: a bundle validator's `validate_bundles` receives `submitted_files` in place of `bundle_resources`, a PipeFunc executor's transported request names its tree by `tree_digest` and carries no `files`, the transported entrypoint takes the directory the call's files were unpacked into, an orchestrator running a job out of process copies the job's trees before it returns, and `claim_method_file_store` joins the registrar's menu.+- **`LibraryCrate` names its method trees by digest (Breaking)**: `python_sources`, `bundle_resources` and `host_bundle_files` give way to `tree_bundles`, which names each pipe's bundle by its tree's digest and its tree path (`TreeBundleRef`), so a crate carries no file's bytes, no listing and no path of the host that assembled it, a pipe built from it resolves a file its bundle names lexically and reads nothing, a Temporal workflow loading it included, and its fingerprint ignores the trees. Bundles loaded from content strings sit at the root of the tree of the files submitted with them, which the files of a library directory whose own tree holds no bundle, such as the directory a server writes a request's Python into, join; two directories submitting different files at one path refuse the load with `BundleResourcePathError`, naming the path in the tree alone and joining none of their files, and a structure class is refused in every tree the load lists, a package or repository nested in a library directory included. A load that validates a crate builds each pipe as a member of its tree when a library of this process holds the tree under the digest the crate names, so a `PipeDocGen` HTML template file is checked as it was where the crate was assembled, and refuses such a step with the new `PipeDocGenTemplateFileUncheckedError` when no library holds its tree, rather than passing its template unchecked; a load skipping validation still reads no file. `LibraryCrate.concepts_only()` gives the crate's concepts and domains without its pipes.+- **A `PipeFunc` call names its method tree (Breaking)**: `PipeFuncExecutionRequest.tree_digest` names the tree of the called step, and the process running the call reads its files, every one but the `.mthds` files and a generated `structures` module, through the method file store under the run's read scope (`read_pipe_func_call_files`). The direct executor's transported run writes them into a temporary directory, generates `structures` unless the method shipped one, imports the function by its import path under the process's hold on that directory and unloads its modules before removing it; the transported entrypoint takes as a required third argument the directory a sandbox client unpacked the files into, since a sandbox reaches no method file store, and runs `DirectPipeFuncExecutor.run_pipe_func_transported_at` on it. Only the called step is built in the tree written for the call, which holds none of the tree's bundles: `load_from_crate` and `rehydrate_library_and_memory` take `written_pipe_trees`, keyed by the step's pipe ref, and every other step, a `PipeDocGen` of the same tree included, is built as the crate names it, its template file named by the crate's digest. The transported library's id is public, `TRANSPORTED_LIBRARY_ID`.+- **A `PipeDocGen` template file is read where the document prints (Breaking)**: `DocumentComposition.template_file`, a `ComposedTemplateFile` naming the file by its tree's digest and tree path (`MethodFileRef`), replaces `template_path` and `template_resource`, and the print stage reads it through the method file store under the run's read scope, renders an `.html` one with the step's data, carried as a `TemplateRenderContext` (the stuffs the step's inputs name, the concepts and domains of the run's crate with none of its pipes, the crate's fingerprint, and the run's runtime parameters), through the template file stage the interpreter installs at boot, a dry print included, in the run's own library where this process holds it and otherwise in a library loaded from the concepts, which the process keeps for later prints (`RenderLibraryCache`), and hands an office one's bytes to its engine, whose template check moves from the step's dry run into the dry print. An `.html` template file whose bytes changed after its tree was listed is refused at load, never read from the disk unchecked. `make_render_job` is synchronous again and takes the rendered `html` or the template's bytes; an inline `template` is still rendered where the step runs.+- **Files submitted with content strings make one method tree (Breaking)**: `PipelexMTHDSProtocol`, `validate_bundle`, `validate_bundles_in_process`, `acquire_library`, `pipeline_run_setup`, `resolve_crate_from_contents` and `BundleValidatorProtocol.validate_bundles` take `submitted_files`, a mapping from the path a step names to the file's bytes, in place of `bundle_resources`, and `LibraryManagerAbstract.add_submitted_files` replaces `add_bundle_resources`. The run names their tree by its digest and carries none of the files, so nothing is stored under the run's `assets/bundle/` before it leaves the process, the 512 KiB bound on `.html` template files is lifted, and files that cannot make one tree, such as two paths equal once case-folded, raise `BundleResourcePathError`. A step names a submitted file by any spelling of its path, so `templates//invoice.docx` reads the file submitted as `templates/invoice.docx`.### Fixed- **A `template_file` no sent file could be keyed by is a blueprint item at its step**: a bundle loaded from content strings, as the API's routes and `validate_bundle` load one, whose `PipeDocGen` step's `template_file` holds a `..` segment or a NUL character, or names no file, is refused when it parses, whatever files the request sends, as one `blueprint_validation` item with `field_path` `pipe.<code>` whose message names the field and not the path, instead of a load refusal saying the file was not supplied. A bundle read from disk still resolves a `..` in its method tree.-## [v0.86.1] - 2026-10-16+### Removed-### Added+- **Bundle resources and their dispatch (Breaking)**: `BundleResource`, `BundleResources`, `make_bundle_resources`, `BundleResourceReadStage`, `MAX_LOAD_STAGE_RESOURCES_BYTES`, `prepare_job_for_remote_dispatch`, `relocate_run_resources` and `does_pipe_run_leave_process` are removed, `InterpreterHub.set_pipe_run` takes the pipe run alone, and `BundleResourceError` and `BundleResourcesTooLargeError` are no longer `error_type`s: no template file rides in a run's payloads, so none is bounded by them, and a method file a run cannot read raises `MethodFileUnavailableError`.-- **`[interpreter.method_tree_limits]`**: the limits every method tree is listed under on this machine, `max_files` (10,000) and `max_total_bytes` (1 GiB) by default with `max_file_bytes` unset, so a folder handed over by mistake is refused before any file is hashed, with the advice to run the method's own folder or to raise the limits; these are not the hosted API's limits, which a deployment sets.-- **A run records its method tree**: `pipelex run bundle` prints the digest of the method tree it read with its recap and writes `method_tree.json` (the digest, the tree's root, its entry and each file's path, hash and size) in its output folder, and `pipelex-agent run bundle` adds `method_tree_digest` to its output file and to its `--with-memory` output.-- **`MethodTreeLoadError`, `MethodEntryError`, `CrateIntegrityError` and `HostLibraryTreeError`**: the `error_type` of a method tree that cannot be listed (a symbolic link, a tree past its limits), of a method folder with no single pipe to start at, of a library crate naming a method tree it does not carry, and of a server's own library directory whose tree cannot be listed beside the bundles a caller submitted, a configuration fault whose message, naming the server's paths, never reaches the caller.+## [v0.86.1] - 2026-10-16### Changed-- **Library directories load through their method trees (Breaking)**: a library directory's `.mthds` files are the bundles of its method tree and of the trees of the nested packages and repositories under it, each loaded as a method of its own, so a hidden, gitignored or virtual-environment `.mthds` file is no longer loaded, a symbolic link in the tree refuses the load, and `[interpreter.scan] excluded_dirs` now applies only to the scan for Python classes and functions; a hosted run sends the same bundles. A directory holding nothing but nested methods loads them, a nested package or repository holding no `.mthds` file is skipped before it is listed, and a dependency package whose tree cannot be listed is refused naming the package by its address, never the directory it was installed into.-- **`-L <subdir>` inside a package loads the whole package (Breaking)**: a library directory is listed as its method tree, which is rooted at the nearest `METHODS.toml` at or above it, so naming a subfolder of a package with `-L`, or as a library directory of a runner, loads every bundle of the package.-- **A `.mthds` file named alone belongs to its method tree (Breaking)**: a bundle file handed to `run bundle`, `validate bundle` or a runner is the member of the tree rooted at the nearest `METHODS.toml` at or above its folder, and with none its method is that one file, so a step naming any other file, such as a `template_file`, is refused with the advice to run the method's folder or to add a `METHODS.toml`.-- **`template_file` resolves in the bundle's method tree (Breaking)**: a PipeDocGen `template_file` read from disk is looked up among the files of its bundle's method tree, where a `..` climbing to another folder of the tree is now allowed, and a file the tree does not hold (above its root, gitignored, hidden or in a nested package) is refused, the message naming each file by its path in the tree; a URL is refused when the bundle parses, and a bundle loaded from a string still reads only the files sent with it.-- **`run bundle <folder>` starts at the method's main pipe (Breaking)**: with no `--pipe`, `pipelex run bundle` and `pipelex-agent run bundle` on a folder, locally as on the hosted API, start at its `METHODS.toml`'s `main_pipe`, or with no manifest at the one `main_pipe` its bundles declare, and refuse none or several, naming each bundle by its path in the tree; a `bundle.mthds` or a single `.mthds` file in the folder is no longer looked for. A hosted run names that pipe as `domain.pipe_code`, so it starts where the local run would when two domains of the method define the same code.-- **Run output folders hold a `.gitignore`**: every folder `pipelex run` creates for a run's outputs holds a `.gitignore` ignoring everything in it, so a run started inside a method's folder leaves the method's tree, and its digest, unchanged; the folder is named after the pipe's own code even when the pipe was named as `domain.pipe_code`, on a hosted run too.-- **`pipelex-agent run` writes into an output folder (Breaking)**: its output file (`live_run.json` or `dry_run.json`) and its graph files go into a new numbered folder, `results/<pipe_code>_output_<NN>/` beside the bundle it ran, else under `mthds-wip/`, holding the same `.gitignore`, instead of beside the bundle itself, so two runs of a method read the same tree, with the same `method_tree_digest`.-- **`LibraryCrate` carries method trees (Breaking)**: `host_bundle_files` gives way to the transport-only `method_trees`, each tree's listing as JSON keyed by the tree, and `tree_bundles`, each pipe's bundle's place in its tree, so a crate loaded again, in a Temporal workflow included, resolves a step's file in the tree the host listed.-- **`mthds` and `pipelex-sdk` versions, MTHDS protocol 1.0.0 and standard 7.0.0 (Breaking)**: the pins move to `mthds==0.22.0`, the release that lists method trees, carries protocol 1.0.0 and implements MTHDS standard 7.0.0, and `pipelex-sdk==0.45.0`, the release built on it, so the runner and `GET /v1/version` report `protocol_version` `1.0.0`, a crate pipelex normalizes is stamped `mthds_version` `7.0.0`, and a `METHODS.toml` declaring `mthds_version = "^5.0.0"` now warns that the engine does not satisfy it. A dependency package fetched before is fetched again into the release's new cache layout, a package's `METHODS.toml` is found only at its root and manifest discovery stops at any `.git` entry; everyone downstream inherits those exact versions.- **A scoped event log captures usage events**: a usage event emitted while `runtime_hub.scoped_event_log` is set now goes into the scoped event log and nowhere else, ahead of an event log registered with `ReportingManager.set_event_log` and of the per-process runner fallback, including inside an isolated sub-execution such as a Temporal activity, where it always went to the fallback. Code running a leaf inside an activity can therefore scope a fresh `InMemoryEventLog` around it and return the leaf's usage events with its result, which is how a backend with no shared tracing store, such as Mistral Workflows, collects a run's usage; with no scoped event log set, usage events are routed as before.## [v0.86.0] - 2026-10-13diff --git a/api/pipelex_api/bundle_resources.py b/api/pipelex_api/bundle_resources.pyindex c299a2a60..2c1c92e6e 100644--- a/api/pipelex_api/bundle_resources.py+++ b/api/pipelex_api/bundle_resources.py@@ -4,8 +4,9 @@ They come in two ways. `resources` is a JSON object mapping each file's bundle-rnames (a `PipeDocGen` step's `template_file`), to the file's bytes in standard base64, beside `mthds_contents` or amethod bundle. A method bundle (`bundle_b64` or `files`) may also ship the file beside its `.mthds` file, which`files_its_steps_read` picks out. Every bundle of the request is read as sitting in one directory, so one path holds-one file. The decoded files go to the runtime as `BundleResources`, which refuses a file none of the bundle's steps-names once the bundle is parsed.+one file. The decoded files go to the runtime as its `submitted_files`, keyed by canonical path, which refuses a file+none of the bundle's steps names once the bundle is parsed, and holds the rest as the files of the tree the bundle+sits at the root of: the run's crate names that tree by its digest and carries none of their bytes.Refusals, in the order they are checked:@@ -27,12 +28,7 @@ from pathlib import PurePosixPathfrom typing import NoReturnfrom pipelex import log-from pipelex.core.bundle_resources.bundle_resource import (- BundleResources,- canonical_resource_path,- canonical_resource_path_or_none,- make_bundle_resources,-)+from pipelex.core.bundle_resources.bundle_resource import canonical_resource_path, canonical_resource_path_or_nonefrom pipelex.core.bundle_resources.exceptions import BundleResourcePathErrorfrom pipelex.mthds_parsing.exceptions import MthdsParserErrorfrom pipelex.mthds_parsing.parser import MthdsParser@@ -77,7 +73,7 @@ def files_its_steps_read(log.debug("A method bundle's file did not parse, so the files its steps read are left to its load", fields=error_fields(exc=exc))continuefor pipe_blueprint in (blueprint.pipe or {}).values():- for named_path in pipe_blueprint.bundle_resource_reads:+ for named_path in pipe_blueprint.named_file_references:canonical_path = canonical_resource_path_or_none(path=named_path)if canonical_path is None:continue@@ -91,7 +87,7 @@ def files_its_steps_read(return files-def decode_bundle_resources(*, resources: dict[str, str] | None, bundle_files: Mapping[str, bytes] | None = None) -> BundleResources | None:+def decode_bundle_resources(*, resources: dict[str, str] | None, bundle_files: Mapping[str, bytes] | None = None) -> dict[str, bytes] | None:"""The files the bundle's steps read, decoded and keyed by canonical path, or None when there are none.`resources` are the ones the request sends, in base64. `bundle_files` are the ones its method bundle ships, as@@ -145,4 +141,4 @@ def decode_bundle_resources(*, resources: dict[str, str] | None, bundle_files: Mtotal_bytes += len(data)if total_bytes > MAX_RESOURCES_TOTAL_BYTES:raise_payload_too_large(message=f"The files the bundle's steps read exceed the {MAX_RESOURCES_TOTAL_BYTES // 1024} KiB total-size limit")- return make_bundle_resources(files=files)+ return filesdiff --git a/api/pipelex_api/exception_handlers.py b/api/pipelex_api/exception_handlers.pyindex c05d824a6..4158f0481 100644--- a/api/pipelex_api/exception_handlers.py+++ b/api/pipelex_api/exception_handlers.py@@ -341,11 +341,6 @@ _ERROR_TYPE_STATUS_OVERRIDES: dict[str, int] = {# sandboxed PipeFuncs, not in-process Python) → 403, the same status as the bundle# transport's custom-code gate."MethodStructuresRefusedError": 403,- # The files submitted in `resources` that the bundle's steps read when the method loads, its HTML templates,- # total more than they may, since they travel inline with the method wherever it runs. Only the parsed bundle- # says which files those are, so the library refuses them rather than this server's decoding: the request- # entity itself is too large → 413, as the decoder's own size refusals are.- "BundleResourcesTooLargeError": 413,}diff --git a/api/pipelex_api/routes/pipelex/crate_ops.py b/api/pipelex_api/routes/pipelex/crate_ops.pyindex 7916d110d..061173d18 100644--- a/api/pipelex_api/routes/pipelex/crate_ops.py+++ b/api/pipelex_api/routes/pipelex/crate_ops.py@@ -153,7 +153,7 @@ def resolve_requested_crate(request_data: MthdsFilesRequest) -> ResolvedClosure:mthds_contents=[item.content for item in selection.files],mthds_sources=[item.source for item in selection.files],# The files the closure's steps read, such as a PipeDocGen template file, which the load reads.- bundle_resources=decode_bundle_resources(resources=request_data.resources),+ submitted_files=decode_bundle_resources(resources=request_data.resources),)return ResolvedClosure(crate=crate, files=selection.files, manifest_main_pipe=selection.manifest_main_pipe)diff --git a/api/pipelex_api/routes/pipelex/pipeline.py b/api/pipelex_api/routes/pipelex/pipeline.pyindex 32a1501d8..6725eeb76 100644--- a/api/pipelex_api/routes/pipelex/pipeline.py+++ b/api/pipelex_api/routes/pipelex/pipeline.py@@ -16,7 +16,6 @@ from pipelex.libraries.method_requirements import ensure_served_method_requiremefrom pipelex.methods.structures_check import ensure_no_structured_content_pythonfrom pipelex.pipe_run.delivery_assignment import DeliveryAssignment, StorageTarget, WebhookTargetfrom pipelex.pipe_run.pipe_run_protocol import PipeRunProtocol-from pipelex.pipe_run.remote_dispatch import prepare_job_for_remote_dispatchfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.pipeline_response import PipelexRunResultExecute, PipelexRunResultStart, RunStatefrom pipelex.pipeline.pipeline_run_setup import pipeline_run_setup@@ -24,7 +23,6 @@ from pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.pipeline.validate_bundle_translation import translate_to_validate_bundle_errorfrom pipelex.reporting.usage_records import apply_tokens_usage_wire_shapefrom pipelex.runtime_bridge.exceptions import MissingBundleValidatorError, MissingOrchestratorError-from pipelex.runtime_bridge.orchestration_mode import DIRECT_ORCHESTRATION_MODEfrom pipelex.runtime_bridge.primitives.hydration import hydrate_working_memoryfrom pipelex.runtime_hub import get_bundle_validator_registry, get_orchestrator_registryfrom pipelex.system.environment import get_required_env@@ -234,18 +232,6 @@ def _pipe_output_from_run_output(run_output: PipelexPipeRunOutput) -> PipeOutput)-async def _prepare_job_for_dispatch(*, pipe_job: PipeJob, orchestration_mode: str) -> PipeJob:- """The job as the mode's orchestrator receives it: prepared to leave this process for every mode but `direct`.-- The files submitted with a bundle travel in the job's crate. An orchestrator other than the in-process `direct`- one, such as Temporal, runs the job outside this process, so the files its steps read only when they run move to- the run's storage first, dry runs included (`prepare_job_for_remote_dispatch`). A `direct` run keeps them inline.- """- if orchestration_mode == DIRECT_ORCHESTRATION_MODE:- return pipe_job- return await prepare_job_for_remote_dispatch(pipe_job=pipe_job)--class _OrchestratorPipeRun(PipeRunProtocol):"""Adapts a mode-selected orchestrator to the `PipeRunProtocol` the base `execute` drives.@@ -266,8 +252,7 @@ class _OrchestratorPipeRun(PipeRunProtocol):@overrideasync def run(self, pipe_job: PipeJob, *, delivery_assignment: DeliveryAssignment | None = None) -> PipeOutput:- dispatched_job = await _prepare_job_for_dispatch(pipe_job=pipe_job, orchestration_mode=self._orchestration_mode)- run_output = await self._orchestrator.execute(pipe_job=dispatched_job, delivery_assignment=delivery_assignment)+ run_output = await self._orchestrator.execute(pipe_job=pipe_job, delivery_assignment=delivery_assignment)return _pipe_output_from_run_output(run_output)@@ -441,7 +426,7 @@ class ApiRunner(PipelexMTHDSProtocol):# The packages the request ships, which the base `execute` threads too.methods_dirs=self.methods_dirs,# The files submitted with the contents, such as a template file, which the base `execute` threads too.- bundle_resources=self.bundle_resources,+ submitted_files=self.submitted_files,pipeline_run_id=pipeline_run_id,request_id=request_id,)@@ -480,8 +465,7 @@ class ApiRunner(PipelexMTHDSProtocol):# `PipelexPipeRunInput` (which carries no request_id / output_multiplicity /# dynamic_output_concept_ref and skips run registration + telemetry). `start` genuinely# enqueues the job and returns a `PipelexPipeDispatchAck` (ids only) immediately.- dispatched_job = await _prepare_job_for_dispatch(pipe_job=pipe_job, orchestration_mode=orchestration_mode)- dispatch_ack = await orchestrator.start(pipe_job=dispatched_job, delivery_assignment=delivery_assignment)+ dispatch_ack = await orchestrator.start(pipe_job=pipe_job, delivery_assignment=delivery_assignment)return PipelexRunResultStart(pipeline_run_id=resolved_pipeline_run_id,@@ -574,7 +558,7 @@ class ApiRunner(PipelexMTHDSProtocol):caller_identity=self.caller_identity,graph_pipe_code=graph_pipe_code,# The files submitted with the contents, which the validation's dry run reads, the template check included.- bundle_resources=self.bundle_resources,+ submitted_files=self.submitted_files,)# The core seam types its valid arm at the protocol-level ValidationReport (a leaf type)# to stay import-acyclic in core; every registered validator in fact produces the canonical@@ -945,7 +929,7 @@ async def execute(request: Request) -> JSONResponse:extras=extras.analytics_groups,library_dirs=source.library_dirs,methods_dirs=source.methods_dirs,- bundle_resources=decode_bundle_resources(resources=run_request.resources, bundle_files=source.bundle_files),+ submitted_files=decode_bundle_resources(resources=run_request.resources, bundle_files=source.bundle_files),)response = await runner.execute(pipe_code=source.pipe_code,@@ -1027,9 +1011,10 @@ async def start(run_request, extras = parsedscopes = _resolve_run_scopes(request, extras=extras)# The run source is materialized only for the synchronous setup phase: `start` builds the- # PipeJob (crate carrying the captured `pipe_func_files`) before it enqueues, so the temp dir- # (a bundle's, or a fetched package's) is no longer needed once `start` returns — cleanup on- # context exit is safe for the async path.+ # PipeJob before it enqueues, its crate naming each method tree by digest, so the temp dir (a+ # bundle's, or a fetched package's) is no longer needed once `start` returns — cleanup on context+ # exit is safe for the async path. The worker reads a tree's files through its own method file+ # store, which the deployment fills, never from this directory.with _run_source(run_request) as source:runner = ApiRunner(user_id=get_request_user_id(request),@@ -1038,7 +1023,7 @@ async def start(extras=extras.analytics_groups,library_dirs=source.library_dirs,methods_dirs=source.methods_dirs,- bundle_resources=decode_bundle_resources(resources=run_request.resources, bundle_files=source.bundle_files),+ submitted_files=decode_bundle_resources(resources=run_request.resources, bundle_files=source.bundle_files),)start_result = await runner.start(pipe_code=source.pipe_code,diff --git a/api/pipelex_api/routes/pipelex/validate.py b/api/pipelex_api/routes/pipelex/validate.pyindex 01f307b79..f6b9f1fe6 100644--- a/api/pipelex_api/routes/pipelex/validate.py+++ b/api/pipelex_api/routes/pipelex/validate.py@@ -405,7 +405,7 @@ async def validate_mthds(request: Request, request_data: ValidateRequest) -> JSOverdict = await ApiRunner(user_id=user_id,extras=request_data.analytics_groups,- bundle_resources=decode_bundle_resources(resources=request_data.resources),+ submitted_files=decode_bundle_resources(resources=request_data.resources),).validate_verdict(mthds_contents=request_data.mthds_contents,mthds_sources=request_data.mthds_sources,diff --git a/api/pipelex_api/schemas/models.py b/api/pipelex_api/schemas/models.pyindex 20d63e3e1..2c6786d7c 100644--- a/api/pipelex_api/schemas/models.py+++ b/api/pipelex_api/schemas/models.py@@ -15,7 +15,6 @@ from urllib.parse import urlparsefrom mthds.protocol.exceptions import PipelineRequestErrorfrom mthds.protocol.pipe_output import VariableMultiplicityfrom mthds.protocol.pipeline_inputs import PipelineInputs-from pipelex.core.bundle_resources.bundle_resource import MAX_LOAD_STAGE_RESOURCES_BYTESfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.methods.fetching import MethodProvenancefrom pipelex.pipeline.pipeline_response import PipelexRunResultExecute, PipelexRunResultStart@@ -54,9 +53,8 @@ RESOURCES_FIELD_DESCRIPTION = (f"By default at most {DEFAULT_MAX_RESOURCES_PER_REQUEST} files, {DEFAULT_MAX_RESOURCE_FILE_KIB} KiB each and "f"{DEFAULT_MAX_RESOURCES_TOTAL_KIB} KiB in all, decoded, counting the files a method bundle ships for its steps; a ""deployment sets its own with `MAX_RESOURCES_PER_REQUEST`, `MAX_RESOURCE_FILE_KIB` and `MAX_RESOURCES_TOTAL_KIB`. A file "- "both sent here and shipped in a method bundle must be the same. The `.html` template files, which travel inline with the "- f"method wherever it runs, may total {MAX_LOAD_STAGE_RESOURCES_BYTES // 1024} KiB at most, a fixed bound, or the request "- "is refused with a 413 `BundleResourcesTooLargeError`."+ "both sent here and shipped in a method bundle must be the same. The files make one method tree with the bundle at its "+ "root, which the run names by its digest: no file's bytes travel with the run, each being read where a step uses it.")diff --git a/api/tests/unit/test_bundle_resources_routes.py b/api/tests/unit/test_bundle_resources_routes.pyindex 5e9234d27..8a67b5831 100644--- a/api/tests/unit/test_bundle_resources_routes.py+++ b/api/tests/unit/test_bundle_resources_routes.py@@ -2,12 +2,11 @@Pins the wire across the routes that load inline contents: the files reach the step that reads them, a file no stepnames is refused as the request's fault, a path that cannot name a file inside the bundle is refused, and the count,-per-file and total limits are enforced before anything loads, and the files read when the method loads within a bound of-their own once it is parsed. A run handed to an orchestrator other than `direct` carries its office templates by-reference to the run's storage, never as bytes in the job.+per-file and total limits are enforced before anything loads. A run handed to an orchestrator other than `direct` names+the tree of the submitted files by its digest, in its crate and its run metadata, and carries none of their bytes.-The hermetic API environment has no document engine, so the step's engine is stubbed and its template check records-the bytes it reads, which is the read the engine's checker would be handed.+The hermetic API environment has no document engine, so the step's engine is stubbed and the dry print's template check+records the bytes it reads through the method file store, which is the read the engine's checker would be handed."""import base64@@ -20,16 +19,15 @@ from typing import Anyimport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from mthds.method_tree.digest import digest_of_contents, sha256_hex, tree_files_from_contents, tree_listing+from pipelex.cogt.content_generation.assignment_models import RenderDocumentAssignmentfrom pipelex.cogt.doc_gen.doc_gen_setting import DocGenSetting-from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.core.method_trees.method_files import StoredTree, read_method_file, read_stored_treesfrom pipelex.pipe_operators.doc_gen.pipe_doc_gen import PipeDocGen-from pipelex.pipe_operators.doc_gen.template_file_resource import bundle_resource_of_template_filefrom pipelex.pipe_run.delivery_assignment import DeliveryAssignmentfrom pipelex.pipe_run.pipe_job import PipeJobfrom pipelex.plugins.orchestrator_registry import OrchestratorRegistryfrom pipelex.runtime_bridge.payloads import PipelexPipeDispatchAck, PipelexPipeRunOutput-from pipelex.system.job_metadata import JobMetadata-from pipelex.tools.storage.in_memory_storage_provider import InMemoryStorageProviderfrom pytest_mock import MockerFixturefrom pipelex_api.api_config import ApiConfig@@ -38,9 +36,8 @@ from pipelex_api.routes import router as api_routerfrom tests.unit._constants import STUB_METHOD_ADDRESS_PIPELINE_NS = "pipelex_api.routes.pipelex.pipeline"-_REMOTE_DISPATCH_NS = "pipelex.pipe_run.remote_dispatch"_RESOURCES_NS = "pipelex_api.bundle_resources"-_LIBRARY_RESOURCES_NS = "pipelex.libraries.bundle_resources"+_PRINT_STAGE_NS = "pipelex.cogt.content_generation.doc_gen_generate"_TEMPLATE_PATH = "templates/invoice.docx"_TEMPLATE_BYTES = b"PK\x03\x04 a docx template"@@ -84,30 +81,35 @@ def _build_client() -> TestClient:def _stub_the_document_engine(mocker: MockerFixture) -> list[bytes]:- """Resolve every PipeDocGen step to an engine, and record the template bytes each template check finds for its step.+ """Resolve every PipeDocGen step to an engine, and record the template bytes each dry print's check reads for its step.- The check looks the step's template file up in the library it runs in, where the files sent with the bundle are held.+ The dry print reads the step's template file through the method file store, which serves the tree of the files sent+ with the bundle while the run's library holds it."""read_templates: list[bytes] = []- async def _record_template_check(pipe: PipeDocGen, *, job_metadata: JobMetadata, working_memory: WorkingMemory) -> None: # noqa: ARG001- assert pipe.template_file is not None- resource = bundle_resource_of_template_file(template_file=pipe.template_file)- assert resource is not None, f"the library holds no file for the template file '{pipe.template_file}'"- read_templates.append(await resource.read_bytes(storage_provider=InMemoryStorageProvider()))+ async def _record_template_check(*, render_assignment: RenderDocumentAssignment) -> None:+ template_file = render_assignment.composition.template_file+ assert template_file is not None+ read_templates.append(await read_method_file(file_ref=template_file.file, read_scope=render_assignment.job_metadata.run_metadata.read_scope))mocker.patch.object(PipeDocGen, "resolve_engine", return_value=DocGenSetting(model="stub-docx"))- mocker.patch.object(PipeDocGen, "check_template_file", autospec=True, side_effect=_record_template_check)+ mocker.patch(f"{_PRINT_STAGE_NS}._check_template_file", side_effect=_record_template_check)return read_templatesclass _RecordingTemporalStub:- """An async-capable orchestrator standing in for Temporal: it records the job it is handed and acks it."""+ """An async-capable orchestrator standing in for Temporal: it records the job it is handed, copies its trees and acks it.++ It copies every tree the job's crate names while it starts, as an orchestrator running the job out of process must+ before it returns, since the runner may drop the files and the library holding them as soon as it does.+ """supports_fire_and_forget = Truedef __init__(self) -> None:self.pipe_jobs: list[PipeJob] = []+ self.copied_trees: list[StoredTree] = []async def execute(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeRunOutput:msg = "/start drives the fire-and-forget `start` arm; `execute` must not be reached."@@ -115,19 +117,42 @@ class _RecordingTemporalStub:async def start(self, *, pipe_job: PipeJob, delivery_assignment: DeliveryAssignment | None) -> PipelexPipeDispatchAck: # noqa: ARG002self.pipe_jobs.append(pipe_job)+ crate = pipe_job.library_crate+ assert crate is not None+ self.copied_trees.extend(await read_stored_trees(tree_digests=crate.tree_digests(), read_scope=pipe_job.job_metadata.run_metadata.read_scope))return PipelexPipeDispatchAck(pipeline_run_id=pipe_job.job_metadata.run_metadata.pipeline_run_id, workflow_id="wf-1")-def _record_dispatches_to_a_temporal_like_orchestrator(mocker: MockerFixture) -> tuple[_RecordingTemporalStub, InMemoryStorageProvider]:- """Make Temporal the deployment's orchestrator, recording each job it is handed, over an in-memory run storage."""- storage_provider = InMemoryStorageProvider()- mocker.patch(f"{_REMOTE_DISPATCH_NS}.get_storage_provider", return_value=storage_provider)+def _record_dispatches_to_a_temporal_like_orchestrator(mocker: MockerFixture) -> _RecordingTemporalStub:+ """Make Temporal the deployment's orchestrator, recording each job it is handed."""mocker.patch(f"{_PIPELINE_NS}.get_api_config", return_value=ApiConfig(orchestration_mode="temporal", allow_request_orchestration_mode_override=False))orchestrator = _RecordingTemporalStub()mocker.patch(f"{_PIPELINE_NS}.get_orchestrator_registry", return_value=OrchestratorRegistry({"temporal": orchestrator}))- return orchestrator, storage_provider+ return orchestrator+++def _assert_the_job_names_the_tree_of(*, pipe_job: PipeJob, files: Mapping[str, bytes], pipe_ref: str = "invoicing.print_invoice") -> None:+ """The job's crate and run metadata name the tree of these files by digest, and the job carries none of their bytes."""+ crate = pipe_job.library_crate+ assert crate is not None+ tree_digest = digest_of_contents(dict(files))+ assert crate.tree_bundles[pipe_ref].tree_digest == tree_digest+ run_metadata = pipe_job.job_metadata.run_metadata+ assert run_metadata.method_tree_digest == tree_digest+ assert run_metadata.crate_fingerprint == crate.fingerprint+ job_json = pipe_job.model_dump_json()+ for data in files.values():+ assert _b64(data) not in job_json+++def _assert_the_orchestrator_copied_the_tree_of(*, orchestrator: _RecordingTemporalStub, files: Mapping[str, bytes]) -> None:+ """The orchestrator read the tree of these files, its listing and each of its files, while it started."""+ (copied_tree,) = orchestrator.copied_trees+ assert copied_tree.tree_digest == digest_of_contents(dict(files))+ assert copied_tree.listing == tree_listing(tree_files_from_contents(dict(files)))+ assert copied_tree.blobs == {sha256_hex(data): data for data in files.values()}def _zip_b64(files: Mapping[str, str | bytes]) -> str:@@ -200,21 +225,6 @@ class TestBundleResourcesRoutes:# 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:- """An HTML template travels inline with the method wherever it runs, so the files read at load are bounded in total."""- _stub_the_document_engine(mocker)- mocker.patch(f"{_LIBRARY_RESOURCES_NS}.MAX_LOAD_STAGE_RESOURCES_BYTES", 1024)- 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)-- 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"),[@@ -301,10 +311,10 @@ class TestBundleResourcesRoutes:assert "resources accompany the bundle" in _assert_problem(response, status=422, error_type="ValidationError")- def test_a_run_handed_to_a_remote_orchestrator_carries_its_template_by_reference(self, mocker: MockerFixture) -> None:- """`/start` on a Temporal-like orchestrator: the job's crate names the stored file, and the run's storage holds its bytes."""+ def test_a_run_handed_to_a_remote_orchestrator_names_the_tree_of_its_files_by_digest(self, mocker: MockerFixture) -> None:+ """`/start` on a Temporal-like orchestrator: the job's crate and run metadata name the tree, and the job carries none of its files."""_stub_the_document_engine(mocker)- orchestrator, storage_provider = _record_dispatches_to_a_temporal_like_orchestrator(mocker)+ orchestrator = _record_dispatches_to_a_temporal_like_orchestrator(mocker)response = _build_client().post("/v1/start",@@ -313,30 +323,37 @@ class TestBundleResourcesRoutes:assert response.status_code == 202, response.text(pipe_job,) = orchestrator.pipe_jobs- assert pipe_job.library_crate is not None- stored = pipe_job.library_crate.bundle_resources[_TEMPLATE_PATH]- assert stored.content_b64 is None- assert stored.uri is not None- assert stored.uri.startswith(f"pipelex-storage://{pipe_job.job_metadata.run_metadata.storage_scope}/assets/bundle/")- assert storage_provider.root[stored.uri.removeprefix("pipelex-storage://")] == _TEMPLATE_BYTES- assert _b64(_TEMPLATE_BYTES) not in pipe_job.model_dump_json()+ _assert_the_job_names_the_tree_of(pipe_job=pipe_job, files={_TEMPLATE_PATH: _TEMPLATE_BYTES})+ _assert_the_orchestrator_copied_the_tree_of(orchestrator=orchestrator, files={_TEMPLATE_PATH: _TEMPLATE_BYTES})@pytest.mark.parametrize(- ("bundle_files", "resources"),+ ("bundle_files", "resources", "tree_files"),[- pytest.param({"invoicing.mthds": _INVOICE_MTHDS, _TEMPLATE_PATH: _TEMPLATE_BYTES}, None, id="beside_the_bundle"),- pytest.param({"methods/invoicing.mthds": _INVOICE_MTHDS, f"methods/{_TEMPLATE_PATH}": _TEMPLATE_BYTES}, None, id="in_a_directory"),pytest.param(- {"invoicing.mthds": _INVOICE_MTHDS, _TEMPLATE_PATH: _TEMPLATE_BYTES}, {_TEMPLATE_PATH: _b64(_TEMPLATE_BYTES)}, id="also_in_resources"+ {"invoicing.mthds": _INVOICE_MTHDS, _TEMPLATE_PATH: _TEMPLATE_BYTES}, None, {_TEMPLATE_PATH: _TEMPLATE_BYTES}, id="beside_the_bundle"+ ),+ # The bundle's other files are written where it ships them, and its step's file is keyed by the path the step+ # names, both in the one tree the bundle's contents sit at the root of.+ pytest.param(+ {"methods/invoicing.mthds": _INVOICE_MTHDS, f"methods/{_TEMPLATE_PATH}": _TEMPLATE_BYTES},+ None,+ {_TEMPLATE_PATH: _TEMPLATE_BYTES, f"methods/{_TEMPLATE_PATH}": _TEMPLATE_BYTES},+ id="in_a_directory",+ ),+ pytest.param(+ {"invoicing.mthds": _INVOICE_MTHDS, _TEMPLATE_PATH: _TEMPLATE_BYTES},+ {_TEMPLATE_PATH: _b64(_TEMPLATE_BYTES)},+ {_TEMPLATE_PATH: _TEMPLATE_BYTES},+ id="also_in_resources",),],)def test_a_method_bundle_carries_the_office_template_it_ships_to_its_step(- self, mocker: MockerFixture, bundle_files: dict[str, str | bytes], resources: dict[str, str] | None+ self, mocker: MockerFixture, bundle_files: dict[str, str | bytes], resources: dict[str, str] | None, tree_files: dict[str, bytes]) -> None:- """A template file shipped beside the bundle's `.mthds` file reaches its step as one sent in `resources` does, by reference."""+ """A template file shipped beside the bundle's `.mthds` file joins the tree of the submitted files as one sent in `resources` does."""_stub_the_document_engine(mocker)- orchestrator, storage_provider = _record_dispatches_to_a_temporal_like_orchestrator(mocker)+ orchestrator = _record_dispatches_to_a_temporal_like_orchestrator(mocker)body: dict[str, Any] = {"bundle_b64": _zip_b64(bundle_files), "inputs": _INVOICE_INPUTS}if resources is not None:body["resources"] = resources@@ -345,16 +362,16 @@ class TestBundleResourcesRoutes:assert response.status_code == 202, response.text(pipe_job,) = orchestrator.pipe_jobs- assert pipe_job.library_crate is not None- assert set(pipe_job.library_crate.bundle_resources) == {_TEMPLATE_PATH}- stored = pipe_job.library_crate.bundle_resources[_TEMPLATE_PATH]- assert stored.uri is not None- assert storage_provider.root[stored.uri.removeprefix("pipelex-storage://")] == _TEMPLATE_BYTES-- def test_a_method_bundle_s_files_map_carries_the_html_template_it_ships_inline(self, mocker: MockerFixture) -> None:- """An HTML template is read while the method loads, so it travels inline in the job, from a `files` map as from a zip."""+ _assert_the_job_names_the_tree_of(pipe_job=pipe_job, files=tree_files)+ _assert_the_orchestrator_copied_the_tree_of(orchestrator=orchestrator, files=tree_files)++ def test_a_method_bundle_s_files_map_names_the_html_template_it_ships_by_its_tree(self, mocker: MockerFixture) -> None:+ """An HTML template is read and checked while the method loads, and the job names it by its tree as an office one.++ A `files` map ships it as a zip does.+ """_stub_the_document_engine(mocker)- orchestrator, _ = _record_dispatches_to_a_temporal_like_orchestrator(mocker)+ orchestrator = _record_dispatches_to_a_temporal_like_orchestrator(mocker)html_mthds = _INVOICE_MTHDS.replace('format = "docx"', 'format = "pdf"').replace(_TEMPLATE_PATH, "templates/invoice.html")html_template = "<h1>{{ invoice.number }}</h1>"@@ -365,8 +382,9 @@ class TestBundleResourcesRoutes:assert response.status_code == 202, response.text(pipe_job,) = orchestrator.pipe_jobs- assert pipe_job.library_crate is not None- assert pipe_job.library_crate.bundle_resources["templates/invoice.html"].inline_bytes() == html_template.encode("utf-8")+ _assert_the_job_names_the_tree_of(pipe_job=pipe_job, files={"templates/invoice.html": html_template.encode("utf-8")})+ _assert_the_orchestrator_copied_the_tree_of(orchestrator=orchestrator, files={"templates/invoice.html": html_template.encode("utf-8")})+ assert "invoice.number }}" not in pipe_job.model_dump_json()@pytest.mark.parametrize(("bundle_files", "resources"),diff --git a/api/tests/unit/test_method_requirements_refusal.py b/api/tests/unit/test_method_requirements_refusal.pyindex a55dfb638..22888d739 100644--- a/api/tests/unit/test_method_requirements_refusal.py+++ b/api/tests/unit/test_method_requirements_refusal.py@@ -9,7 +9,7 @@ the deployment's fault, never the caller's.import asyncioimport sys-from collections.abc import Callable, Generator, Sequence+from collections.abc import Callable, Generator, Mapping, Sequencefrom pathlib import Pathimport pytest@@ -17,7 +17,6 @@ from fastapi import FastAPIfrom fastapi.testclient import TestClientfrom pipelex.base_exceptions import DisclosureMode, ErrorReportfrom pipelex.config import get_config-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.interpreter_hub import get_interpreter_hubfrom pipelex.libraries.exceptions import MethodRequirementsNotMetErrorfrom pipelex.pipe_run.delivery_assignment import DeliveryAssignment@@ -106,7 +105,7 @@ class _UnreachableValidator:library_dirs: Sequence[Path] | None, # noqa: ARG002caller_identity: CallerIdentity | None, # noqa: ARG002graph_pipe_code: str | None, # noqa: ARG002- bundle_resources: BundleResources | None, # noqa: ARG002+ submitted_files: Mapping[str, bytes] | None, # noqa: ARG002) -> ErrorReport:self.calls += 1msg = "A method refused for its requirements must not reach the validator."diff --git a/api/tests/unit/test_validate_caller_identity.py b/api/tests/unit/test_validate_caller_identity.pyindex 0eab6beec..c7da86257 100644--- a/api/tests/unit/test_validate_caller_identity.py+++ b/api/tests/unit/test_validate_caller_identity.py@@ -12,7 +12,7 @@ The user comes from `request.state.user`, which the auth layer sets; a tiny middfor it here. The groups come from the body and are refused at the wire exactly as on a run."""-from collections.abc import Awaitable, Callable, Sequence+from collections.abc import Awaitable, Callable, Mapping, Sequencefrom pathlib import Pathfrom typing import Any@@ -20,7 +20,6 @@ import pytestfrom fastapi import FastAPI, Request, Responsefrom fastapi.testclient import TestClientfrom pipelex.base_exceptions import ErrorReport, ValidationErrorCategory, ValidationErrorItem-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.pipeline.validate_in_process import validate_bundles_in_processfrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistryfrom pipelex.system.caller_identity import CallerIdentity@@ -65,7 +64,7 @@ class _RecordingBundleValidator:library_dirs: Sequence[Path] | None, # noqa: ARG002caller_identity: CallerIdentity | None,graph_pipe_code: str | None, # noqa: ARG002- bundle_resources: BundleResources | None, # noqa: ARG002+ submitted_files: Mapping[str, bytes] | None, # noqa: ARG002) -> ErrorReport:self.caller_identities.append(caller_identity)return ErrorReport(diff --git a/api/tests/unit/test_validate_dispatch.py b/api/tests/unit/test_validate_dispatch.pyindex 34d98df3b..b896b66f1 100644--- a/api/tests/unit/test_validate_dispatch.py+++ b/api/tests/unit/test_validate_dispatch.py@@ -10,7 +10,7 @@ override is a 403). The `direct` path is covered end-to-end by the existing `/vathe dispatch is backend-agnostic, not direct-only."""-from collections.abc import Sequence+from collections.abc import Mapping, Sequencefrom pathlib import Pathfrom typing import Any@@ -18,7 +18,6 @@ import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClientfrom pipelex.base_exceptions import ErrorDomain, ErrorReport, PipelexConfigError, ValidationErrorCategory, ValidationErrorItem-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistryfrom pipelex.runtime_bridge.exceptions import MissingBundleValidatorErrorfrom pipelex.system.caller_identity import CallerIdentity@@ -50,7 +49,7 @@ class _StubBundleValidator:library_dirs: Sequence[Path] | None,caller_identity: CallerIdentity | None,graph_pipe_code: str | None,- bundle_resources: BundleResources | None,+ submitted_files: Mapping[str, bytes] | None,) -> ErrorReport:self.calls.append({@@ -60,7 +59,7 @@ class _StubBundleValidator:"library_dirs": library_dirs,"caller_identity": caller_identity,"graph_pipe_code": graph_pipe_code,- "bundle_resources": bundle_resources,+ "submitted_files": submitted_files,})if self._error is not None:diff --git a/api/tests/unit/test_validate_graph_target.py b/api/tests/unit/test_validate_graph_target.pyindex 22e2155f4..8ae4338d1 100644--- a/api/tests/unit/test_validate_graph_target.py+++ b/api/tests/unit/test_validate_graph_target.py@@ -8,14 +8,13 @@ pipe. These tests read the target twice: off the graph the real in-process validoff the call a dispatched validator receives."""-from collections.abc import Callable, Sequence+from collections.abc import Callable, Mapping, Sequencefrom pathlib import Pathfrom typing import Anyfrom fastapi import FastAPIfrom fastapi.testclient import TestClientfrom pipelex.base_exceptions import ErrorReport, ValidationErrorCategory, ValidationErrorItem-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistryfrom pipelex.system.caller_identity import CallerIdentityfrom pytest_mock import MockerFixture@@ -53,7 +52,7 @@ class _RecordingBundleValidator:library_dirs: Sequence[Path] | None, # noqa: ARG002caller_identity: CallerIdentity | None, # noqa: ARG002graph_pipe_code: str | None,- bundle_resources: BundleResources | None, # noqa: ARG002+ submitted_files: Mapping[str, bytes] | None, # noqa: ARG002) -> ErrorReport:self.graph_pipe_codes.append(graph_pipe_code)return ErrorReport(diff --git a/docs/api-server/error-responses.md b/docs/api-server/error-responses.mdindex 534514e3b..443ed0351 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), `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`).+- `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`, `BundleResourcePathError`, 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 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`.-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 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.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/api-server/openapi/pipelex-api.openapi.yaml b/docs/api-server/openapi/pipelex-api.openapi.yamlindex 9482970ae..bd1bc266d 100644--- a/docs/api-server/openapi/pipelex-api.openapi.yaml+++ b/docs/api-server/openapi/pipelex-api.openapi.yaml@@ -193,8 +193,8 @@ paths:422 `BundleResourceNotNamedError`. By default at most 32 files, 5120 KiB each and 10240 KiB in all, decoded,counting the files a method bundle ships for its steps; a deployment sets its own with `MAX_RESOURCES_PER_REQUEST`,`MAX_RESOURCE_FILE_KIB` and `MAX_RESOURCES_TOTAL_KIB`. A file both sent here and shipped in a method bundle- must be the same. The `.html` template files, which travel inline with the method wherever it runs, may- total 512 KiB at most, a fixed bound, or the request is refused with a 413 `BundleResourcesTooLargeError`.'+ must be the same. The files make one method tree with the bundle at its root, which the run names by its+ digest: no file''s bytes travel with the run, each being read where a step uses it.'orchestration_mode:anyOf:- type: string@@ -466,8 +466,8 @@ paths:422 `BundleResourceNotNamedError`. By default at most 32 files, 5120 KiB each and 10240 KiB in all, decoded,counting the files a method bundle ships for its steps; a deployment sets its own with `MAX_RESOURCES_PER_REQUEST`,`MAX_RESOURCE_FILE_KIB` and `MAX_RESOURCES_TOTAL_KIB`. A file both sent here and shipped in a method bundle- must be the same. The `.html` template files, which travel inline with the method wherever it runs, may- total 512 KiB at most, a fixed bound, or the request is refused with a 413 `BundleResourcesTooLargeError`.'+ must be the same. The files make one method tree with the bundle at its root, which the run names by its+ digest: no file''s bytes travel with the run, each being read where a step uses it.'pipeline_run_id:anyOf:- type: string@@ -1577,9 +1577,9 @@ components:colon. Every file must be named by a step, or the request is refused with a 422 `BundleResourceNotNamedError`.By default at most 32 files, 5120 KiB each and 10240 KiB in all, decoded, counting the files a method bundle shipsfor its steps; a deployment sets its own with `MAX_RESOURCES_PER_REQUEST`, `MAX_RESOURCE_FILE_KIB` and `MAX_RESOURCES_TOTAL_KIB`.- A file both sent here and shipped in a method bundle must be the same. The `.html` template files, which travel- inline with the method wherever it runs, may total 512 KiB at most, a fixed bound, or the request is refused with- a 413 `BundleResourcesTooLargeError`.'+ A file both sent here and shipped in a method bundle must be the same. The files make one method tree with the+ bundle at its root, which the run names by its digest: no file''s bytes travel with the run, each being read where+ a step uses it.'kind:$ref: '#/components/schemas/CodegenRouteKind'description: What to project. `types` projects the crate's concept set into typed models.@@ -3966,9 +3966,9 @@ components:colon. Every file must be named by a step, or the request is refused with a 422 `BundleResourceNotNamedError`.By default at most 32 files, 5120 KiB each and 10240 KiB in all, decoded, counting the files a method bundle shipsfor its steps; a deployment sets its own with `MAX_RESOURCES_PER_REQUEST`, `MAX_RESOURCE_FILE_KIB` and `MAX_RESOURCES_TOTAL_KIB`.- A file both sent here and shipped in a method bundle must be the same. The `.html` template files, which travel- inline with the method wherever it runs, may total 512 KiB at most, a fixed bound, or the request is refused with- a 413 `BundleResourcesTooLargeError`.'+ A file both sent here and shipped in a method bundle must be the same. The files make one method tree with the+ bundle at its root, which the run names by its digest: no file''s bytes travel with the run, each being read where+ a step uses it.'type: objecttitle: MthdsFilesRequestdescription: 'Shared closure selector for the resolve/codegen routes: inline `files[]` XOR a `method_ref`.@@ -5045,9 +5045,9 @@ components:colon. Every file must be named by a step, or the request is refused with a 422 `BundleResourceNotNamedError`.By default at most 32 files, 5120 KiB each and 10240 KiB in all, decoded, counting the files a method bundle shipsfor its steps; a deployment sets its own with `MAX_RESOURCES_PER_REQUEST`, `MAX_RESOURCE_FILE_KIB` and `MAX_RESOURCES_TOTAL_KIB`.- A file both sent here and shipped in a method bundle must be the same. The `.html` template files, which travel- inline with the method wherever it runs, may total 512 KiB at most, a fixed bound, or the request is refused with- a 413 `BundleResourcesTooLargeError`.'+ A file both sent here and shipped in a method bundle must be the same. The files make one method tree with the+ bundle at its root, which the run names by its digest: no file''s bytes travel with the run, each being read where+ a step uses it.'pipe_ref:anyOf:- type: string@@ -7729,9 +7729,9 @@ components:colon. Every file must be named by a step, or the request is refused with a 422 `BundleResourceNotNamedError`.By default at most 32 files, 5120 KiB each and 10240 KiB in all, decoded, counting the files a method bundle shipsfor its steps; a deployment sets its own with `MAX_RESOURCES_PER_REQUEST`, `MAX_RESOURCE_FILE_KIB` and `MAX_RESOURCES_TOTAL_KIB`.- A file both sent here and shipped in a method bundle must be the same. The `.html` template files, which travel- inline with the method wherever it runs, may total 512 KiB at most, a fixed bound, or the request is refused with- a 413 `BundleResourcesTooLargeError`.'+ A file both sent here and shipped in a method bundle must be the same. The files make one method tree with the+ bundle at its root, which the run names by its digest: no file''s bytes travel with the run, each being read where+ a step uses it.'render:items:type: stringdiff --git a/docs/api-server/pipe-run.md b/docs/api-server/pipe-run.mdindex 723af4ea4..aeb9d0eb1 100644--- a/docs/api-server/pipe-run.md+++ b/docs/api-server/pipe-run.md@@ -38,7 +38,7 @@ Execute a Pipelex pipeline with flexible inputs and wait for completion.- `bundle_b64` (string, optional): **Pipelex-API extension.** Base64-encoded zip of a whole method bundle, which may carry the method packages it calls — see [Shipping a method bundle](#shipping-a-method-bundle-custom-pipefunc). Mutually exclusive with `files`.- `files` (dict[str, str], optional): **Pipelex-API extension.** The same bundle as a `{relative_path: text}` map (the unzipped equivalent of `bundle_b64`). Mutually exclusive with `bundle_b64`.- `method_ref` (string, optional): **Pipelex-API extension.** Run a published method by address instead of inline source — see [Running a method by address](#running-a-method-by-address-method_ref). Mutually exclusive with `mthds_contents` and with a method bundle; `pipe_code` may accompany it to override the package's `main_pipe`.-- `resources` (dict[str, str], 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](pipe-validate.md#sending-the-files-the-steps-read-resources). It accompanies `mthds_contents` or a method bundle; beside `method_ref`, or with no bundle at all, it is a 422. On an orchestrator that runs the job remotely, such as Temporal, each office template file is stored under the run's `storage_scope` (`assets/bundle/`) before the run is dispatched, so the job carries a reference rather than the bytes; the `.html` template files, which travel inline, are bounded to 512 KiB in total.+- `resources` (dict[str, str], 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](pipe-validate.md#sending-the-files-the-steps-read-resources). It accompanies `mthds_contents` or a method bundle; beside `method_ref`, or with no bundle at all, it is a 422. The files make one method tree with the bundles at its root, and the job names that tree by its digest and carries none of its files: the step that reads one, on an orchestrator that runs the job remotely such as Temporal included, reads it through the deployment's method file store.- `storage_scope` (string, optional): **Pipelex-API extension.** The prefix every object this run writes lands under — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).- `read_scope` (string, optional): **Pipelex-API extension.** The prefix every stored object this run reads must lie under — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).- `analytics_groups` (dict[str, str], optional): **Pipelex-API extension.** The groups this run's telemetry belongs to, such as `{"organization": "org_acme"}` — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).@@ -119,7 +119,7 @@ Start a pipeline execution and get its `pipeline_run_id` back with a `202` ack.- `bundle_b64` (string, optional): **Pipelex-API extension.** Base64-encoded zip of a whole method bundle, which may carry the method packages it calls — see [Shipping a method bundle](#shipping-a-method-bundle-custom-pipefunc). Mutually exclusive with `files`.- `files` (dict[str, str], optional): **Pipelex-API extension.** The same bundle as a `{relative_path: text}` map (the unzipped equivalent of `bundle_b64`). Mutually exclusive with `bundle_b64`.- `method_ref` (string, optional): **Pipelex-API extension.** Run a published method by address instead of inline source — see [Running a method by address](#running-a-method-by-address-method_ref). Mutually exclusive with `mthds_contents` and with a method bundle; `pipe_code` may accompany it to override the package's `main_pipe`.-- `resources` (dict[str, str], 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](pipe-validate.md#sending-the-files-the-steps-read-resources). It accompanies `mthds_contents` or a method bundle; beside `method_ref`, or with no bundle at all, it is a 422. On an orchestrator that runs the job remotely, such as Temporal, each office template file is stored under the run's `storage_scope` (`assets/bundle/`) before the run is dispatched, so the job carries a reference rather than the bytes; the `.html` template files, which travel inline, are bounded to 512 KiB in total.+- `resources` (dict[str, str], 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](pipe-validate.md#sending-the-files-the-steps-read-resources). It accompanies `mthds_contents` or a method bundle; beside `method_ref`, or with no bundle at all, it is a 422. The files make one method tree with the bundles at its root, and the job names that tree by its digest and carries none of its files: the step that reads one, on an orchestrator that runs the job remotely such as Temporal included, reads it through the deployment's method file store.- `storage_scope` (string, optional): **Pipelex-API extension.** The prefix every object this run writes lands under — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).- `read_scope` (string, optional): **Pipelex-API extension.** The prefix every stored object this run reads must lie under — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).- `analytics_groups` (dict[str, str], optional): **Pipelex-API extension.** The groups this run's telemetry belongs to, such as `{"organization": "org_acme"}` — see [Host-supplied run context](#host-supplied-run-context-storage_scope-and-analytics_groups).@@ -230,7 +230,7 @@ The server materializes the bundle into a temporary library directory for the ru}```-**Template files shipped in the bundle.** A file a step reads beside its bundle, such as a `PipeDocGen` step's `template_file`, can ship in the bundle, relative to the `.mthds` file whose step names it, as it sits beside a bundle on disk. The bundle's `.mthds` files load as content, so the server sends each such file with them as if it had come in [`resources`](pipe-validate.md#sending-the-files-the-steps-read-resources): it is counted against the same limits as `resources`, together with them, an office template file is stored with the run when the run goes to a remote orchestrator, and an `.html` one is bounded with the files read when the method loads. Every `.mthds` file of the bundle is read as sitting in one directory, so two different files a step reads under one path, shipped beside two `.mthds` files or shipped and also sent in `resources`, are a `422 InvalidResourcePath`; the same file in both is accepted.+**Template files shipped in the bundle.** A file a step reads beside its bundle, such as a `PipeDocGen` step's `template_file`, can ship in the bundle, relative to the `.mthds` file whose step names it, as it sits beside a bundle on disk. The bundle's `.mthds` files load as content, so the server sends each such file with them as if it had come in [`resources`](pipe-validate.md#sending-the-files-the-steps-read-resources): it is counted against the same limits as `resources`, together with them, and it joins the one method tree of the request's files, which the run names by its digest and a remote orchestrator copies into its deployment's method file store as it dispatches the run. Every `.mthds` file of the bundle is read as sitting in one directory, so two different files a step reads under one path, shipped beside two `.mthds` files or shipped and also sent in `resources`, are a `422 InvalidResourcePath`; the same file in both is accepted.**Ingest guards.** Bundles are bounded at ingest and rejected with a clear error (never a silent truncation):diff --git a/docs/api-server/pipe-validate.md b/docs/api-server/pipe-validate.mdindex 62786775f..3c6abd39b 100644--- a/docs/api-server/pipe-validate.md+++ b/docs/api-server/pipe-validate.md@@ -171,7 +171,7 @@ A bundle sent as content has no directory, so a file one of its steps reads from- **Each value is the file's bytes** in standard base64 (RFC 4648, with padding). A value that does not decode is a **400** `InvalidBase64`.- **Every file must be one a step names.** A file no step of the bundle reads is a **422** `BundleResourceNotNamedError`, whose `detail` lists the unnamed paths: a misspelled key fails loudly rather than leaving its step without its file. This is a request error, never an `is_valid: false` verdict.- **The sizes are bounded**: at most `MAX_RESOURCES_PER_REQUEST` files (32 by default), each at most `MAX_RESOURCE_FILE_KIB` once decoded (5 MiB by default), and at most `MAX_RESOURCES_TOTAL_KIB` across the request (10 MiB by default), counting the files a method bundle ships for its steps. A request over any of them is a **413** `PayloadTooLarge`, an oversized file refused on its encoded length before it is decoded. The whole body stays under `MAX_REQUEST_BODY_MIB` as well.-- **The files read when the method loads are bounded too**: the `.html` template files, which travel inline with the method wherever it runs, a remote orchestrator's payloads included, may total 512 KiB at most once decoded. That bound is fixed, sized well under Temporal's 2 MB payload limit, and checked once the bundle is parsed, since only its steps say which files those are: a request over it is a **413** `BundleResourcesTooLargeError` naming the files and the limit. An office template file is not counted, since a run handed to a remote orchestrator carries it by reference to the run's storage.+- **The files make one method tree**, with the request's bundles at its root. A run names that tree by its digest, as it names the tree of a method loaded from a directory, and carries none of the files in its payloads, a remote orchestrator's included: the step that reads one reads it from the tree, through the deployment's method file store. Two files colliding in one tree, such as two keys equal once case-folded, are a **422** `BundleResourcePathError`.The files are checked as files on disk are. An `.html` template file is checked against the step's inputs when the bundle loads, and the document engine's template check runs on an office template file in the validation's dry run, where its errors are validation errors on the step. A step whose `template_file` could not be a key, being empty or absolute, or holding a `..` segment, a backslash, a colon or a NUL character, is refused when its bundle is parsed, whatever the request sends: the verdict's one item is a `blueprint_validation` item located at the step by its `pipe_code` and by `field_path` `pipe.<code>`, whose message names the field without repeating the path. A step whose `template_file` could be a key but was not sent is refused at load, and the verdict's `validation_errors[]` says the file was not supplied with its bundle and names the key it is expected under.@@ -192,7 +192,7 @@ A validation is not a run, but it still emits telemetry: the sweep's `pipe_dry_rOnly conditions where the endpoint could not produce a verdict are non-2xx, rendered as [RFC 7807 problem documents](error-responses.md):- **422** — a malformed request body, an `mthds_sources` / `mthds_contents` length mismatch, both/neither of `mthds_contents` / `method_ref`, or a malformed `analytics_groups` (`error_type` `InvalidAnalyticsGroups`) — request-shape errors caught before the runtime.-- **422**, **413** and **400** on `resources` — a path that cannot name a file inside the bundle (`InvalidResourcePath`), a file no step names (`BundleResourceNotNamedError`), a file or a request over its size limit (`PayloadTooLarge`), `.html` template files over the load-stage bound (`BundleResourcesTooLargeError`), or a value that is not base64 (`InvalidBase64`) — see [Sending the files the steps read](#sending-the-files-the-steps-read-resources).+- **422**, **413** and **400** on `resources` — a path that cannot name a file inside the bundle (`InvalidResourcePath`), a file no step names (`BundleResourceNotNamedError`), files that cannot make one tree (`BundleResourcePathError`), a file or a request over its size limit (`PayloadTooLarge`), or a value that is not base64 (`InvalidBase64`) — see [Sending the files the steps read](#sending-the-files-the-steps-read-resources).- **401 / 403** — unauthenticated / forbidden (including a per-request `orchestration_mode` override the deployment does not allow).- **`method_ref` resolution failures** — a selector that could not be resolved produced no verdict, so it is never rendered as `is_valid: false`: a malformed reference or a failed fetch is a **422**, no matching package in the repository a **404**, and the custom-Python policy (the sandbox gate, the structures refusal) a **403** — the same statuses and `error_type`s as on the run routes (see the [error table](pipe-run.md#running-a-method-by-address-method_ref)).- **5xx** — a server fault (including a host-wiring programmer error, surfaced as `PipelexUnexpectedError`).diff --git a/docs/building-methods/method-trees.md b/docs/building-methods/method-trees.mdindex 1855d1a59..b525eeacf 100644--- a/docs/building-methods/method-trees.md+++ b/docs/building-methods/method-trees.md@@ -34,7 +34,7 @@ A file a bundle names, such as a [`PipeDocGen`](pipes/pipe-operators/PipeDocGen.## Python modules-A [`PipeFunc`](pipes/pipe-operators/PipeFunc.md) step names its function by its import path from the root of the tree, such as `funcs.totals.compute_totals` for the function `compute_totals` of `funcs/totals.py`, and its module is found among the tree's files. A run imports the tree's modules with the root first on the import path, refuses the import of a file the membership rule keeps out, such as a `.gitignore`d module, and writes no `__pycache__` into the tree. On a sandbox-hosted deployment, every file of the tree except its `.mthds` files travels with each call of the step.+A [`PipeFunc`](pipes/pipe-operators/PipeFunc.md) step names its function by its import path from the root of the tree, such as `funcs.totals.compute_totals` for the function `compute_totals` of `funcs/totals.py`, and its module is found among the tree's files. A run imports the tree's modules with the root first on the import path, refuses the import of a file the membership rule keeps out, such as a `.gitignore`d module, and writes no `__pycache__` into the tree. On a sandbox-hosted deployment, each call of the step receives every file of the tree except its `.mthds` files, read by the tree's digest where the call is made (see [Inside a run](#inside-a-run)).## Library directories@@ -82,3 +82,11 @@ max_total_bytes = 4294967296These limits are not the hosted API's. A deployment sets its own, which a local run cannot know, and applying them locally would refuse a method rooted in a cluttered folder that loads today; a sender warned of the hosted limits before it sends is the hosted run's concern, not a local load's.Every listing computes the tree's digest, the SHA-256 of its canonical listing of paths, hashes and sizes, which names the exact files of a method: two folders with the same files have the same digest. A local run records the digest of the tree it ran. `pipelex run bundle` prints it with the run's recap and writes `method_tree.json` into the run's output folder, holding the digest, the tree's root on this machine, its entry and each file's path, hash and size. `pipelex-agent run bundle` adds `method_tree_digest` to the run's output file and, with `--with-memory`, to its output.++## Inside a run++A run carries no file of its method. The library a run hands from step to step, its crate, names the tree each bundle belongs to by the tree's digest and the bundle by its path in the tree, and a step names a file it reads, such as a `PipeDocGen` step's template file, the same way. The files a request submits with bundles sent as text make a tree too, with those bundles at its root, named by its digest like a folder's.++Every method file is read where reading is allowed, at the moment a step uses it: a `PipeDocGen` step's template file at its print, and the files of a `PipeFunc` call where the call is made. Each read goes through the method file store, by the tree's digest and under the run's read scope, and is checked against the digest: the listing read must have that digest, and each file the hash the listing gives it. Locally, the store serves the trees the process's libraries hold, from the folder they were listed from or from the files submitted with them. A distributed orchestrator, such as Temporal, runs a step's leaves apart from the process that loaded the method, and its deployment provides the store that serves them there: the orchestrator copies every tree the run names into it while it dispatches the run, before the runner drops the files the trees were listed from.++A run records two identities of its method: the digest of its tree, which changes with any byte of any file, and the fingerprint of its crate, which changes only with the meaning of its concepts and pipes. A method whose bundles were all sent as text, with no file beside them, belongs to no tree, so its run records the fingerprint alone.diff --git a/docs/building-methods/pipes/executing-pipelines.md b/docs/building-methods/pipes/executing-pipelines.mdindex f4f3f2328..7480e85ff 100644--- a/docs/building-methods/pipes/executing-pipelines.md+++ b/docs/building-methods/pipes/executing-pipelines.md@@ -92,7 +92,7 @@ When using `PipelexMTHDSProtocol`, you can control library behavior with these p- **`mthds_contents`**: When provided to `PipelexMTHDSProtocol.execute()`, Pipelex parses these strings and loads them into the library in addition to any resolved library directories. To run with only this content, disable directory loading explicitly (e.g. `library_dirs=[]`). This is useful for dynamic pipeline execution without file-based definitions.-- **`bundle_uris`**: Optional file paths identifying the bundles passed as `mthds_contents` (matched by position). When a URI matches a bundle already loaded from the library directories, that content is skipped instead of being loaded twice. Without `bundle_uris`, every `mthds_contents` entry is loaded unconditionally — so passing content that duplicates a directory-loaded bundle raises a duplicate-declaration error. A content whose URI names a file on this machine is loaded as read from that file, so its steps read the files beside it, such as a `PipeDocGen` step's `template_file`, and an address-based reference is looked for in a `.mthds/methods/` directory above it, exactly as when its directory loads; without `bundle_uris`, a content string has no directory, and its template files are passed as `bundle_resources`, so a step naming one by a path no such file could be keyed by, such as one through a `..` segment, is refused when the content is parsed.+- **`bundle_uris`**: Optional file paths identifying the bundles passed as `mthds_contents` (matched by position). When a URI matches a bundle already loaded from the library directories, that content is skipped instead of being loaded twice. Without `bundle_uris`, every `mthds_contents` entry is loaded unconditionally — so passing content that duplicates a directory-loaded bundle raises a duplicate-declaration error. A content whose URI names a file on this machine is loaded as read from that file, so its steps read the files beside it, such as a `PipeDocGen` step's `template_file`, and an address-based reference is looked for in a `.mthds/methods/` directory above it, exactly as when its directory loads; without `bundle_uris`, a content string has no directory, and its template files are passed as `submitted_files` to `PipelexMTHDSProtocol`, so a step naming one by a path no such file could be keyed by, such as one through a `..` segment, is refused when the content is parsed.!!! info "Python Structure Classes"If your concepts use Python `StructuredContent` classes instead of inline structures, those Python files must be in the directories specified by `library_dirs`. Pipelex auto-discovers and registers these classes during library loading. Learn more about [Python StructuredContent Classes](../concepts/python-classes.md).diff --git a/docs/building-methods/pipes/pipe-operators/PipeDocGen.md b/docs/building-methods/pipes/pipe-operators/PipeDocGen.mdindex f2e973a0b..10a364d4c 100644--- a/docs/building-methods/pipes/pipe-operators/PipeDocGen.md+++ b/docs/building-methods/pipes/pipe-operators/PipeDocGen.md@@ -128,11 +128,13 @@ A `pdf` step's `template`, or its `.html` `template_file`, is rendered with exac- **Pipelex's `format` filter shadows Jinja's own.** To format a number, write `{{ '%.2f' % invoice.total }}` rather than `{{ '%.2f' | format(invoice.total) }}`.- **The `markdown` filter** turns Markdown held in a plain text field into HTML: `{{ invoice.notes | markdown }}`. A `Markdown` input needs no filter.+An inline `template` is rendered where the step runs, its text being the bundle's own. A `template_file` is read where the document is printed: the step names the file by its method tree and its path there, and the print stage reads it, renders it with the step's data and prints it, a dry run's print included, so a value the template reads that does not exist fails the dry run as it fails a live one. On a distributed orchestrator such as Temporal, the step runs in a workflow, which reads no file, and the print runs in an activity, which reads the file from the method file store of the deployment. An HTML template file is printed with the inputs the step declares, the only data it may read, so an HTML step's print carries none of the run's other data.+### Office template filesAn `.xlsx`, `.docx` or `.pptx` template file is filled by its engine from the inputs as plain data, so it sees fields, not the sigils and filters of HTML templates. In plain data a native value is its value, and a verdict is its verdict: a `YesNo` is its boolean, a `Choice` its option key and a `Rating` its level, so the file reads `team` rather than `team.choice`, and a verdict's probability or confidence does not reach it. A `pdf` template reads the verdict whole, `team.choice` and `team.confidence` included, as a `PipeCompose` template does. Its contract is documented with the plugin. When the plugin's engine checks templates, `pipelex validate` and the dry run compare the file with the inputs' concepts: a misspelled name is reported before any run.-A bundle loaded from a directory, a dependency package's included, finds its template file beside its own file, and never among the files sent with a request. A bundle loaded from a string has no directory, so its template files come with it: the API's routes take them in the request's `resources`, each keyed by exactly the path its step names, and the Python entry points take them as `bundle_resources` (see [Template files sent with a bundle](#template-files-sent-with-a-bundle)). A string-loaded step whose file was not supplied is refused at load, saying so, whatever source label the bundle carries: only a bundle file the runtime read itself has a directory beside it, so a label naming a path, or a `source` written in the bundle's text, never makes the runtime read its own disk. An inline `template` works on every load path.+A bundle loaded from a directory, a dependency package's included, finds its template file beside its own file, and never among the files sent with a request. A bundle loaded from a string has no directory, so its template files come with it: the API's routes take them in the request's `resources`, each keyed by exactly the path its step names, and the Python entry points take them as `submitted_files` (see [Template files sent with a bundle](#template-files-sent-with-a-bundle)). A string-loaded step whose file was not supplied is refused at load, saying so, whatever source label the bundle carries: only a bundle file the runtime read itself has a directory beside it, so a label naming a path, or a `source` written in the bundle's text, never makes the runtime read its own disk. An inline `template` works on every load path.### Template files sent with a bundle@@ -145,23 +147,22 @@ When a bundle is sent as content rather than read from a directory, as it is thr}```-- **The key is the path the step names**, relative to the bundle and written with forward slashes: a step with `template_file = "templates/invoice.docx"` reads the file sent as `templates/invoice.docx`, and `./templates/invoice.docx` names the same file. Every bundle of the request is read as sitting in one directory. An absolute path, a `..` segment, a backslash and a colon are refused, as a key and as the path a step names: a step whose `template_file` could not be a key is refused when its bundle is parsed, whatever the request sends, so every file a string-loaded step can name can be sent with it.+- **The key is the path the step names**, relative to the bundle and written with forward slashes: a step with `template_file = "templates/invoice.docx"` reads the file sent as `templates/invoice.docx`, and `./templates/invoice.docx` or `templates//invoice.docx`, as a key or as the path a step names, names the same file. Every bundle of the request is read as sitting in one directory. An absolute path, a `..` segment, a backslash and a colon are refused, as a key and as the path a step names: a step whose `template_file` could not be a key is refused when its bundle is parsed, whatever the request sends, so every file a string-loaded step can name can be sent with it.- **The value is the file's bytes** in standard base64.- **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. 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.+The files sent with a bundle make one method tree, with the bundles sent as strings at its root: the run names that tree by its digest, as it names the tree of a bundle loaded from a directory, and carries none of its files. The print stage reads a template file from the tree, under the run's read scope, to print it or to check it, wherever it runs: in the process that loaded the method, the tree is the one its library holds; on a remote orchestrator such as Temporal, the deployment's method file store serves it. No template file rides in the run's payloads, so none is bounded by them.-From Python, the same files are passed as `bundle_resources`, built with `make_bundle_resources`:+From Python, the same files are passed as `submitted_files`, a mapping from the path the step names to the file's bytes:```pythonfrom pathlib import Path-from pipelex.core.bundle_resources.bundle_resource import make_bundle_resourcesfrom pipelex.pipeline.runner import PipelexMTHDSProtocol-resources = make_bundle_resources(files={"templates/invoice.docx": Path("templates/invoice.docx").read_bytes()})-result = await PipelexMTHDSProtocol(bundle_resources=resources).execute(mthds_contents=[bundle_text], inputs=inputs)+submitted_files = {"templates/invoice.docx": Path("templates/invoice.docx").read_bytes()}+result = await PipelexMTHDSProtocol(submitted_files=submitted_files).execute(mthds_contents=[bundle_text], inputs=inputs)```## Running and iterating@@ -174,7 +175,7 @@ pipelex run bundle invoice/ --pipe render_invoice_pdf --inputs invoice/inputs.jsRunning the `PipeDocGen` step alone on inputs saved from an earlier run is the loop for working on a document's layout: it spends nothing on inference. Write the inputs file in the shape `pipelex run` takes, one entry per input with its concept and content.-A dry run composes for real against mock inputs, which checks the templates and the file's name, prints nothing, and outputs a mock `Document`.+A dry run composes for real against mock inputs, which checks the templates and the file's name, and its print reads the template file, renders an HTML one and hands an office one to the engine's template checker, then prints nothing and outputs a mock `Document`.When the plugin's engine checks an office template file, validation reports what it finds in two ways. An error, such as a Word tag that names no field, fails the step's dry run, and so the validation. A warning, such as an Excel defined name or a PowerPoint shape name that matches no field, leaves the bundle valid and rides the verdict's advisory `warnings` as a `template_check_warning` item naming the step (`pipe_code`, `domain_code`), the file (`template_file`) and the place in it (`template_location`). Read it all the same: a misspelled name fills nothing, so the document keeps the template's sample value there. The warning reaches every surface that returns the verdict: `pipelex validate`, `pipelex-agent validate` and the API server's `POST /v1/validate`. A dry run that returns no verdict, such as `pipelex run --dry-run`, `pipelex fix bundle` or `pipelex build inputs`, logs it instead.diff --git a/docs/contribute/hub-layering.md b/docs/contribute/hub-layering.mdindex c00b36ac7..b22eef3b7 100644--- a/docs/contribute/hub-layering.md+++ b/docs/contribute/hub-layering.md@@ -40,6 +40,7 @@ There is deliberately **no** `pipelex.hub`. It was deleted rather than kept as a| secrets | `get_secrets_provider`, `get_secret` || system registries | `get_class_registry` || storage | `get_storage_provider` |+| method files | `get_method_file_store`, `get_template_file_stage` || telemetry | `get_telemetry_manager`, `get_otel_tracer` || models | `get_models_manager`, `get_model_deck`, `get_sdk_client_manager` || inference | `get_inference_manager`, `get_llm_worker`, `get_img_gen_worker`, `get_extract_worker` |@@ -62,7 +63,7 @@ There is deliberately **no** `pipelex.hub`. It was deleted rather than kept as a| current-library contextvar | `set_current_library`, `get_current_library`, `get_current_library_id_or_none`, `clear_current_library`, `scoped_current_library` || library dirs | `resolve_library_dirs`, `get_default_library_dirs` || pipe router | `get_pipe_router`, `set_pipe_router`, `teardown_current_pipe_router`, `scoped_pipe_router` |-| run | `get_pipe_run`, `does_pipe_run_leave_process`, `get_pipeline_manager`, `get_pipeline` |+| run | `get_pipe_run`, `get_pipeline_manager`, `get_pipeline` || pipe func | `get_pipe_func_executor`, `scoped_pipe_func_executor`, `get_pipe_func_executor_registry`, `get_pipe_func_package_offer_registry` |Setters follow their getters onto the matching container.@@ -231,6 +232,10 @@ A run may pin a per-library `ClassRegistry` rather than the process-global KajsoThis is the same shape as `HubSlot.ISOLATED_EXECUTION_PROBE`: a defaulted callable a higher layer replaces at boot, never an unset attribute. A process that only ever builds a `RuntimeHub` therefore degrades to the process-global registry instead of raising. That used to describe only the doctor path and most unit tests; since [the boot split](#where-the-boot-splits) it is a first-class entry point — `RuntimeBoot.make()` installs no `InterpreterHub`, and a test pins that scoping stays at its unscoped default on that boot.+### The print stage's template file stage crosses downward too++A `PipeDocGen` step's print stage is a kernel-layer leaf, and rendering its HTML template file needs the method: the step's data typed by the concepts of the run's crate, and the `PipeCompose` HTML stack. So the kernel layer holds only the seam, `TemplateFileStageProtocol` in `pipelex/cogt/doc_gen/template_file_stage.py`, read through `runtime_hub.get_template_file_stage`, and `Pipelex.setup` installs the interpreter's implementation, `pipelex/pipe_operators/doc_gen/template_file_stage.py`, once the interpreter is up. Unlike the slots above it has no default: a kernel-only boot prints no template file, and asking for the stage there raises, naming why. Teardown releases it. The method file store beside it, `get_method_file_store`, is a kernel-tier slot with a core default, `LOCAL_METHOD_FILES`, that a plugin may claim (`HubSlot.METHOD_FILE_STORE`).+## EnforcementThe boundary is enforced mechanically. Two things are checked, because the rule and the property it buys can fail independently.diff --git a/docs/errors/authoring-and-language.md b/docs/errors/authoring-and-language.mdindex 8a4df2cce..b22753d02 100644--- a/docs/errors/authoring-and-language.md+++ b/docs/errors/authoring-and-language.md@@ -17,10 +17,8 @@ own page. Classes are grouped by subsystem.## Core language-- [`BundleResourceError`](bundle-resource-error.md) — Bundle resource- [`BundleResourceNotNamedError`](bundle-resource-not-named-error.md) — Bundle resource not named- [`BundleResourcePathError`](bundle-resource-path-error.md) — Bundle resource path-- [`BundleResourcesTooLargeError`](bundle-resources-too-large-error.md) — Bundle resources too large- [`ConceptCodeError`](concept-code-error.md) — Concept code- [`ConceptError`](concept-error.md) — Concept error- [`ConceptFactoryError`](concept-factory-error.md) — Concept factory@@ -39,6 +37,7 @@ own page. Classes are grouped by subsystem.- [`InputStuffSpecsError`](input-stuff-specs-error.md) — Input stuff specs- [`InputStuffSpecsFactoryError`](input-stuff-specs-factory-error.md) — Input stuff specs factory- [`ListWhereSingularError`](list-where-singular-error.md) — List where singular+- [`MethodFileUnavailableError`](method-file-unavailable-error.md) — Method file unavailable- [`MultiplicityCountMismatchError`](multiplicity-count-mismatch-error.md) — Multiplicity count mismatch- [`NativeConceptDefinitionError`](native-concept-definition-error.md) — Native concept definition- [`NullInputError`](null-input-error.md) — Null input@@ -83,6 +82,7 @@ own page. Classes are grouped by subsystem.- [`PipeDocGenFactoryError`](pipe-doc-gen-factory-error.md) — Pipe doc gen factory- [`PipeDocGenRunError`](pipe-doc-gen-run-error.md) — Pipe doc gen run- [`PipeDocGenTemplateCheckError`](pipe-doc-gen-template-check-error.md) — Pipe doc gen template check+- [`PipeDocGenTemplateFileUncheckedError`](pipe-doc-gen-template-file-unchecked-error.md) — Pipe doc gen template file unchecked- [`PipeDocGenUndefinedValueError`](pipe-doc-gen-undefined-value-error.md) — Pipe doc gen undefined value- [`PipeExtractFactoryError`](pipe-extract-factory-error.md) — Pipe extract factory- [`PipeFuncExecutionError`](pipe-func-execution-error.md) — Pipe func execution@@ -120,7 +120,6 @@ own page. Classes are grouped by subsystem.- [`ConceptLibraryError`](concept-library-error.md) — Concept library- [`ConceptLoadingError`](concept-loading-error.md) — Concept loading-- [`CrateIntegrityError`](crate-integrity-error.md) — Crate integrity error- [`CrateNormalizationError`](crate-normalization-error.md) — Crate normalization error- [`DomainLibraryError`](domain-library-error.md) — Domain library- [`DomainLoadingError`](domain-loading-error.md) — Domain loadingdiff --git a/docs/errors/bundle-resource-error.md b/docs/errors/bundle-resource-error.mddeleted file mode 100644index 446aaa425..000000000--- a/docs/errors/bundle-resource-error.md+++ /dev/null@@ -1,21 +0,0 @@-----title: "Bundle resource"-description: "Reference for the `BundleResourceError` Pipelex error class."------<!-- pipelex:generated -->--# Bundle resource--Raised when a bundle resource cannot be read: stored bytes that no longer match their digest, or a read the resource cannot serve.--| Field | Value |-|---|---|-| `error_type` | `BundleResourceError` |-| `title` | Bundle resource |-| `type_uri` | `https://docs.pipelex.com/latest/errors/bundle-resource-error/` |-| `error_domain` | _(inherited from parent)_ |-| Defined in | `pipelex.core.bundle_resources.exceptions` |-| Parent class | [`PipelexError`](pipelex-error.md) |--[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.mddeleted file mode 100644index 9a72f65a8..000000000--- a/docs/errors/bundle-resources-too-large-error.md+++ /dev/null@@ -1,22 +0,0 @@-----title: "Bundle resources too large"-description: "Reference for the `BundleResourcesTooLargeError` Pipelex error class."------<!-- pipelex:generated -->--# Bundle resources too large--Raised when the files a bundle's steps read when the method loads, such as HTML templates, are too large in total.--| Field | Value |-|---|---|-| `error_type` | `BundleResourcesTooLargeError` |-| `title` | Bundle resources too large |-| `type_uri` | `https://docs.pipelex.com/latest/errors/bundle-resources-too-large-error/` |-| `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/crate-integrity-error.md b/docs/errors/crate-integrity-error.mddeleted file mode 100644index b39b0cf9d..000000000--- a/docs/errors/crate-integrity-error.md+++ /dev/null@@ -1,21 +0,0 @@-----title: "Crate integrity error"-description: "Reference for the `CrateIntegrityError` Pipelex error class."------<!-- pipelex:generated -->--# Crate integrity error--Raised when a library crate names a method tree it does not carry: the host that assembled it built it wrong.--| Field | Value |-|---|---|-| `error_type` | `CrateIntegrityError` |-| `title` | Crate integrity error |-| `type_uri` | `https://docs.pipelex.com/latest/errors/crate-integrity-error/` |-| `error_domain` | _(inherited from parent)_ |-| Defined in | `pipelex.libraries.exceptions` |-| Parent class | [`LibraryError`](library-error.md) |--[Back to Error Reference](index.md)diff --git a/docs/errors/method-file-unavailable-error.md b/docs/errors/method-file-unavailable-error.mdnew file mode 100644index 000000000..489b29692--- /dev/null+++ b/docs/errors/method-file-unavailable-error.md@@ -0,0 +1,21 @@+---+title: "Method file unavailable"+description: "Reference for the `MethodFileUnavailableError` Pipelex error class."+---++<!-- pipelex:generated -->++# Method file unavailable++A method file, or the listing of the tree that holds it, cannot be read through the method file store.++| Field | Value |+|---|---|+| `error_type` | `MethodFileUnavailableError` |+| `title` | Method file unavailable |+| `type_uri` | `https://docs.pipelex.com/latest/errors/method-file-unavailable-error/` |+| `error_domain` | _(inherited from parent)_ |+| Defined in | `pipelex.core.method_trees.exceptions` |+| Parent class | [`PipelexError`](pipelex-error.md) |++[Back to Error Reference](index.md)diff --git a/docs/errors/pipe-doc-gen-template-file-unchecked-error.md b/docs/errors/pipe-doc-gen-template-file-unchecked-error.mdnew file mode 100644index 000000000..66dad0568--- /dev/null+++ b/docs/errors/pipe-doc-gen-template-file-unchecked-error.md@@ -0,0 +1,22 @@+---+title: "Pipe doc gen template file unchecked"+description: "Reference for the `PipeDocGenTemplateFileUncheckedError` Pipelex error class."+---++<!-- pipelex:generated -->++# Pipe doc gen template file unchecked++Raised when a ``PipeDocGen`` step built from a library crate is validated where its HTML template file is not at hand.++| Field | Value |+|---|---|+| `error_type` | `PipeDocGenTemplateFileUncheckedError` |+| `title` | Pipe doc gen template file unchecked |+| `type_uri` | `https://docs.pipelex.com/latest/errors/pipe-doc-gen-template-file-unchecked-error/` |+| `error_domain` | `runtime` |+| Defined in | `pipelex.pipe_operators.doc_gen.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.mdindex bc3e6a96b..fb18c4c73 100644--- a/docs/under-the-hood/distributed-content-generation.md+++ b/docs/under-the-hood/distributed-content-generation.md@@ -172,7 +172,9 @@ 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>`, 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.+The traffic also runs the other way, and no file of the method rides it. A run's `LibraryCrate` names the method tree each pipe's bundle belongs to by the tree's digest, and the bundle by its tree path (`TreeBundleRef`), and a `PipeDocGen` step names its template file the same way (`MethodFileRef`): the crate carries no file's bytes, no listing and no path of the host that assembled it. The bundles loaded from content strings sit at the root of the tree of the files submitted with them, a tree the library assembles in memory and names by digest like any other. A leaf that uses a method file reads it where IO is allowed, through one seam, the method file store (`MethodFileStoreProtocol` in `pipelex/core/method_trees/method_file_store.py`, read through `pipelex/core/method_trees/method_files.py`): it reads the tree's listing by the tree's digest, checks the listing against the digest, then reads each file it needs by its SHA-256, checks the bytes against the listing, and passes the run's read scope with every read. The runtime hub holds the store (`get_method_file_store`). Unclaimed, it is the local one, `LOCAL_METHOD_FILES`, which serves the trees this process's libraries hold while they hold them, from the disk they were listed from or from the bytes submitted with a request; a host whose activities run apart from the process that loaded the method claims `HubSlot.METHOD_FILE_STORE` for its own, such as a blob store the runner filled before it dispatched the run.++Two leaves read through it. The print stage of a `PipeDocGen` step reads its template file: the compose stage, which may run in a workflow, names the file in the step's `DocumentComposition`, with what an HTML template renders with (`TemplateRenderContext`): the stuffs the step's inputs name, the only ones its template may read, dumped for transport, the concepts and domains of the run's crate with none of its pipes, the crate's fingerprint, and the run's runtime parameters. The composition crosses into the print activity's payload, so it carries neither the run's pipes nor data the step does not read. The print renders it with the interpreter's template file stage (`pipelex/pipe_operators/doc_gen/template_file_stage.py`, installed on the runtime hub when the interpreter boots), which types the data again in the run's own library when this process holds it, and otherwise in a library loaded from the concepts alone, which the process keeps, by the concepts' fingerprint, for the prints that follow (`RenderLibraryCache`), then prints. At a dry print, the HTML template is rendered too, and an office template is handed to its engine's template checker, whose findings the stage reports. And an out-of-process `PipeFunc` call names its step's tree by digest (`PipeFuncExecutionRequest.tree_digest`), and whoever runs it reads the files of the tree but its bundles (`read_pipe_func_call_files`) and writes them where the function imports them. A run records both identities of the method it ran in its `RunMetadata`: the digest of the tree its pipe belongs to, which changes with any byte of the method, and the crate's fingerprint, which changes only with the meaning of its concepts and pipes.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.mdindex 6fe1ef63e..16e46ca8e 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. 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 |+| `retryable` | `bool \| None` | Whether a retry could succeed. Declared per class, `retryable = False` on a deterministic refusal of what the caller sent (`BundleResourceNotNamedError`, `BundleResourcePathError`), 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/docs/under-the-hood/inference-backend-plugins.md b/docs/under-the-hood/inference-backend-plugins.mdindex 22d80b5d9..cff76ce0c 100644--- a/docs/under-the-hood/inference-backend-plugins.md+++ b/docs/under-the-hood/inference-backend-plugins.md@@ -200,7 +200,7 @@ Declare an entry point in the `pipelex.plugins.kernel` group; discovery finds itacme = "my_pkg.acme_plugin:AcmePlugin"```-**The group declares your layer, and the choice is not cosmetic.** An inference backend is kernel-layer — it constructs a worker, never a `Pipe` — so it belongs in `pipelex.plugins.kernel`, and a kernel-only boot reads that group and finds it. Publish the same plugin under `pipelex.plugins.interpreter` and a kernel-only boot never even *imports* your module, so your backend is simply absent. The reverse mistake fails loudly instead: a `pipelex.plugins.kernel` plugin whose `register` reaches an interpreter-layer capability — `add_orchestrator`, `add_bundle_validator`, `add_pipe_func_executor`, `add_pipe_func_package_offer`, or the three hub slots that hand back a `Pipe`-aware object (`claim_pipe_router`, `claim_pipe_run`, `claim_pipe_func_executor`) — raises `PluginLayerViolationError` naming the capability and the group to move to. The other three slots are kernel-tier and a kernel-group plugin may claim them freely: `claim_content_generator`, `claim_task_manager`, `claim_isolated_execution_probe`. The restriction is one-directional — an interpreter-group plugin may contribute kernel-tier capabilities too.+**The group declares your layer, and the choice is not cosmetic.** An inference backend is kernel-layer — it constructs a worker, never a `Pipe` — so it belongs in `pipelex.plugins.kernel`, and a kernel-only boot reads that group and finds it. Publish the same plugin under `pipelex.plugins.interpreter` and a kernel-only boot never even *imports* your module, so your backend is simply absent. The reverse mistake fails loudly instead: a `pipelex.plugins.kernel` plugin whose `register` reaches an interpreter-layer capability — `add_orchestrator`, `add_bundle_validator`, `add_pipe_func_executor`, `add_pipe_func_package_offer`, or the three hub slots that hand back a `Pipe`-aware object (`claim_pipe_router`, `claim_pipe_run`, `claim_pipe_func_executor`) — raises `PluginLayerViolationError` naming the capability and the group to move to. The other slots are kernel-tier and a kernel-group plugin may claim them freely: `claim_content_generator`, `claim_task_manager`, `claim_isolated_execution_probe`, `claim_method_file_store`. The restriction is one-directional — an interpreter-group plugin may contribute kernel-tier capabilities too.The single pre-split `pipelex.plugins` group is retired. It is not ignored: a plugin still published there fails startup with `RetiredPluginEntryPointGroupError`, because the alternative — being silently undiscovered — is the expensive failure to diagnose.diff --git a/docs/under-the-hood/orchestrator-plugins.md b/docs/under-the-hood/orchestrator-plugins.mdindex 30d91cfcb..29b898c27 100644--- a/docs/under-the-hood/orchestrator-plugins.md+++ b/docs/under-the-hood/orchestrator-plugins.md@@ -153,6 +153,12 @@ Each `claim_*` takes a **thunk** (a zero-arg factory), never a constructed instaThe first four slots swap in the runtime's implementations of core execution services. The fifth, `claim_isolated_execution_probe`, is different in kind: its thunk resolves not a service but an **ambient predicate** (`Callable[[], bool]`) reporting whether the current call runs inside an isolated sub-execution — a Temporal activity — whose side-effecting emissions must not be written into the parent run's replay-deterministic buffer. `ReportingManager` consults it (`hub.is_in_isolated_execution()`) to route an activity-side usage emission to the per-process log instead of the workflow's registered buffer. A scoped event log (`runtime_hub.scoped_event_log`) set by the activity's own code comes first: the emission goes into it and nowhere else, which is how an activity captures its leaf's usage to return it with its result (see [the scoped override](execution-graph-tracing.md#event-log-transport-and-the-scoped-override)). The override is a ContextVar, so a workflow's scope never reaches an activity, co-located or not. It exists as a hub slot for the same reason the others do: only a boot-orchestrator plugin whose runtime has a replay/activity split knows how to answer, and core names no such runtime. Unclaimed (any in-process boot), the hub's core default answers "never isolated" — the in-process orchestrator has no such split.+### The method file store slot++A run names the files of its method by the digest of their method tree, and a leaf reads one, such as a `PipeDocGen` step's template file at its print or the files of an out-of-process `PipeFunc` call, through the method file store (`MethodFileStoreProtocol` in `pipelex/core/method_trees/method_file_store.py`): `read_tree_listing(tree_digest=…, read_scope=…)` returns the tree's listing, and `read_blob(sha256=…, read_scope=…)` a file's bytes, each `None` when the store does not hold it for that read scope. The caller checks the listing against the digest and each blob against the listing (`pipelex/core/method_trees/method_files.py`), so a store only serves bytes. A plugin whose activities run apart from the process that loaded the method claims the slot with `claim_method_file_store`, a thunk like the others, and its store serves the trees that process listed, from wherever the host put them. The slot is kernel-tier, a store constructing no `Pipe`. Unclaimed, the hub's core default is the local store, `LOCAL_METHOD_FILES`, which serves the trees this process's libraries hold while they hold them.++The host puts them there at one moment: an orchestrator that runs a job out of process copies every tree the job's crate names into the store its workers read **before its `execute` or `start` returns**. The runner may drop the library holding a tree and the files it was listed from as soon as the orchestrator returns: `/start` deletes the temporary directory it wrote a request's files into when `start` returns. `read_stored_trees(tree_digests=pipe_job.library_crate.tree_digests(), read_scope=…)` in `pipelex/core/method_trees/method_files.py` reads them for that copy, each one as a store keeps it, its listing under the tree's digest and each distinct file under its SHA-256, checked against the digest. The contract is on `OrchestratorProtocol` too. An orchestrator running the job in the runner's process copies nothing.+Because the gate is a name-match, `boot_orchestrator` must name a plugin that actually registered. After discovery, `Pipelex.setup` rejects a `boot_orchestrator` that no registered plugin carries — a typo or a missing plugin (e.g. `--orchestrator temporal` without the Temporal plugin installed) raises `UnknownBootOrchestratorError` instead of silently running in-process: nothing would claim the hub slots, so the process would otherwise fall through to the core defaults and execute on the wrong runtime. The check matches against **plugin names** (the same namespace the gate uses), not the `orchestration_mode` registry — a plugin's name and the token(s) it serves are separate namespaces that *may* differ, even where a shipped plugin keeps them identical (our Temporal plugin is named `temporal` and serves `temporal`). The error names no specific plugin, keeping core decoupled.### Injection precedencediff --git a/docs/under-the-hood/pipe-func-requirements.md b/docs/under-the-hood/pipe-func-requirements.mdindex 4608331d8..991036035 100644--- a/docs/under-the-hood/pipe-func-requirements.md+++ b/docs/under-the-hood/pipe-func-requirements.md@@ -28,7 +28,7 @@ A requirement whose marker is false in the environment is not needed there and i| `direct` | `InterpreterPackageEnvironment` | The distributions installed in the interpreter Pipelex runs in, through `importlib.metadata`, and this interpreter's own marker environment. Extras are followed through each distribution's `Requires-Dist`. || any other mode | `OfferedPackageEnvironment` | The package set the plugin providing the mode states for its sandbox, and nothing else. A marker variable the offer does not state cannot be judged, and a requirement with extras cannot be followed, so both are refused rather than judged against this process's own values. |-In the `direct` mode, a method's Python is imported into the process that loads it, when its steps first bind their functions, and that is the process the check judges. A distributed orchestrator, such as our Temporal plugin, never carries a `direct`-mode method's Python to its worker: the library crate carries the files of a `PipeFunc` call (`pipe_func_files`) only in a sandbox mode, where they are captured rather than imported. A worker in the `direct` mode therefore runs only the functions its own deployment installed, whose packages are that deployment's to install, and the API server refuses a caller's Python outright unless it is sandbox-hosted (`403 CustomCodeRequiresSandbox`). So no worker needs to repeat the check.+In the `direct` mode, a method's Python is imported into the process that loads it, when its steps first bind their functions, and that is the process the check judges. A distributed orchestrator, such as our Temporal plugin, never carries a method's Python to its worker: the library crate names the step's method tree by its digest, and in a sandbox mode the call's files are read through the method file store by whoever runs it, for the sandbox to import them, never this process. A worker in the `direct` mode therefore runs only the functions its own deployment installed, whose packages are that deployment's to install, and the API server refuses a caller's Python outright unless it is sandbox-hosted (`403 CustomCodeRequiresSandbox`). So no worker needs to repeat the check.## How a refusal names the methoddiff --git a/docs/under-the-hood/runtime-bridge-and-transport.md b/docs/under-the-hood/runtime-bridge-and-transport.mdindex eaa078943..aa73b60b5 100644--- a/docs/under-the-hood/runtime-bridge-and-transport.md+++ b/docs/under-the-hood/runtime-bridge-and-transport.md@@ -79,6 +79,8 @@ The submitter builds a `LibraryCrate` from its loaded library (`pipelex/librarieA load ends by validating the whole library (`Library.validate_library`), which checks every pipe against the concepts and pipes it depends on. That check is pure — it raises or returns, and leaves nothing behind that a run later reads — and the crate a worker receives was built from a library the submitter already loaded and validated. So a worker running the same pipelex version as its submitter can call `load_from_crate(library_id=…, crate=…, is_crate_prevalidated=True)`, which skips that final validation and nothing else: fingerprint idempotency, domain and concept loading with the registration of the dynamic classes, the resolution of their references to one another, the concept-cycle check, pipe construction with each pipe's static validation, and source tracking all still run. The precondition belongs to the host: pass it only where submitter and worker ship on the same pipelex, as a deployment that builds them from one lockfile does. A crate from anywhere else keeps the default, validating load.+A crate carries no file of the method either. It names the method tree each pipe's bundle belongs to by the tree's digest and the bundle by its tree path (`LibraryCrate.tree_bundles`), so a pipe built from a crate resolves a file its bundle names lexically, joined to the bundle's tree path, and reads nothing: the pre-validated crate's load reads no file, and a workflow may load it. A load that validates the crate builds a pipe as a member of its tree when a library of this process holds the tree under the digest the crate names, so a `PipeDocGen` step's HTML template file is read for its checks and the crate reaches the verdict its bundles reached; where no library holds the tree, such a step is refused (`PipeDocGenTemplateFileUncheckedError`) rather than passed with its template unchecked. The process running a transported `PipeFunc` call writes the call's tree out, with none of its bundles, and builds the called step, and no other, in it (`load_from_crate(written_pipe_trees=…)`, keyed by the step's pipe ref): every other step of the crate, a sibling in the same tree included, is built as the crate names it. The leaf that uses a file reads it through the method file store, by the tree's digest and under the run's read scope (see [Distributed Content Generation](distributed-content-generation.md)). The crate's fingerprint keeps its role as the semantic identity of the method's concepts and pipes and ignores the trees: the digest changes with any byte, the fingerprint only with meaning, and a run's `RunMetadata` records both.+A crate carries no method package the library depends on, so a structure field typed by a dependency's concept cannot be resolved on the worker. A crate load therefore never refuses a structure class it could not complete, whichever the flag: the refusal of a field naming a concept that cannot be found belongs to the load from bundles, which resolves the dependencies first, and the submitter's library went through it. Such a class fails only if a run on the worker uses it, as would the dependency's own pipes, which the crate does not carry either.---diff --git a/docs/under-the-hood/writing-an-inference-plugin.md b/docs/under-the-hood/writing-an-inference-plugin.mdindex 36ddffe40..9745f9691 100644--- a/docs/under-the-hood/writing-an-inference-plugin.md+++ b/docs/under-the-hood/writing-an-inference-plugin.md@@ -110,7 +110,7 @@ class HelloInferencePlugin:name = "hello_inference"# The plugin API version this plugin was written against, as a literal: never import the# runtime's PLUGIN_API_VERSION here, or the check that catches a breaking runtime upgrade always passes.- targets_api = 6+ targets_api = 7def register(self, registrar: PluginRegistrar) -> None:registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="hello", make_worker=_make_hello_llm_worker)diff --git a/pipelex/cogt/content_generation/doc_gen_generate.py b/pipelex/cogt/content_generation/doc_gen_generate.pyindex 82d6be609..944d8b798 100644--- a/pipelex/cogt/content_generation/doc_gen_generate.py+++ b/pipelex/cogt/content_generation/doc_gen_generate.py@@ -7,6 +7,13 @@ the worker of the ``doc_gen`` model the assignment names, resolved when the stepthread, since engines are synchronous; a file its document names, such as an image, it reads back through the``RenderResources`` it is handed, under the run's read scope.+A step printing from a template file names it in its composition by its tree's digest and its tree path, and the+leaf reads it through the method file store, under the run's read scope: this is the activity, where IO is allowed,+and the compose stage, which may run in a workflow, reads no file. An HTML template file is then rendered with the+step's data by the interpreter's template file stage (``pipelex.cogt.doc_gen.template_file_stage``), a dry print+included, so a value the template reads that does not exist fails the dry run as it fails a live one; an office+template file is handed to its engine, and at a dry print to its engine's template checker.+Engines run on a thread pool of their own rather than the event loop's default executor, because an engine'sthread waits while the loop reads a file for it, and that read may itself need a default-executor thread (alocal file read, a DNS lookup, a cloud storage call). Were the engines on the default executor, as many@@ -18,7 +25,7 @@ import asyncioimport contextvarsimport threadingfrom concurrent.futures import ThreadPoolExecutor-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, NamedTuplefrom typing_extensions import override@@ -29,11 +36,14 @@ from pipelex.cogt.content_generation.generated_content_factory import GeneratedCfrom pipelex.cogt.content_generation.read_authorization import authorize_assignment_readsfrom pipelex.cogt.doc_gen.doc_gen_engine import get_doc_gen_inference_model, require_doc_gen_engine_installedfrom pipelex.cogt.doc_gen.doc_gen_worker_factory import DocGenWorkerFactory+from pipelex.cogt.doc_gen.document_composition import DocumentCompositionfrom pipelex.cogt.doc_gen.exceptions import DocGenRenderError-from pipelex.cogt.doc_gen.render_job import LoadedResource, RenderedDocument, RenderResources+from pipelex.cogt.doc_gen.render_job import LoadedResource, RenderedDocument, RenderJob, RenderResources+from pipelex.cogt.doc_gen.template_check import TemplateCheckRequestfrom pipelex.cogt.inference.inference_call_summary import InferenceCallSummary, InferenceOperation+from pipelex.core.method_trees.method_files import read_method_filefrom pipelex.core.stuffs.document_content import DocumentContent-from pipelex.runtime_hub import get_report_delegate+from pipelex.runtime_hub import get_report_delegate, get_template_file_stagefrom pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstractfrom pipelex.tools.uri.uri_bytes import load_bytes_and_mime_type_from_any_urifrom pipelex.tools.uri.uri_read_scope import authorize_uri_read@@ -89,10 +99,12 @@ async def render_document_and_store("""Print the composed document with its engine, store the file, and return the `DocumentContent` pointing at it.The read scope is authorized first in either mode, so a dry run, which prints and stores nothing, refuses what- a live one would. A live print ends with the event every inference call ends with, as `_print_document` says.+ a live one would. A dry run reads and checks the template file the step prints from, if any, as `_check_template_file`+ says. A live print ends with the event every inference call ends with, as `_print_document` says.Raises:UriReadRefusedError: an image the document names is outside the run's read scope.+ MethodFileUnavailableError: the template file cannot be read through the method file store for this run.ModelNotFoundError: the assignment's engine is not a model served here.DocGenEngineMissingError: the engine is the built-in one or one of the plugin's and is no longer declared here, orno installed plugin registers it.@@ -100,6 +112,7 @@ async def render_document_and_store("""if render_assignment.cogt_run_params.run_mode.is_dry:authorize_assignment_reads(job_metadata=render_assignment.job_metadata, uri_references=render_assignment.referenced_uris())+ await _check_template_file(render_assignment=render_assignment)return dry_render_document(render_assignment)rendered = await _print_document(render_assignment=render_assignment, storage_provider=generated_content_factory.storage_provider)composition = render_assignment.composition@@ -111,6 +124,76 @@ async def render_document_and_store()+class TemplateFileForPrint(NamedTuple):+ """What the print hands its engine from the step's template file: an HTML one rendered, or an office one's bytes."""++ html: str | None+ template: bytes | None+++async def read_template_file(*, render_assignment: RenderDocumentAssignment) -> TemplateFileForPrint:+ """Read the step's template file through the method file store, and render it when it is an HTML template.++ Raises:+ MethodFileUnavailableError: the file cannot be read through the method file store for this run.+ DocGenRenderError: an HTML template file is not UTF-8 text.+ """+ composition = render_assignment.composition+ template_file = composition.template_file+ if template_file is None:+ return TemplateFileForPrint(html=None, template=None)+ data = await read_method_file(file_ref=template_file.file, read_scope=render_assignment.job_metadata.run_metadata.read_scope)+ if template_file.render_context is None:+ return TemplateFileForPrint(html=None, template=data)+ try:+ template_source = data.decode("utf-8")+ except UnicodeDecodeError as exc:+ msg = f"The template file '{template_file.name}' of '{composition.filename}' is not UTF-8 text."+ raise DocGenRenderError(msg) from exc+ html = await get_template_file_stage().render_html_template_file(template_file=template_file, template_source=template_source)+ return TemplateFileForPrint(html=html, template=None)+++async def _check_template_file(*, render_assignment: RenderDocumentAssignment) -> None:+ """At a dry print, read the step's template file and check it against the step's mock inputs.++ An HTML template file is rendered with them, so a value it reads that does not exist fails the step. An office one+ is handed to its engine's template checker, when the engine has one, and the interpreter's template file stage+ reports what it found: an error fails the step, and a warning joins the validation verdict's warnings, or the log.++ Raises:+ MethodFileUnavailableError: the file cannot be read through the method file store for this run.+ PipeDocGenTemplateCheckError: the checker reported errors (raised by the template file stage).+ """+ composition = render_assignment.composition+ template_file = composition.template_file+ if template_file is None:+ return+ read_template = await read_template_file(render_assignment=render_assignment)+ if read_template.template is None:+ return+ inference_model = get_doc_gen_inference_model(+ model_handle=render_assignment.doc_gen_setting.model,+ doc_gen_format=composition.format,+ source=composition.source,+ pipe_code=render_assignment.job_metadata.pipe_code,+ )+ worker = DocGenWorkerFactory.make_doc_gen_worker(inference_model=inference_model, reporting_delegate=get_report_delegate())+ request = TemplateCheckRequest(+ format=composition.format,+ template=read_template.template,+ template_name=template_file.name,+ inputs=template_file.input_shapes,+ data=composition.data,+ )+ findings = await asyncio.to_thread(worker.check_template, request=request)+ get_template_file_stage().report_template_findings(template_file=template_file, findings=findings)+++def _render_job_of(*, composition: DocumentComposition, read_template: TemplateFileForPrint) -> RenderJob:+ return composition.make_render_job(html=read_template.html, template=read_template.template)++async def _print_document(*, render_assignment: RenderDocumentAssignment, storage_provider: StorageProviderAbstract) -> RenderedDocument:"""Print the composed document with its engine, ending the print with the event every inference call ends with.@@ -123,6 +206,7 @@ async def _print_document(*, render_assignment: RenderDocumentAssignment, storagRaises:UriReadRefusedError: an image the document names is outside the run's read scope.+ MethodFileUnavailableError: the template file cannot be read through the method file store for this run.ModelNotFoundError: the assignment's engine is not a model served here.DocGenEngineMissingError: the engine is the built-in one or one of the plugin's and is no longer declared here, orno installed plugin registers it.@@ -155,7 +239,7 @@ async def _print_document(*, render_assignment: RenderDocumentAssignment, storag)engine_name = inference_model.nameworker = DocGenWorkerFactory.make_doc_gen_worker(inference_model=inference_model, reporting_delegate=get_report_delegate())- render_job = await composition.make_render_job(storage_provider=storage_provider)+ render_job = _render_job_of(composition=composition, read_template=await read_template_file(render_assignment=render_assignment))resources = RunRenderResources(storage_provider=storage_provider,read_scope=render_assignment.job_metadata.run_metadata.read_scope,diff --git a/pipelex/cogt/doc_gen/document_composition.py b/pipelex/cogt/doc_gen/document_composition.pyindex 5e7be6cb7..112458b07 100644--- a/pipelex/cogt/doc_gen/document_composition.py+++ b/pipelex/cogt/doc_gen/document_composition.py@@ -1,25 +1,66 @@-from pathlib import Pathfrom typing import Any, Selffrom pydantic import BaseModel, ConfigDict, Field, model_validatorfrom pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSource+from pipelex.cogt.doc_gen.input_shape import InputShapefrom pipelex.cogt.doc_gen.layout_tree import LayoutDocumentfrom pipelex.cogt.doc_gen.render_job import RenderJob-from pipelex.core.bundle_resources.bundle_resource import BundleResource-from pipelex.tools.storage.storage_provider_abstract import StorageProviderAbstract+from pipelex.core.method_trees.tree_bundle import MethodFileReffrom pipelex.tools.uri.uri_read_scope import UriReference+class TemplateRenderContext(BaseModel):+ """What the print stage renders a step's HTML template file with: the step's data, and the concepts that type it.++ The data is the stuffs the step's inputs name, the only ones its template may read, as they travel between processes.+ The concepts are those of the run's library crate, with its domains and none of its pipes, which travel beside the+ data as plain JSON, so the print stage can type the data again wherever it runs and render the template with the+ whole stack of a `PipeCompose` HTML template, its filters included. The print stage renders in the run's own library+ when its process holds it, which `crate_fingerprint` names, such as in a local run, so the data keeps the classes the+ run built it with; anywhere else it types the data with the concepts alone, in a library it keeps for later prints.+ The composition crosses into the print activity's payload, so it carries neither the run's pipes nor the data the+ step does not read.+ """++ model_config = ConfigDict(frozen=True, extra="forbid")++ crate_fingerprint: str = Field(description="The fingerprint of the run's library crate, by which a process holding it renders in it")+ concepts_crate: dict[str, Any] = Field(+ description="The concepts and domains of the run's library crate, with none of its pipes, as JSON, which type the step's data"+ )+ working_memory_raw: dict[str, Any] = Field(description="The stuffs the step's inputs name, as a working memory dumped for transport")+ runtime_params: dict[str, Any] = Field(default_factory=dict, description="The run's runtime parameters, which a template may read")+++class ComposedTemplateFile(BaseModel):+ """A template file a step names, as its print stage reads it: a file of the step's method tree, and what to read it with.++ The compose stage runs where the step runs, in a workflow on a hosted plane, which reads no file, so it names the+ template file by its tree's digest and its tree path, and the print stage, an activity, reads it through the method+ file store. An HTML template file carries the context it renders with; an office template file carries the shapes+ of the step's inputs, which the engine's template checker reads at a dry print.+ """++ model_config = ConfigDict(frozen=True, extra="forbid")++ file: MethodFileRef = Field(description="The template file, as a file of the step's method tree")+ name: str = Field(description="The template file as the method names it, for messages")+ pipe_ref: str = Field(description="The step naming the template file, as 'domain.pipe_code', for the findings of its check")+ render_context: TemplateRenderContext | None = Field(default=None, description="What an HTML template file is rendered with")+ input_shapes: dict[str, InputShape] = Field(+ default_factory=dict, description="The step's declared inputs by name, as the shape of their plain data, for an office template's check"+ )++class DocumentComposition(BaseModel):"""What a `PipeDocGen` step's compose stage produced, for its print stage to hand an engine.- The compose stage is pure, so it can run where the pipe runs, inside a workflow; this is what crosses to- the print stage, which reads the template file and prints. It differs from the engine's `RenderJob` by- naming the template file rather than carrying its bytes: reading a file is the print stage's IO. A template- file beside a bundle loaded from disk is named by its path; one submitted with a bundle loaded from content- strings is its bundle resource, inline in a run that stays in its process and a reference to the run's storage- in one handed to a remote orchestrator, so the bytes never ride in the composition across a workflow boundary.+ The compose stage is pure, so it can run where the pipe runs, inside a workflow; this is what crosses to the print+ stage, which reads the template file, renders it when it is an HTML template, and prints. It differs from the+ engine's `RenderJob` by naming the template file rather than carrying its bytes: reading a method file is the print+ stage's IO, through the method file store, so the bytes never ride in the composition across a workflow boundary.+ An inline HTML template, whose text is the bundle's own, is rendered by the compose stage and travels as `html`."""model_config = ConfigDict(extra="forbid")@@ -30,21 +71,27 @@ class DocumentComposition(BaseModel):title: strlayout: LayoutDocument | None = Nonehtml: str | None = None- template_path: str | None = Field(default=None, description="The template file's resolved path, for the print stage to read")- template_resource: BundleResource | None = Field(- default=None, description="The template file submitted with the bundle, for the print stage to read"- )- template_name: str | None = Field(default=None, description="The template file as the method names it")+ template_file: ComposedTemplateFile | None = Field(default=None, description="The template file the print stage reads, renders and prints")data: dict[str, Any] = Field(default_factory=dict)+ @property+ def template_name(self) -> str | None:+ """The template file as the method names it, when the step prints from one."""+ return self.template_file.name if self.template_file is not None else None++ @property+ def renders_html_template_file(self) -> bool:+ """Whether the print stage renders an HTML template file before it prints."""+ return self.template_file is not None and self.template_file.render_context is not None+def _carries_payload_of(self, *, source: DocGenSource) -> bool:match source:case DocGenSource.LAYOUT:return self.layout is not Nonecase DocGenSource.HTML:- return self.html is not None+ return self.html is not None or self.renders_html_template_filecase DocGenSource.TEMPLATE_FILE:- return self.template_path is not None or self.template_resource is not None+ return self.template_file is not None and self.template_file.render_context is None@model_validator(mode="after")def validate_payload(self) -> Self:@@ -57,46 +104,39 @@ class DocumentComposition(BaseModel):if extra_payloads:msg = f"A document composed {self.source.desc} carries only its own payload, not the {', '.join(extra_payloads)} one."raise ValueError(msg)- if self.template_path is not None and self.template_resource is not None:- msg = "A template file is read from disk or submitted with its bundle, not both."+ if self.html is not None and self.template_file is not None:+ msg = "A document composed from HTML carries its rendered HTML or the template file the print stage renders, not both."raise ValueError(msg)return selfdef referenced_uris(self) -> list[UriReference]:"""The files the print stage will read for the document, which it authorizes against the run's read scope first.- The images of the layout tree, and a template file submitted with the bundle and stored with the run.- Composed HTML may name files too, but only an engine laying it out finds them, and it reads each through- `RenderResources`, which applies the same check.+ The images of the layout tree. A template file is a method file, read through the method file store under the+ run's read scope, and composed HTML may name files too, but only an engine laying it out finds them, and it reads+ each through `RenderResources`, which applies the same check."""- references: list[UriReference] = []- if self.template_resource is not None and self.template_resource.uri is not None:- references.append(UriReference(uri=self.template_resource.uri, position=f"the template file '{self.template_name}'"))- if self.layout is not None:- references.extend(- UriReference(uri=image_url, position=f"image {index} of the document '{self.filename}'")- for index, image_url in enumerate(self.layout.image_urls(), start=1)- )- return references-- async def make_render_job(self, *, storage_provider: StorageProviderAbstract) -> RenderJob:- """The engine's job: this composition with the template file's bytes read in, when there is one.-- A stored template file is read through the run's storage provider; the caller authorizes the read against the- run's read scope first, with `referenced_uris`.+ if self.layout is None:+ return []+ return [+ UriReference(uri=image_url, position=f"image {index} of the document '{self.filename}'")+ for index, image_url in enumerate(self.layout.image_urls(), start=1)+ ]++ def make_render_job(self, *, html: str | None = None, template: bytes | None = None) -> RenderJob:+ """The engine's job: this composition with what the print stage read and rendered.++ Args:+ html: The HTML template file, rendered with the step's data, when the step prints from one.+ template: The office template file's bytes, when the step prints from one."""- template: bytes | None = None- if self.template_path is not None:- template = Path(self.template_path).read_bytes()- elif self.template_resource is not None:- template = await self.template_resource.read_bytes(storage_provider=storage_provider)return RenderJob(format=self.format,source=self.source,filename=self.filename,title=self.title,layout=self.layout,- html=self.html,+ html=html if html is not None else self.html,template=template,template_name=self.template_name,data=self.data,diff --git a/pipelex/cogt/doc_gen/template_file_stage.py b/pipelex/cogt/doc_gen/template_file_stage.pynew file mode 100644index 000000000..9c64f5633--- /dev/null+++ b/pipelex/cogt/doc_gen/template_file_stage.py@@ -0,0 +1,39 @@+"""The interpreter's part in printing from a template file: what only a loaded method can do with the file.++The print stage of a `PipeDocGen` step is a kernel-layer leaf (`pipelex.cogt.content_generation.doc_gen_generate`):+it reads the step's template file through the method file store and hands the engine its job. Two things it does with+the file need the method itself, its concepts and its steps' error classes, which live in the interpreter layer:+rendering an HTML template file with the step's data, typed by the run's library, under the whole stack of a+`PipeCompose` HTML template; and reporting what the engine's template checker found in an office template file at a dry+print, an error failing the step and a warning joining the validation verdict. The interpreter implements this protocol+and installs it on the runtime hub when it boots (`Pipelex.setup`); a process booted with the kernel layer alone prints+no template file.+"""++from typing import Protocol++from pipelex.cogt.doc_gen.document_composition import ComposedTemplateFile+from pipelex.cogt.doc_gen.template_check import TemplateFinding+++class TemplateFileStageProtocol(Protocol):+ """Renders an HTML template file with its step's data, and reports the findings of an office template's check."""++ async def render_html_template_file(self, *, template_file: ComposedTemplateFile, template_source: str) -> str:+ """The HTML template file's text rendered with the step's data, as the compose stage of a `PipeCompose` renders one.++ Every value the template reads must exist, as in every template of a document: a missing one fails the step.++ Args:+ template_file: The template file as the compose stage named it, with the context it renders with.+ template_source: The template file's text, read through the method file store.+ """+ ...++ def report_template_findings(self, *, template_file: ComposedTemplateFile, findings: list[TemplateFinding]) -> None:+ """Report what the engine's template checker found in an office template file, at a dry print.++ An error finding fails the step; a warning joins the validation verdict's warnings, or the log when no+ validation collects them.+ """+ ...diff --git a/pipelex/core/bundle_resources/bundle_resource.py b/pipelex/core/bundle_resources/bundle_resource.pyindex 0955b057e..186eab9a3 100644--- a/pipelex/core/bundle_resources/bundle_resource.py+++ b/pipelex/core/bundle_resources/bundle_resource.py@@ -1,58 +1,16 @@-"""A bundle's resources: the files beside its `.mthds` text that its steps read, such as a `PipeDocGen` template file.--A bundle loaded from a directory finds them beside its file on disk. A bundle submitted as content strings, which is-how the runner's routes receive one, has no directory, so the files come with it: each is keyed by the-bundle-relative path a step names, read as if every bundle of the submission sat in one directory. The library holds-them for its pipes to read, and its crate carries them wherever the library is loaded again.--A resource carries its bytes inline, base64-encoded so that it serializes to JSON like the rest of a crate, or by-reference to the run's storage. A file a step reads when the method loads, such as an HTML template, which is checked-against the step's inputs, always travels inline, like the bundle's own text, so the files read at load are bounded in-total (`MAX_LOAD_STAGE_RESOURCES_BYTES`). A file a step reads only when it runs, such as an office template, which only-its engine opens, moves to the run's storage before a run is handed to an orchestrator outside this process, so a run-that crosses to another process carries a reference rather than the bytes.+"""The files submitted with bundles loaded from content strings: the path each is keyed by, and the rule that path follows.++A bundle loaded from a directory finds the files its steps name in its method tree. A bundle submitted as content+strings, which is how the runner's routes receive one, has no directory, so the files come with it, each keyed by the+bundle-relative path a step names, read as if every bundle of the submission sat in one directory. The library places+those bundles at the root of the tree these files make (`LibraryManager`), so a step resolves a file it names there, as+it would in a folder, and the run's crate names that tree by its digest like any other: no file's bytes travel with it."""-import base64-import binascii-import hashlibfrom collections.abc import Mapping-from enum import StrEnumfrom pathlib import PurePosixPath-from typing import Self--from pydantic import BaseModel, ConfigDict, Field, model_validator--from pipelex.core.bundle_resources.exceptions import BundleResourceError, BundleResourcePathError-from pipelex.tools.storage.storage_provider_abstract import PIPELEX_STORAGE_SCHEME, StorageProviderAbstract--MAX_LOAD_STAGE_RESOURCES_BYTES = 512 * 1024-"""The most the files a bundle's steps read when the method loads, such as its HTML templates, may total, in bytes.--They travel inline in the method's crate wherever it runs, a remote orchestrator's payloads included, where the remote-side reads them while it loads the crate and may do no IO, so they cannot move to the run's storage as an office-template does. Sized well under Temporal's 2 MB payload limit, with room for the third that base64 adds and for the-method's own text. A fixed bound, not a setting: raising it would let a run that passed every check fail at dispatch.-"""---class BundleResourceReadStage(StrEnum):- """When a step reads a file of its bundle, which decides how the file travels with the bundle's crate."""-- LOAD = "load"- """Read while the method loads, such as an HTML template checked against the step's inputs: it travels inline."""-- RUN = "run"- """Read only when the step runs, such as an office template its engine fills: it may travel by reference."""- @property- def is_read_at_load(self) -> bool:- """Whether the file is read while the method loads, so it travels inline with the method wherever it runs."""- match self:- case BundleResourceReadStage.LOAD:- return True- case BundleResourceReadStage.RUN:- return False+from pipelex.core.bundle_resources.exceptions import BundleResourcePathErrordef resource_path_refusal(*, path: str) -> str | None:@@ -91,7 +49,7 @@ def canonical_resource_path_or_none(*, path: str) -> str | None:def canonical_resource_path(*, path: str) -> str:- """The one spelling of a bundle-relative path, the key a resource is held and looked up under.+ """The one spelling of a bundle-relative path, the key a submitted file is held and looked up under.POSIX separators only, relative, and inside the bundle: an absolute path, a `..` segment, a backslash, a colonand an empty path are refused. `.` segments and repeated slashes collapse, so `./invoice.xlsx` and@@ -107,93 +65,17 @@ def canonical_resource_path(*, path: str) -> str:return PurePosixPath(path).as_posix()-class BundleResource(BaseModel):- """One file of a bundle, with its bytes inline or stored, and their digest either way."""-- model_config = ConfigDict(frozen=True, extra="forbid")-- sha256: str = Field(description="The SHA-256 of the file's bytes, in hexadecimal")- size: int = Field(ge=0, description="The file's size in bytes")- content_b64: str | None = Field(default=None, description="The file's bytes, base64-encoded, when they travel inline")- uri: str | None = Field(default=None, description="The pipelex-storage URI of the file's bytes, when they were stored")-- @model_validator(mode="after")- def validate_carrier(self) -> Self:- if (self.content_b64 is None) == (self.uri is None):- msg = "A bundle resource carries its bytes either inline or by reference, exactly one of the two."- raise ValueError(msg)- if self.uri is not None and not self.uri.startswith(PIPELEX_STORAGE_SCHEME):- msg = f"A bundle resource stored by reference names a '{PIPELEX_STORAGE_SCHEME}' URI."- raise ValueError(msg)- return self-- @classmethod- def make_inline(cls, *, content: bytes) -> Self:- return cls(- sha256=hashlib.sha256(content).hexdigest(),- size=len(content),- content_b64=base64.b64encode(content).decode("ascii"),- )-- def stored_at(self, *, uri: str) -> Self:- """The same file, now carried by reference to where its bytes were stored."""- return self.model_copy(update={"content_b64": None, "uri": uri})-- @property- def is_inline(self) -> bool:- return self.content_b64 is not None-- def inline_bytes(self) -> bytes:- """The file's bytes, which it carries inline.-- Raises:- BundleResourceError: the file was stored, so its bytes are read through the run's storage.- """- if self.content_b64 is None:- msg = "The bundle file was stored with its run, so it is read through the run's storage provider."- raise BundleResourceError(msg)- try:- return base64.b64decode(self.content_b64, validate=True)- except binascii.Error as exc:- msg = "The bundle file's inline bytes are not valid base64."- raise BundleResourceError(msg) from exc-- async def read_bytes(self, *, storage_provider: StorageProviderAbstract) -> bytes:- """The file's bytes, inline or read back from storage and checked against their digest.-- A stored file is read from its own `pipelex-storage://` URI only. The caller authorizes that read against the- run's read scope first, as it does every file a step reads.-- Raises:- BundleResourceError: the stored bytes no longer match the digest the file was submitted with.- """- if self.content_b64 is not None:- return self.inline_bytes()- if self.uri is None:- msg = "A bundle resource carries its bytes either inline or by reference."- raise BundleResourceError(msg)- data = await storage_provider.load(self.uri)- if hashlib.sha256(data).hexdigest() != self.sha256:- msg = "The stored bundle file no longer matches the file submitted with the bundle."- raise BundleResourceError(msg)- return data---BundleResources = dict[str, BundleResource]-"""A bundle's files, keyed by their canonical bundle-relative path."""---def make_bundle_resources(*, files: Mapping[str, bytes]) -> BundleResources:- """The files submitted with a bundle, keyed by their canonical path and carried inline.+def canonical_submitted_files(*, files: Mapping[str, bytes]) -> dict[str, bytes]:+ """The files submitted with bundles, keyed by their canonical bundle-relative path.Raises:BundleResourcePathError: a path cannot name a file inside the bundle, or two paths name the same file."""- resources: BundleResources = {}+ canonical_files: dict[str, bytes] = {}for path, content in files.items():canonical_path = canonical_resource_path(path=path)- if canonical_path in resources:+ if canonical_path in canonical_files:msg = f"Two files submitted with the bundle name the same file '{canonical_path}'."raise BundleResourcePathError(msg)- resources[canonical_path] = BundleResource.make_inline(content=content)- return resources+ canonical_files[canonical_path] = content+ return canonical_filesdiff --git a/pipelex/core/bundle_resources/exceptions.py b/pipelex/core/bundle_resources/exceptions.pyindex 4ad56959f..3895aa245 100644--- a/pipelex/core/bundle_resources/exceptions.py+++ b/pipelex/core/bundle_resources/exceptions.py@@ -1,16 +1,14 @@from pipelex.base_exceptions import ErrorDomain, PipelexError-class BundleResourceError(PipelexError):- """Raised when a bundle resource cannot be read: stored bytes that no longer match their digest, or a read the resource cannot serve."""--class BundleResourcePathError(PipelexError):"""Raised when a file submitted with a bundle is keyed by a path that cannot name a file inside the bundle.- 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, and the same request is refused again.+ A submitted file'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, or a key the tree of the submitted files cannot hold, such as one colliding with another once+ case-folded, or naming a file already submitted, from a library directory or with the request, with other bytes.+ 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@@ -29,16 +27,3 @@ class BundleResourceNotNamedError(PipelexError):error_domain = ErrorDomain.INPUTretryable = False_authors_caller_facing_message = True---class BundleResourcesTooLargeError(PipelexError):- """Raised when the files a bundle's steps read when the method loads, such as HTML templates, are too large in total.-- 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, and the same request is refused again.- """-- error_domain = ErrorDomain.INPUT- retryable = False- _authors_caller_facing_message = Truediff --git a/pipelex/core/method_trees/building_bundle.py b/pipelex/core/method_trees/building_bundle.pyindex 2351cc4bb..0b629faca 100644--- a/pipelex/core/method_trees/building_bundle.py+++ b/pipelex/core/method_trees/building_bundle.py@@ -1,24 +1,34 @@"""The method tree member a pipe is being built from, for the factories that resolve a file reference while building.-The library manager builds every pipe of a bundle it read from disk inside `building_pipe_of`, naming the bundle's-member of its method tree, and every pipe of a bundle parsed from a content string with none. A factory that resolves-a file the step names, such as `PipeDocGen`'s `template_file`, reads it here: the tree is the only place it looks, so-neither a `source` a caller labelled a bundle with nor one the bundle's own text wrote can point a read at this host's-disk.+The library manager builds every pipe inside `building_pipe_of`, naming where its bundle lies:++- a `TreeBundle` for a bundle this host holds, read from its disk as a member of a method tree, or parsed from a content+ string and placed at the root of the tree of the files submitted with it: a factory resolves a file the step names,+ such as `PipeDocGen`'s `template_file`, in that tree, checks the file is there, and may read it to check it;+- a `TreeBundleRef` for a pipe built from a library crate, which names the tree by digest and carries no listing: a+ factory resolves the reference lexically and reads nothing, the host that assembled the crate having checked it;+- None for a bundle parsed from a content string with no file submitted beside it.++The tree is the only place a factory looks, so neither a `source` a caller labelled a bundle with nor one the bundle's+own text wrote can point a read at this host's disk."""from collections.abc import Generatorfrom contextlib import contextmanagerfrom contextvars import ContextVar+from typing import TypeAlias++from pipelex.core.method_trees.tree_bundle import TreeBundle, TreeBundleRef-from pipelex.core.method_trees.tree_bundle import TreeBundle+#: Where the bundle of a pipe being built lies: a tree this host holds, a tree a crate names, or none.+BuildingBundle: TypeAlias = TreeBundle | TreeBundleRef | None-_BUILDING_TREE_BUNDLE: ContextVar[TreeBundle | None] = ContextVar("building_tree_bundle", default=None)+_BUILDING_TREE_BUNDLE: ContextVar[BuildingBundle] = ContextVar("building_tree_bundle", default=None)@contextmanager-def building_pipe_of(*, tree_bundle: TreeBundle | None) -> Generator[None, None, None]:- """Build the pipes inside this block as pipes of `tree_bundle`, or of a bundle parsed from a string when None."""+def building_pipe_of(*, tree_bundle: BuildingBundle) -> Generator[None, None, None]:+ """Build the pipes inside this block as pipes of `tree_bundle`, as `BuildingBundle` describes it."""token = _BUILDING_TREE_BUNDLE.set(tree_bundle)try:yield@@ -26,6 +36,6 @@ def building_pipe_of(*, tree_bundle: TreeBundle | None) -> Generator[None, None,_BUILDING_TREE_BUNDLE.reset(token)-def get_building_tree_bundle() -> TreeBundle | None:- """The member of its method tree the pipe being built was read from, or None for a bundle parsed from a string."""+def get_building_tree_bundle() -> BuildingBundle:+ """Where the bundle of the pipe being built lies, as `BuildingBundle` describes it."""return _BUILDING_TREE_BUNDLE.get()diff --git a/pipelex/core/method_trees/exceptions.py b/pipelex/core/method_trees/exceptions.pyindex ed25d4ffc..c70c11e09 100644--- a/pipelex/core/method_trees/exceptions.py+++ b/pipelex/core/method_trees/exceptions.py@@ -38,3 +38,12 @@ class TreeModuleExcludedError(ImportError):super().__init__(message, name=module_name)self.message = messageself.tree_path = tree_path+++class MethodFileUnavailableError(PipelexError):+ """A method file, or the listing of the tree that holds it, cannot be read through the method file store.++ The store does not hold it, such as a tree the process that assembled the run never handed over, or the bytes it+ holds no longer match the hash the tree's listing names, such as a file edited on disk after its tree was listed. The+ message names the tree by its digest and the file by its tree path, never by a path of this host.+ """diff --git a/pipelex/core/method_trees/file_references.py b/pipelex/core/method_trees/file_references.pyindex 31c354849..0e38d4305 100644--- a/pipelex/core/method_trees/file_references.py+++ b/pipelex/core/method_trees/file_references.py@@ -6,24 +6,35 @@ file of the tree, which is a lookup in the set of tree paths the listing produceout of the tree, a dotfile, a `.gitignore`d file or a file of a nested package, is invisible to the step, and nothingoutside the tree is ever opened.-A bundle loaded from a content string belongs to no tree and reads only the files submitted with it, so the parser,-told so by its caller, validates its blueprint under that origin (`BundleValidationContext`), and a reference none of-those files could be keyed by is refused there, as a blueprint item at the step that names it.+A bundle loaded from a content string reads only the files submitted with it, so the parser, told so by its caller,+validates its blueprint under that origin (`BundleValidationContext`), and a reference none of those files could be keyed+by is refused there, as a blueprint item at the step that names it. Such bundles sit at the root of the tree of the files+submitted with them, so their references resolve from the root, and the result must be one of those files. Such a+reference is first spelled the one way the submitted files are keyed, its `.` segments and repeated slashes collapsed,+so `templates//invoice.docx` names the file submitted as `templates/invoice.docx`.++A pipe built from a library crate, which names its bundle's tree by digest and carries no listing, resolves a reference+lexically and reads nothing: the host that assembled the crate resolved it in the tree and checked the file was there."""from enum import StrEnum-from mthds.method_tree.exceptions import MethodTreeRefusedError-from mthds.method_tree.references import resolve_reference+from mthds.method_tree.exceptions import MethodTreeRefusedError, TreeRefusal+from mthds.method_tree.references import ROOT_RESOLVED, lexical_join, resolve_reference+from mthds.method_tree.tree_path import nfc, tree_path_violationfrom mthds.method_tree.vocabulary import ReferenceContext, TreeRefusalCodefrom pydantic import BaseModel, ConfigDict, Fieldfrom pipelex.base_exceptions import PipelexUnexpectedError-from pipelex.core.bundle_resources.bundle_resource import resource_path_refusal-from pipelex.core.method_trees.tree_bundle import TreeBundle+from pipelex.core.bundle_resources.bundle_resource import canonical_resource_path_or_none, resource_path_refusal+from pipelex.core.method_trees.tree_bundle import TreeBundle, TreeBundleRefONE_FILE_TREE_ADVICE = "Run the method's folder instead, or add a METHODS.toml to it."+#: The holder a reference is joined to when it is written in bundles at the root of their tree, which they are no file of:+#: any lone segment, since a join keeps the holder's directories and drops its name.+_ROOT_HOLDER = "."+class BundleFileOrigin(StrEnum):"""Where a bundle's steps find the files they name, which decides the rule a file reference is held to.@@ -106,10 +117,21 @@ def file_reference_form_refusal(*, reference: str) -> str | None:def resolve_bundle_file_reference(*, reference: str, tree_bundle: TreeBundle) -> str:"""The tree path of the file a bundle field names, resolved against the bundle's tree path in its method tree.+ Bundles at the root of the tree of the files submitted with them resolve a reference from the root, and the result+ must be one of those files.+Raises:MethodTreeRefusedError: When the reference is refused; `refusal.code` says at which step of the resolution,and `reference_refusal_reason` words it for the bundle's author."""+ if tree_bundle.tree_path is None:+ resolved_from_root = _join_lexically(reference=reference, holder=None)+ if resolved_from_root not in tree_bundle.tree.members:+ msg = f"The file reference '{reference}' resolves to '{resolved_from_root}', which is not one of the files submitted with the bundle."+ raise MethodTreeRefusedError(+ msg, refusal=TreeRefusal(code=TreeRefusalCode.REFERENCE_NOT_IN_TREE, names=[reference], resolved=resolved_from_root)+ )+ return resolved_from_rootresolved = resolve_reference(reference, holder=tree_bundle.tree_path, context=ReferenceContext.PATH, tree=tree_bundle.tree)if resolved is None:msg = f"A reference in path context is always a file reference, yet '{reference}' was resolved as none."@@ -117,6 +139,51 @@ def resolve_bundle_file_reference(*, reference: str, tree_bundle: TreeBundle) ->return resolved+def resolve_crate_file_reference(*, reference: str, tree_bundle_ref: TreeBundleRef) -> str:+ """The tree path of the file a bundle field names, joined to the bundle's tree path as a library crate names it.++ A crate names its bundles' trees by digest and carries no listing, so the reference is resolved lexically and+ nothing is read: the host that assembled the crate resolved it in the tree, and found the file there.++ Raises:+ MethodTreeRefusedError: The reference cannot name a file of any tree from where the bundle lies.+ """+ return _join_lexically(reference=reference, holder=tree_bundle_ref.tree_path)+++def _join_lexically(*, reference: str, holder: str | None) -> str:+ """The tree path `reference` names from `holder`, or from the root when None, by the standard's join alone.++ From the root, the reference names a file submitted beside bundles loaded from content strings, so it is first spelled+ as those files are keyed (`canonical_resource_path_or_none`): blueprint validation accepts a repeated slash or a `.`+ segment there, which the standard's join would otherwise keep as an empty segment.++ Raises:+ MethodTreeRefusedError: The reference's form names no file, it climbs above the root, or it names the root.+ """+ form_refusal = file_reference_form_refusal(reference=reference)+ if form_refusal is not None:+ msg = f"The file reference '{reference}' cannot name a file of a method tree: {form_refusal}."+ raise MethodTreeRefusedError(msg, refusal=TreeRefusal(code=TreeRefusalCode.REFERENCE_INVALID, names=[reference]))+ if holder is None:+ joined = canonical_resource_path_or_none(path=reference) or reference+ segments = lexical_join(holder=_ROOT_HOLDER, path=nfc(joined))+ else:+ segments = lexical_join(holder=holder, path=nfc(reference))+ if segments is None:+ msg = f"The file reference '{reference}' climbs above the root of its method tree."+ raise MethodTreeRefusedError(msg, refusal=TreeRefusal(code=TreeRefusalCode.REFERENCE_LEAVES_TREE, names=[reference]))+ if segments in ([], [""]):+ msg = f"The file reference '{reference}' resolves to the root of the tree, not a file."+ raise MethodTreeRefusedError(msg, refusal=TreeRefusal(code=TreeRefusalCode.REFERENCE_NOT_IN_TREE, names=[reference], resolved=ROOT_RESOLVED))+ resolved = "/".join(segments)+ violation = tree_path_violation(resolved)+ if violation is not None:+ msg = f"The file reference '{reference}' resolves to '{resolved}', which is not a tree path: {violation}."+ raise MethodTreeRefusedError(msg, refusal=TreeRefusal(code=TreeRefusalCode.REFERENCE_NOT_A_TREE_PATH, names=[reference], resolved=resolved))+ return resolved++def reference_refusal_reason(*, refusal_error: MethodTreeRefusedError, tree_bundle: TreeBundle) -> str:"""Why a file reference was refused, as a sentence naming files by their tree paths only, never by a host path.diff --git a/pipelex/core/method_trees/method_file_store.py b/pipelex/core/method_trees/method_file_store.pynew file mode 100644index 000000000..b1f30aa38--- /dev/null+++ b/pipelex/core/method_trees/method_file_store.py@@ -0,0 +1,236 @@+"""The method file store: where the process that uses a method file reads it, by the digest of its tree and its hash.++A run's library crate names each tree it loads by its digest and carries none of its bytes (`wip/extra-files/design.md`,+"Inside a run"). Whatever later needs a file of the method, a `PipeFunc` call writing its tree for the function to import,+a `PipeDocGen` print reading its template, reads it through this one seam, where IO is allowed: in the activity that+uses the file, never in a workflow. The store answers two questions, laid out as the hosted plane lays out its blobs: the+listing of a tree, by the tree's digest, and a file's bytes, by their SHA-256. `pipelex.core.method_trees.method_files`+does the rest: it checks the listing against the digest and each file against the hash the listing names.++Every read carries the run's read scope, the trusted prefix the host scopes the run's reads to: a hosted implementation+builds its keys from it, so a run reads the method files of its own organization only. The local implementation below+serves one process and ignores it.++`LocalMethodFileStore` is pipelex's own implementation and the default one: it serves the trees this process's+libraries listed or were handed, while those libraries hold them. A tree listed from a directory is read from the disk,+and checked against the hash its listing recorded, so a file edited after the listing is not served as the file the run+validated; a tree a library assembled in memory, such as the files submitted with bundles loaded from content strings,+is served from the bytes it holds. A host whose activities run in another process than the one that listed the tree,+such as a Temporal worker, claims `HubSlot.METHOD_FILE_STORE` with an implementation reading its own blob store.+"""++import asyncio+import threading+from collections.abc import Mapping+from pathlib import Path+from typing import NamedTuple, Protocol++from mthds.method_tree.digest import sha256_hex, tree_digest, tree_listing+from mthds.method_tree.models import MethodTree, TreeFile+from mthds.method_tree.tree_path import sorted_tree_paths+from typing_extensions import override+++class MethodFileStoreProtocol(Protocol):+ """Reads a tree's listing by the tree's digest, and a file's bytes by their SHA-256, under the run's read scope."""++ async def read_tree_listing(self, *, tree_digest: str, read_scope: str | None) -> bytes | None:+ """The listing of the tree whose digest is `tree_digest`, as the standard writes it, or None when not held.++ Args:+ tree_digest: The tree's digest, `sha256:` and 64 lowercase hexadecimal digits.+ read_scope: The run's read scope, which a hosted store builds its keys from; None for an unscoped run.+ """+ ...++ async def read_blob(self, *, sha256: str, read_scope: str | None) -> bytes | None:+ """The bytes whose SHA-256 is `sha256`, in lowercase hexadecimal, or None when not held.++ Args:+ sha256: The SHA-256 of the bytes, as a tree's listing names it.+ read_scope: The run's read scope, which a hosted store builds its keys from; None for an unscoped run.+ """+ ...+++class HeldFile(NamedTuple):+ """A file of a tree the local store holds: its hash and size, and where its bytes are, on disk or in memory."""++ sha256: str+ size: int+ source: Path | bytes++ @classmethod+ def of_bytes(cls, *, data: bytes) -> "HeldFile":+ return cls(sha256=sha256_hex(data), size=len(data), source=data)+++class _HeldTree(NamedTuple):+ tree: MethodTree+ files: dict[str, HeldFile]+++class _HeldFileKey(NamedTuple):+ """Which holder holds a file, in which tree and at which tree path: the key of the store's index by hash."""++ holder: str+ tree_digest: str+ tree_path: str+++def tree_of_held_files(*, files: Mapping[str, HeldFile]) -> MethodTree:+ """The tree whose files are `files`, keyed by tree path, read from no directory: its listing and its digest.++ The caller has checked that every key is a tree path and that no two collide.+ """+ tree_files = [TreeFile(path=tree_path, sha256=files[tree_path].sha256, size=files[tree_path].size) for tree_path in sorted_tree_paths(files)]+ return MethodTree(files=tree_files, digest=tree_digest(tree_files))+++class LocalMethodFileStore(MethodFileStoreProtocol):+ """The trees this process's libraries hold, served from the disk they were listed from or from the bytes held for them.++ A library holds the trees it loads, under its own id, until it is torn down (`release`), so a tree is served while+ any run of a library holding it may still read it. Two libraries holding the same tree serve it from either's+ sources, since a digest names the same files wherever they are read from: a file is served from the first source+ whose bytes still match its hash.+ """++ def __init__(self) -> None:+ self._lock = threading.Lock()+ # holder -> tree digest -> the tree as that holder listed or assembled it, with where its files are read from.+ self._held: dict[str, dict[str, _HeldTree]] = {}+ # sha256 -> every held file with those bytes, in the order they were held: the index `read_blob` reads, so a read+ # of every file of a tree costs one lookup per file rather than a scan of every held file.+ self._by_sha256: dict[str, dict[_HeldFileKey, HeldFile]] = {}++ def hold_tree(self, *, holder: str, tree: MethodTree) -> None:+ """Serve `tree`, listed from a directory of this host, for `holder` until it releases its trees.++ Raises:+ ValueError: The tree was not listed from a directory, so this store cannot read its files.+ """+ if tree.directory is None:+ msg = "A tree held from the disk is a tree listed from a directory; one assembled in memory is held with hold_files."+ raise ValueError(msg)+ files = {+ tree_file.path: HeldFile(sha256=tree_file.sha256, size=tree_file.size, source=tree.file_location(tree_file.path))+ for tree_file in tree.files+ }+ self._hold(holder=holder, held_tree=_HeldTree(tree=tree, files=files))++ def hold_files(self, *, holder: str, files: Mapping[str, HeldFile]) -> MethodTree:+ """Serve the tree whose files are `files`, keyed by tree path, for `holder` until it releases its trees, and return it.++ The caller has checked that every key is a tree path and that no two collide.+ """+ tree = tree_of_held_files(files=files)+ self._hold(holder=holder, held_tree=_HeldTree(tree=tree, files=dict(files)))+ return tree++ def _hold(self, *, holder: str, held_tree: _HeldTree) -> None:+ tree_digest = held_tree.tree.digest+ with self._lock:+ held_trees = self._held.setdefault(holder, {})+ # A holder holding a tree it already holds keeps its first sources.+ if tree_digest in held_trees:+ return+ held_trees[tree_digest] = held_tree+ for tree_path, held_file in held_tree.files.items():+ key = _HeldFileKey(holder=holder, tree_digest=tree_digest, tree_path=tree_path)+ self._by_sha256.setdefault(held_file.sha256, {})[key] = held_file++ def holds(self, *, holder: str, tree_digest: str) -> bool:+ """Whether `holder` already holds the tree `tree_digest`."""+ with self._lock:+ return tree_digest in self._held.get(holder, {})++ def _held_trees(self, *, tree_digest: str) -> list[_HeldTree]:+ """Every holder's record of the tree `tree_digest`, in the order the holders first held a tree."""+ with self._lock:+ return [held_trees[tree_digest] for held_trees in self._held.values() if tree_digest in held_trees]++ def release(self, *, holder: str) -> None:+ """Stop serving the trees `holder` held, except from the sources another holder still holds them with."""+ with self._lock:+ held_trees = self._held.pop(holder, {})+ for tree_digest, held_tree in held_trees.items():+ for tree_path, held_file in held_tree.files.items():+ same_bytes = self._by_sha256.get(held_file.sha256)+ if same_bytes is None:+ continue+ same_bytes.pop(_HeldFileKey(holder=holder, tree_digest=tree_digest, tree_path=tree_path), None)+ if not same_bytes:+ del self._by_sha256[held_file.sha256]++ def release_all(self) -> None:+ """Stop serving every tree."""+ with self._lock:+ self._held = {}+ self._by_sha256 = {}++ def held_files_with_hash(self, *, sha256: str) -> list[HeldFile]:+ """Every held file whose bytes have the SHA-256 `sha256`, in the order they were held, wherever their bytes are."""+ with self._lock:+ return list(self._by_sha256.get(sha256, {}).values())++ def held_tree(self, *, tree_digest: str) -> MethodTree | None:+ """The tree held under `tree_digest`, as listed or assembled, or None when no library holds it."""+ held_trees = self._held_trees(tree_digest=tree_digest)+ return held_trees[0].tree if held_trees else None++ def read_held_file(self, *, tree_digest: str, tree_path: str) -> bytes | None:+ """The bytes of the file at `tree_path` of the tree held under `tree_digest`, checked against its hash, or None.++ None when the tree is not held, holds no file at `tree_path`, or holds one on disk whose bytes changed since the+ tree was listed or that can no longer be read.+ """+ for held_tree in self._held_trees(tree_digest=tree_digest):+ held_file = held_tree.files.get(tree_path)+ if held_file is None:+ return None+ data = _read_held_file(held_file=held_file)+ if data is not None:+ return data+ return None++ @override+ async def read_tree_listing(self, *, tree_digest: str, read_scope: str | None) -> bytes | None:+ # One process, one organization: the read scope selects nothing here.+ held_tree = self.held_tree(tree_digest=tree_digest)+ if held_tree is None:+ return None+ return tree_listing(held_tree.files)++ @override+ async def read_blob(self, *, sha256: str, read_scope: str | None) -> bytes | None:+ # One process, one organization: the read scope selects nothing here.+ for held_file in self.held_files_with_hash(sha256=sha256):+ match held_file.source:+ case bytes() as data:+ return data+ case Path():+ # Reading and hashing a file on disk blocks, so it runs off the event loop.+ read_from_disk = await asyncio.to_thread(_read_held_file, held_file=held_file)+ if read_from_disk is not None:+ return read_from_disk+ return None+++def _read_held_file(*, held_file: HeldFile) -> bytes | None:+ """The bytes of a held file when they still match its hash, or None."""+ match held_file.source:+ case bytes() as data:+ return data+ case Path() as location:+ try:+ data = location.read_bytes()+ except OSError:+ return None+ if sha256_hex(data) != held_file.sha256:+ return None+ return data+++#: The store this process's libraries hold their trees in, and the default the runtime hub reads method files through.+LOCAL_METHOD_FILES = LocalMethodFileStore()diff --git a/pipelex/core/method_trees/method_files.py b/pipelex/core/method_trees/method_files.pynew file mode 100644index 000000000..1a5660fd7--- /dev/null+++ b/pipelex/core/method_trees/method_files.py@@ -0,0 +1,156 @@+"""A method file named by its tree's digest and its tree path, and the reads that reach it through the method file store.++A library crate names each tree a run loads by its digest, and a step names a file of its tree by the file's tree path,+so a method file travels as a `MethodFileRef` and its bytes are read only where they are used, in an activity, through+the method file store the runtime hub holds (`pipelex.core.method_trees.method_file_store`). Every read is checked: the+listing against the digest that names it, and each file against the hash the listing names, so a store serving the+wrong bytes is refused rather than trusted.+"""++from collections.abc import Callable, Iterable++from mthds.method_tree.digest import DIGEST_PREFIX, is_sha256_hex, sha256_hex+from mthds.method_tree.tree_path import tree_path_violation+from pydantic import BaseModel, ConfigDict++from pipelex.core.method_trees.exceptions import MethodFileUnavailableError+from pipelex.core.method_trees.tree_bundle import MethodFileRef+from pipelex.runtime_hub import get_method_file_store++#: The separator between a file's hash and its tree path on a line of a tree's listing.+_LISTING_SEPARATOR = " "+#: What ends each line of a tree's listing, and the only character that does.+_LISTING_LINE_END = "\n"+++class TreeListing(BaseModel):+ """A tree's listing, read and checked against its digest: each file's SHA-256, by tree path."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ tree_digest: str+ files: dict[str, str]++ @classmethod+ def parse(cls, *, tree_digest: str, listing: bytes) -> "TreeListing":+ """Read a tree's listing, as the standard writes it, after checking that it is the listing `tree_digest` names.++ Raises:+ MethodFileUnavailableError: The bytes are not the listing the digest names, or not a listing at all.+ """+ if DIGEST_PREFIX + sha256_hex(listing) != tree_digest:+ msg = f"The listing the method file store returned for the tree '{tree_digest}' is not the one its digest names."+ raise MethodFileUnavailableError(msg)+ try:+ text = listing.decode("utf-8")+ except UnicodeDecodeError as exc:+ msg = f"The listing of the tree '{tree_digest}' is not UTF-8 text."+ raise MethodFileUnavailableError(msg) from exc+ # The standard ends every line with a line feed, and only a line feed separates them: a tree path may hold any+ # other character `str.splitlines` would split on, such as U+2028 or U+2029.+ if text and not text.endswith(_LISTING_LINE_END):+ msg = f"The listing of the tree '{tree_digest}' does not end with a line feed."+ raise MethodFileUnavailableError(msg)+ files: dict[str, str] = {}+ for line in text.split(_LISTING_LINE_END)[:-1]:+ sha256, separator, tree_path = line.partition(_LISTING_SEPARATOR)+ if not separator or not is_sha256_hex(sha256) or tree_path_violation(tree_path) is not None:+ msg = f"The listing of the tree '{tree_digest}' holds a line that is not a file's hash and tree path."+ raise MethodFileUnavailableError(msg)+ files[tree_path] = sha256+ return cls(tree_digest=tree_digest, files=files)+++async def read_tree_listing(*, tree_digest: str, read_scope: str | None) -> TreeListing:+ """The listing of the tree `tree_digest` names, read through the method file store under the run's read scope.++ Raises:+ MethodFileUnavailableError: The store does not hold the tree, or serves a listing its digest does not name.+ """+ listing = await get_method_file_store().read_tree_listing(tree_digest=tree_digest, read_scope=read_scope)+ if listing is None:+ msg = f"The method file store holds no tree '{tree_digest}' for this run."+ raise MethodFileUnavailableError(msg)+ return TreeListing.parse(tree_digest=tree_digest, listing=listing)+++async def _read_listed_file(*, listing: TreeListing, tree_path: str, read_scope: str | None) -> bytes:+ sha256 = listing.files.get(tree_path)+ if sha256 is None:+ msg = f"The tree '{listing.tree_digest}' holds no file '{tree_path}'."+ raise MethodFileUnavailableError(msg)+ data = await get_method_file_store().read_blob(sha256=sha256, read_scope=read_scope)+ if data is None:+ msg = f"The method file store does not hold the file '{tree_path}' of the tree '{listing.tree_digest}' for this run."+ raise MethodFileUnavailableError(msg)+ if sha256_hex(data) != sha256:+ msg = f"The bytes the method file store returned for the file '{tree_path}' of the tree '{listing.tree_digest}' are not the file's."+ raise MethodFileUnavailableError(msg)+ return data+++async def read_method_file(*, file_ref: MethodFileRef, read_scope: str | None) -> bytes:+ """The bytes of a method file, read through the method file store under the run's read scope and checked against its hash.++ Raises:+ MethodFileUnavailableError: The store does not hold the tree or the file, or serves bytes the tree does not name.+ """+ listing = await read_tree_listing(tree_digest=file_ref.tree_digest, read_scope=read_scope)+ return await _read_listed_file(listing=listing, tree_path=file_ref.tree_path, read_scope=read_scope)+++async def read_tree_files(*, tree_digest: str, read_scope: str | None, keeps: Callable[[str], bool] | None = None) -> dict[str, bytes]:+ """The files of the tree `tree_digest` names, by tree path, read through the method file store and checked.++ Args:+ tree_digest: The tree's digest.+ read_scope: The run's read scope.+ keeps: Decides, from a file's tree path, whether it is read; every file is read when None.++ Raises:+ MethodFileUnavailableError: The store does not hold the tree or one of its files, or serves bytes the tree does not name.+ """+ listing = await read_tree_listing(tree_digest=tree_digest, read_scope=read_scope)+ files: dict[str, bytes] = {}+ for tree_path in listing.files:+ if keeps is not None and not keeps(tree_path):+ continue+ files[tree_path] = await _read_listed_file(listing=listing, tree_path=tree_path, read_scope=read_scope)+ return files+++class StoredTree(BaseModel):+ """A method tree as a store keeps it: its listing, under the tree's digest, and its files' bytes, under their hashes."""++ model_config = ConfigDict(frozen=True, extra="forbid")++ tree_digest: str+ listing: bytes+ blobs: dict[str, bytes]+++async def read_stored_trees(*, tree_digests: Iterable[str], read_scope: str | None) -> list[StoredTree]:+ """Every tree `tree_digests` names, as a store keeps it, read through the method file store and checked.++ What an orchestrator that runs a job out of process copies into the store its workers read, for every tree the job's+ crate names (`LibraryCrate.tree_digests`), before its `execute` or `start` returns: the runner may drop the files a+ tree was listed from as soon as it does, such as the temporary directory it wrote a request's files into, and the+ library holding the tree in this process is torn down with the request (`OrchestratorProtocol`).++ Raises:+ MethodFileUnavailableError: The store does not hold a tree or one of its files, or serves bytes the tree does not name.+ """+ method_file_store = get_method_file_store()+ stored_trees: list[StoredTree] = []+ for tree_digest in tree_digests:+ listing_bytes = await method_file_store.read_tree_listing(tree_digest=tree_digest, read_scope=read_scope)+ if listing_bytes is None:+ msg = f"The method file store holds no tree '{tree_digest}' for this run."+ raise MethodFileUnavailableError(msg)+ listing = TreeListing.parse(tree_digest=tree_digest, listing=listing_bytes)+ blobs: dict[str, bytes] = {}+ for tree_path, sha256 in listing.files.items():+ if sha256 not in blobs:+ blobs[sha256] = await _read_listed_file(listing=listing, tree_path=tree_path, read_scope=read_scope)+ stored_trees.append(StoredTree(tree_digest=tree_digest, listing=listing_bytes, blobs=blobs))+ return stored_treesdiff --git a/pipelex/core/method_trees/tree_bundle.py b/pipelex/core/method_trees/tree_bundle.pyindex fa25cfae7..51761e2d1 100644--- a/pipelex/core/method_trees/tree_bundle.py+++ b/pipelex/core/method_trees/tree_bundle.py@@ -1,50 +1,80 @@-"""A bundle as a member of its method tree: the tree it was listed in, and its tree path there.+"""A bundle as a member of its method tree, and a file of a method tree, as this host holds them and as a crate names them.A bundle read from this host's disk is always read as a member of a method tree (`mthds/docs/spec/method-tree.md`),listed by `mthds-python`'s lister: a library directory's tree, the tree of a method's folder, the tree of a `.mthds`file named alone, or a dependency package's tree. A file the bundle's steps name, such as a `PipeDocGen` step's`template_file`, is then resolved in that tree, by a lookup in its set of tree paths, and never by opening a path the-bundle wrote. A bundle parsed from a content string belongs to no tree here.+bundle wrote. Bundles parsed from content strings sit at the root of the tree of the files submitted with them, when+there are any, a tree this host assembled in memory (`LibraryManager`), and belong to no tree otherwise.++A library crate carries none of this: it names each bundle's tree by the tree's digest and the bundle by its tree path+(`TreeBundleRef`), and a step names a file of its tree the same way (`MethodFileRef`), so a crate travels without a+file's bytes or a path of the host that assembled it, and the process that uses a file reads it through the method file+store (`pipelex.core.method_trees.method_file_store`)."""from pathlib import Pathfrom mthds.method_tree.models import MethodTree-from pydantic import BaseModel, ConfigDict-+from pydantic import BaseModel, ConfigDict, Field-def tree_key_of(*, tree: MethodTree) -> str:- """The key a tree is held under where several travel together, such as in a library crate.- Two listings of one directory with the same files share a key, and a one-file tree never shares one with the- directory tree of its folder, since only the latter lets a reference reach another file.- """- kind = "one-file" if tree.is_one_file else "directory"- return f"{kind}:{tree.directory}:{tree.digest}"+class TreeBundle(BaseModel):+ """A bundle of a method tree this host holds: the tree, and the bundle's tree path in it.+ `tree_path` is None for bundles parsed from content strings, which sit at the root of the tree of the files submitted+ with them without being a file of it: a reference they write resolves from the root.-class TreeBundle(BaseModel):- """A bundle file of a method tree: the tree, listed from this host's disk, and the bundle's tree path in it."""+ `named_digest` is the digest a library crate names the tree by, when this host wrote the tree out apart from its+ bundles, such as the tree of a `PipeFunc` call written for its function to import, which holds no `.mthds` file and+ may hold a generated `structures` module, so its own digest is not the crate's. None when the tree is the one the+ crate names. `digest` is the one to name the tree by to any other process.+ """model_config = ConfigDict(frozen=True)tree: MethodTree- tree_path: str+ tree_path: str | None+ named_digest: str | None = None@property- def tree_key(self) -> str:- return tree_key_of(tree=self.tree)+ def digest(self) -> str:+ """The digest the tree is named by outside this host: the crate's, when this host wrote the tree out, else its own."""+ return self.named_digest or self.tree.digest@propertydef location(self) -> Path:- """Where the bundle's file lies on this host."""+ """Where the bundle's file lies on this host.++ Raises:+ ValueError: The bundle is not a file of a tree listed from a directory.+ """+ if self.tree_path is None:+ msg = "A bundle parsed from a content string has no file on this host."+ raise ValueError(msg)return self.tree.file_location(self.tree_path)+ def make_ref(self) -> "TreeBundleRef":+ """The bundle as a crate names it: its tree's digest and its tree path."""+ return TreeBundleRef(tree_digest=self.digest, tree_path=self.tree_path)+class TreeBundleRef(BaseModel):- """A bundle file named by the key of its tree and its tree path, as a library crate carries it beside its trees."""+ """A bundle named by the digest of its tree and its tree path, as a library crate carries it.++ `tree_path` is None for bundles parsed from content strings, at the root of the tree of the files submitted with them.+ """++ model_config = ConfigDict(frozen=True, extra="forbid")++ tree_digest: str = Field(description="The digest of the bundle's tree, 'sha256:' and 64 lowercase hexadecimal digits")+ tree_path: str | None = Field(description="The bundle's tree path, or None for bundles at the root of the files submitted with them")+++class MethodFileRef(BaseModel):+ """A file of a method tree: the digest of the tree that holds it, and its tree path there."""model_config = ConfigDict(frozen=True, extra="forbid")- tree_key: str- tree_path: str+ tree_digest: str = Field(description="The digest of the tree holding the file, 'sha256:' and 64 lowercase hexadecimal digits")+ tree_path: str = Field(description="The file's tree path, relative to the root of its tree")diff --git a/pipelex/core/method_trees/tree_files.py b/pipelex/core/method_trees/tree_files.pyindex a724bc7a3..25327779d 100644--- a/pipelex/core/method_trees/tree_files.py+++ b/pipelex/core/method_trees/tree_files.py@@ -1,81 +1,41 @@-"""A method tree's files as they travel with a `PipeFunc` call: at their tree paths, in the standard's file entry forms.+"""A method tree's files as a `PipeFunc` call receives them: every file but the bundles, written at their tree paths.-A call to a `PipeFunc` that runs out of this process receives every file of its tree except the `.mthds` files, so the-function imports its sibling modules and reads a file beside its module as it does locally (`wip/extra-files/design.md`,-"Inside a run"). Each file travels as a file entry of `mthds/docs/spec/method-tree.md`, "The File Entry": its text-when its bytes are UTF-8, else `{"base64": "…"}`. A hash entry, which names bytes the receiver already holds, is-resolved by whoever holds the blobs before the files reach the process that writes them.+A call to a `PipeFunc` that runs out of the process that loaded its method receives every file of its tree except the+`.mthds` files, so the function imports its sibling modules and reads a file beside its module as it does locally+(`wip/extra-files/design.md`, "Inside a run"). The call names its tree by digest; the process running it reads the files+through the method file store and writes them out here, or a sandbox client hands them to the sandbox it runs the call+in, which writes them the same way."""from collections.abc import Mappingfrom pathlib import Path-from typing import Protocol, TypeAlias-from mthds.method_tree.file_entry import Base64FileEntry-from mthds.method_tree.models import MethodTreefrom mthds.method_tree.tree_path import tree_path_violationfrom pipelex.core.method_trees.exceptions import TreePythonError-#: A file's bytes as they travel: its text when they are UTF-8, else in Base64.-TreeFileEntry: TypeAlias = str | Base64FileEntry-BUNDLE_SUFFIX = ".mthds"-class CallFileFilter(Protocol):- """Decides, from a file's tree path and bytes, whether it travels with a call."""-- def __call__(self, *, tree_path: str, data: bytes) -> bool: ...---def encode_tree_file(*, data: bytes) -> TreeFileEntry:- """The entry a file's bytes travel as: the text when they are UTF-8, else Base64."""- try:- return data.decode("utf-8")- except UnicodeDecodeError:- return Base64FileEntry.make_from_bytes(data)---def tree_file_bytes(*, entry: TreeFileEntry) -> bytes:- """The bytes a file entry carries."""- if isinstance(entry, Base64FileEntry):- return entry.data- return entry.encode("utf-8")+def is_bundle_file(*, tree_path: str) -> bool:+ """Whether the file at `tree_path` is a bundle, which a `PipeFunc` call never receives."""+ return tree_path.endswith(BUNDLE_SUFFIX)-def read_call_files(*, tree: MethodTree, keeps: CallFileFilter | None = None) -> dict[str, TreeFileEntry]:- """Every file of a tree listed from this host's disk except its `.mthds` files, read as the entries a call receives.-- Args:- tree: A tree listed from a directory of this host.- keeps: Decides, from a file's tree path and bytes, whether it travels; every file travels when None.-- Returns:- The files by tree path, in tree path order.- """- files: dict[str, TreeFileEntry] = {}- for tree_path in tree.tree_paths:- if tree_path.endswith(BUNDLE_SUFFIX):- continue- data = tree.file_location(tree_path).read_bytes()- if keeps is not None and not keeps(tree_path=tree_path, data=data):- continue- files[tree_path] = encode_tree_file(data=data)- return files---def write_call_files(*, files: Mapping[str, TreeFileEntry], destination: Path) -> None:+def write_call_files(*, files: Mapping[str, bytes], destination: Path) -> None:"""Write the files a call received into `destination`, each at its tree path.+ Every key is checked before any file is written.+Raises:TreePythonError: A key is not a tree path, so it could name a place outside `destination`."""- for tree_path, entry in files.items():+ for tree_path in files:violation = tree_path_violation(tree_path)if violation is not None:msg = f"The PipeFunc call received a file at '{tree_path}', which is not a tree path: {violation}."raise TreePythonError(msg)+ for tree_path, data in files.items():target = destination.joinpath(*tree_path.split("/"))target.parent.mkdir(parents=True, exist_ok=True)- target.write_bytes(tree_file_bytes(entry=entry))+ target.write_bytes(data)diff --git a/pipelex/interpreter_hub.py b/pipelex/interpreter_hub.pyindex 4efc29ca6..e1a4b9418 100644--- a/pipelex/interpreter_hub.py+++ b/pipelex/interpreter_hub.py@@ -62,7 +62,6 @@ class InterpreterHub:# runself._pipe_router: PipeRouterProtocol | None = Noneself._pipe_run: PipeRunProtocol | None = None- self._pipe_run_leaves_process = Falseself._pipe_func_executor: PipeFuncExecutorProtocol | None = Noneself._pipe_func_executor_registry: PipeFuncExecutorRegistry | None = Noneself._pipe_func_package_offer_registry: PipeFuncPackageOfferRegistry | None = None@@ -110,14 +109,9 @@ class InterpreterHub:def set_pipe_router(self, pipe_router: "PipeRouterProtocol"):self._pipe_router = pipe_router- def set_pipe_run(self, pipe_run: "PipeRunProtocol", *, leaves_process: bool) -> None:- """Set the pipe run a run uses when its caller injects none, and say whether it runs the job in this process.-- `leaves_process` is true for the pipe run a boot orchestrator's plugin claimed, which hands each job to that- orchestrator, such as Temporal, outside this process, and false for core's own, which runs it here.- """+ def set_pipe_run(self, pipe_run: "PipeRunProtocol") -> None:+ """Set the pipe run a run uses when its caller injects none."""self._pipe_run = pipe_run- self._pipe_run_leaves_process = leaves_processdef set_pipe_func_executor(self, pipe_func_executor: PipeFuncExecutorProtocol):self._pipe_func_executor = pipe_func_executor@@ -186,10 +180,6 @@ class InterpreterHub:raise RuntimeError(msg)return self._pipe_run- def does_pipe_run_leave_process(self) -> bool:- """Whether the pipe run `get_required_pipe_run` returns hands each job to an orchestrator outside this process."""- return self._pipe_run_leaves_process-def get_required_pipe_func_executor(self) -> PipeFuncExecutorProtocol:if self._pipe_func_executor is None:msg = "PipeFuncExecutor is not initialized"@@ -517,10 +507,6 @@ def get_pipe_run() -> "PipeRunProtocol":return get_interpreter_hub().get_required_pipe_run()-def does_pipe_run_leave_process() -> bool:- return get_interpreter_hub().does_pipe_run_leave_process()--def get_pipeline_manager() -> PipelineManagerAbstract:return get_interpreter_hub().get_required_pipeline_manager()diff --git a/pipelex/libraries/bundle_resources.py b/pipelex/libraries/bundle_resources.pyindex b82dd00f1..f5b75d31a 100644--- a/pipelex/libraries/bundle_resources.py+++ b/pipelex/libraries/bundle_resources.py@@ -1,68 +1,44 @@-"""The files submitted with bundles loaded from content strings, checked against their steps and moved with their runs.+"""The files submitted with bundles loaded from content strings, checked against the steps that name them.-`pipelex.core.bundle_resources.bundle_resource` says what a bundle resource is. This module holds what the library-layer does with them: refusing a file no step names and files read at load that are too large, and moving the files-read only when a step runs to the run's storage before the run leaves the process, so the crate a remote orchestrator-receives carries references rather than the bytes.+`pipelex.core.bundle_resources.bundle_resource` says how a submitted file is keyed. This module holds the library+layer's one check on them: every submitted file must be one a step names, so a misspelt key fails loudly rather than+leaving the step without its file."""from collections.abc import Iterable, Mapping-from pathlib import PurePosixPath-from pipelex.core.bundle_resources.bundle_resource import (- MAX_LOAD_STAGE_RESOURCES_BYTES,- BundleResource,- BundleResourceReadStage,- canonical_resource_path_or_none,-)-from pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError, BundleResourcesTooLargeError-from pipelex.libraries.library_crate import LibraryCrate+from pipelex.core.bundle_resources.bundle_resource import canonical_resource_path_or_none, canonical_submitted_files+from pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedErrorfrom 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"-# 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]:- """The bundle files these pipes read, keyed by canonical path, and when each is first read.+def named_bundle_files(*, pipe_blueprints: Iterable[PipeBlueprintUnion]) -> set[str]:+ """The bundle files these pipes name, by canonical path.A path no file submitted with a bundle can have, such as one with a `..` segment, is left out: no submitted file- can answer it, and the step that names it is refused when it is built, as naming a file not supplied with its- bundle. A file read at load by one step and at run by another counts as read at load, which is the stricter way to- carry it.+ can answer it, and the step that names it is refused when its blueprint validates."""- reads: dict[str, BundleResourceReadStage] = {}+ named: set[str] = set()for pipe_blueprint in pipe_blueprints:- for named_path, stage in pipe_blueprint.bundle_resource_reads.items():+ for named_path in pipe_blueprint.named_file_references:canonical_path = canonical_resource_path_or_none(path=named_path)- if canonical_path is None:- continue- known_stage = reads.get(canonical_path)- if known_stage is None or not known_stage.is_read_at_load:- reads[canonical_path] = stage- return reads-+ if canonical_path is not None:+ named.add(canonical_path)+ return named-def check_bundle_resources(*, blueprints: Iterable[PipelexBundleBlueprint], bundle_resources: Mapping[str, BundleResource]) -> None:- """Refuse a file submitted with the bundles that none of their steps names, and files read at load that are too large.- The files the steps read when the method loads, such as HTML templates, travel inline with the method wherever it- runs, so their total is bounded by `MAX_LOAD_STAGE_RESOURCES_BYTES`.+def check_submitted_files(*, blueprints: Iterable[PipelexBundleBlueprint], submitted_files: Mapping[str, bytes]) -> None:+ """Refuse a file submitted with the bundles that none of their steps names, whatever spelling of its path it is keyed by.Raises:+ BundleResourcePathError: a submitted file's path cannot name a file inside the bundle, or two name the same file.BundleResourceNotNamedError: a submitted file is named by no step of the bundles.- BundleResourcesTooLargeError: the files the steps read when the method loads total more than the bound."""- if not bundle_resources:+ if not submitted_files:returnpipe_blueprints = [pipe_blueprint for blueprint in blueprints for pipe_blueprint in (blueprint.pipe or {}).values()]- reads = bundle_resource_reads(pipe_blueprints=pipe_blueprints)- unnamed_paths = sorted(set(bundle_resources) - set(reads))+ submitted_paths = set(canonical_submitted_files(files=submitted_files))+ unnamed_paths = sorted(submitted_paths - named_bundle_files(pipe_blueprints=pipe_blueprints))if unnamed_paths:listed = ", ".join(f"'{path}'" for path in unnamed_paths)msg = (@@ -70,47 +46,3 @@ def check_bundle_resources(*, blueprints: Iterable[PipelexBundleBlueprint], bund"each keyed by the path the step names, such as a PipeDocGen step's 'template_file', relative to the bundle.")raise BundleResourceNotNamedError(msg)- load_stage_paths = sorted(path for path, stage in reads.items() if stage.is_read_at_load and path in bundle_resources)- load_stage_bytes = sum(bundle_resources[path].size for path in load_stage_paths)- if load_stage_bytes > MAX_LOAD_STAGE_RESOURCES_BYTES:- listed = ", ".join(f"'{path}'" for path in load_stage_paths)- msg = (- f"The files the bundle's steps read when the method loads ({listed}) total {load_stage_bytes} bytes, over the "- f"{MAX_LOAD_STAGE_RESOURCES_BYTES // 1024} KiB limit. Such a file, an HTML template, travels inline with the method "- "wherever it runs, so keep it small: move images and fonts out of it, to URLs it references."- )- raise BundleResourcesTooLargeError(msg)---async def relocate_run_resources(*, crate: LibraryCrate, storage_provider: StorageProviderAbstract, storage_scope: str) -> LibraryCrate:- """The crate with every file read only when a step runs stored under the run's scope and carried by reference.-- Called before a run leaves the process (`prepare_job_for_remote_dispatch`), so the job an orchestrator such as- Temporal receives carries a reference to each office template rather than its bytes, and the step reads the bytes- back from the run's storage under the run's read scope, when it prints or when a dry run checks the template. A- 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- run_stage_paths = {path for path, stage in bundle_resource_reads(pipe_blueprints=crate.pipes.values()).items() if not stage.is_read_at_load}- relocated: dict[str, BundleResource] = {}- for path, resource in crate.bundle_resources.items():- if path not in run_stage_paths or not resource.is_inline:- relocated[path] = resource- continue- 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=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/libraries/exceptions.py b/pipelex/libraries/exceptions.pyindex 351c799f2..c3b386f5e 100644--- a/pipelex/libraries/exceptions.py+++ b/pipelex/libraries/exceptions.py@@ -12,12 +12,6 @@ class CrateNormalizationError(LibraryError):_declared_title = "Crate normalization error"-class CrateIntegrityError(LibraryError):- """Raised when a library crate names a method tree it does not carry: the host that assembled it built it wrong."""-- _declared_title = "Crate integrity error"--class LibraryLoadingError(LibraryError):"""Error raised when loading library components fails.diff --git a/pipelex/libraries/library.py b/pipelex/libraries/library.pyindex da6c13fb7..56b8abc40 100644--- a/pipelex/libraries/library.py+++ b/pipelex/libraries/library.py@@ -7,7 +7,6 @@ from pydantic import BaseModel, Field, PrivateAttrfrom pipelex import logfrom pipelex.base_exceptions import PipelexUnexpectedError-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.core.exceptions import PipesAndConceptValidationErrorDatafrom pipelex.core.qualified_ref import QualifiedRef, QualifiedRefErrorfrom pipelex.libraries.concept.concept_library import ConceptLibrary@@ -124,10 +123,6 @@ class Library(BaseModel):pipe_library: PipeLibraryloaded_mthds_paths: list[Path] = Field(default_factory=empty_list_factory_of(Path))dependency_libraries: dict[str, "Library"] = Field(default_factory=dict)- bundle_resources: BundleResources = Field(default_factory=dict)- """The files submitted with the bundles this library loaded from content strings, keyed by canonical path, for- their pipes to read: a `PipeDocGen` step of such a bundle reads its `template_file` here and nowhere else, while a- step of a bundle this host read from a file reads beside it on disk."""_class_registry: ClassRegistry | None = PrivateAttr(default=None)def get_class_registry(self) -> ClassRegistry | None:@@ -136,22 +131,6 @@ class Library(BaseModel):def set_class_registry(self, class_registry: ClassRegistry) -> None:self._class_registry = class_registry- def add_bundle_resources(self, *, bundle_resources: BundleResources) -> None:- """Hold the files submitted with a bundle, for its pipes to read.-- A file the library already holds under the same path is kept when the new one has the same bytes.-- Raises:- LibraryError: a file the library already holds under the same path has different bytes.- """- for path, resource in bundle_resources.items():- held = self.bundle_resources.get(path)- if held is None:- self.bundle_resources[path] = resource- elif held.sha256 != resource.sha256:- msg = f"Two different files were submitted under the same path '{path}' for one library."- raise LibraryError(msg)-def get_domain_library(self) -> DomainLibrary:return self.domain_library@@ -202,7 +181,6 @@ class Library(BaseModel):self.concept_library.teardown()self.domain_library.teardown()self.loaded_mthds_paths = []- self.bundle_resources = {}# Drop this library's dynamically generated structure classes with the library itself.# The registry object would be garbage anyway once the manager forgets the Library, but# a caller holding its own reference must not keep resolving a torn-down library's classes.diff --git a/pipelex/libraries/library_crate.py b/pipelex/libraries/library_crate.pyindex 34d60b496..41e4bd51e 100644--- a/pipelex/libraries/library_crate.py+++ b/pipelex/libraries/library_crate.py@@ -1,21 +1,13 @@import hashlibimport json-from mthds.method_tree.models import MethodTreefrom pydantic import BaseModel, ConfigDict, Field-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.core.concepts.concept_blueprint import ConceptBlueprintfrom pipelex.core.domains.domain_blueprint import DomainBlueprint-from pipelex.core.method_trees.tree_bundle import TreeBundle, TreeBundleRef-from pipelex.core.method_trees.tree_files import TreeFileEntry-from pipelex.libraries.exceptions import CrateIntegrityError+from pipelex.core.method_trees.tree_bundle import TreeBundleReffrom pipelex.mthds_parsing.pipelex_bundle_blueprint import ElaborationMetadata, PipeBlueprintUnion-#: The Python root of the steps whose bundles were parsed from content strings, which have no method tree: the files of-#: the library directories loaded beside them, as a sandbox-hosted deployment captures them.-SUBMITTED_PYTHON_ROOT_KEY = "submitted"-class LibraryCrate(BaseModel):"""Complete library content as qualified blueprints, ready to load into a live Library.@@ -49,67 +41,34 @@ class LibraryCrate(BaseModel):``preliminary_text`` PipeLLM), so a refusal raised while building a helper is reported on the pipeand the field the author wrote. Like ``source_map``, it is excluded from the fingerprint."""- pipe_func_files: dict[str, dict[str, TreeFileEntry]] = Field(default_factory=dict)- """Python root -> the files a `PipeFunc` call of that root receives, by tree path, captured WITHOUT importing.-- A root is the key of a method tree (`tree_key_of`) for a step whose bundle was read from a tree, holding every file- of that tree except its `.mthds` files, or `SUBMITTED_PYTHON_ROOT_KEY` for the steps of bundles parsed from content- strings, holding the files of the library directories loaded beside them, keyed by their path there. Each file is a- file entry of the standard: its text, or `{"base64": ...}`. A call carries its own root's files to the sandbox that- imports and runs the function (`PipeFuncExecutionRequest.files`). Populated only in sandbox-hosted load mode;- empty for local/direct loads, which import from the disk. Deliberately EXCLUDED from the fingerprint (see- compute_fingerprint_from_content): the fingerprint represents library structure for dedupe, and folding files into- it would break the structural-idempotency contract in load_from_crate.- """-- bundle_resources: BundleResources = Field(default_factory=dict)- """canonical bundle-relative path -> a file submitted with a bundle loaded from content strings.-- Carries the files a content-string bundle's steps read, such as a PipeDocGen `template_file`, wherever the- crate is loaded again, a Temporal workflow included: a file read when the method loads travels inline, and one- read only when its step runs may travel by reference to the run's storage (see `relocate_run_resources`).- Empty for a library loaded from directories, whose steps read beside their files on disk. Like- `pipe_func_files`, it is transport-only: EXCLUDED from the fingerprint and from the normalized crate.- """-- method_trees: dict[str, str] = Field(default_factory=dict)- """tree key (`tree_key_of`) -> a method tree the host that assembled the crate listed its bundles' files in, as- the JSON of its listing, a `MethodTree`, so the crate stays plain text wherever it travels, a Temporal payload- included.+ tree_bundles: dict[str, TreeBundleRef] = Field(default_factory=dict)+ """pipe_ref -> the method tree the pipe's bundle belongs to, named by its digest, and the bundle's tree path there.A pipe reads a file its bundle names, such as a PipeDocGen `template_file`, only by resolving it in its bundle's- tree (`tree_bundles`), never through `source_map`: a source is a label, which a caller sends with content strings- and a bundle's own text can write, so a pipe loaded from content strings has no tree and reads only the files- submitted with it (`bundle_resources`). Transport-only, like `pipe_func_files`: EXCLUDED from the fingerprint and- from the normalized crate, so a host path never reaches a caller through `/resolve`.+ tree, never through `source_map`: a source is a label, which a caller sends with content strings and a bundle's own+ text can write. The crate carries no tree's files nor listing, and no path of the host that assembled it: a pipe+ built from the crate resolves a reference lexically and reads nothing, and the process that uses a file, a+ `PipeFunc` call or a `PipeDocGen` print, reads it through the method file store by the tree's digest. Bundles parsed+ from content strings name the tree of the files submitted with them, with no tree path, and none when no file was+ submitted. Transport-only: EXCLUDED from the fingerprint and from the normalized crate."""- tree_bundles: dict[str, TreeBundleRef] = Field(default_factory=dict)- """pipe_ref -> the member of `method_trees` the pipe's bundle was read as, for a pipe whose bundle the host that- assembled the crate read from its disk. Transport-only, like `method_trees`."""-- def tree_bundles_by_pipe_ref(self) -> dict[str, TreeBundle]:- """Each pipe whose bundle was read from a host's disk, with the member of its method tree the bundle was read as.+ def tree_digests(self) -> list[str]:+ """The digest of every tree the crate's pipes belong to, each once, sorted."""+ return sorted({tree_bundle_ref.tree_digest for tree_bundle_ref in self.tree_bundles.values()})- Each tree is read back once, however many pipes its bundles define. A pipe of a bundle parsed from a string has- no entry.+ def concepts_only(self) -> "LibraryCrate":+ """The crate's concepts and domains, with none of its pipes: what a process typing the run's data loads.- Raises:- CrateIntegrityError: A pipe names a tree the crate does not carry.+ Its fingerprint is its own, computed from its concepts, so two runs whose methods declare the same concepts share+ it whatever their pipes."""- trees: dict[str, MethodTree] = {}- tree_bundles: dict[str, TreeBundle] = {}- for pipe_ref, tree_bundle_ref in self.tree_bundles.items():- tree = trees.get(tree_bundle_ref.tree_key)- if tree is None:- tree_json = self.method_trees.get(tree_bundle_ref.tree_key)- if tree_json is None:- msg = f"The crate names the method tree '{tree_bundle_ref.tree_key}' for pipe '{pipe_ref}' but carries no such tree."- raise CrateIntegrityError(msg)- tree = MethodTree.model_validate_json(tree_json)- trees[tree_bundle_ref.tree_key] = tree- tree_bundles[pipe_ref] = TreeBundle(tree=tree, tree_path=tree_bundle_ref.tree_path)- return tree_bundles+ return LibraryCrate(+ mthds_version=self.mthds_version,+ concepts=dict(self.concepts),+ domains=dict(self.domains),+ fingerprint=self.compute_fingerprint_from_content(concepts=self.concepts, pipes={}),+ )fingerprint: str = """""SHA-256 hex digest of the serialized concepts + pipes content (source is intentionally excluded)."""diff --git a/pipelex/libraries/library_crate_factory.py b/pipelex/libraries/library_crate_factory.pyindex d895b9486..ba497db35 100644--- a/pipelex/libraries/library_crate_factory.py+++ b/pipelex/libraries/library_crate_factory.py@@ -1,10 +1,7 @@from typing import TYPE_CHECKING, NamedTuple-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.domains.domain_blueprint import DomainBlueprint-from pipelex.core.method_trees.tree_bundle import TreeBundleRef-from pipelex.core.method_trees.tree_files import TreeFileEntryfrom pipelex.libraries.collision_messages import duplicate_ref_msgfrom pipelex.libraries.concept.exceptions import ConceptLibraryErrorfrom pipelex.libraries.contract_match import contracts_match@@ -15,9 +12,8 @@ from pipelex.mthds_parsing.pipelex_bundle_blueprint import ElaborationMetadata,from pipelex.pipe_machinery.pipe_factory import PipeFactoryif TYPE_CHECKING:- from mthds.method_tree.models import MethodTree-from pipelex.core.concepts.concept_blueprint import ConceptBlueprint+ from pipelex.core.method_trees.tree_bundle import TreeBundleRefclass PipeDeclaration(NamedTuple):@@ -38,9 +34,6 @@ class LibraryCrateFactory:def make_from_blueprints(cls,blueprints: list[PipelexBundleBlueprint],- *,- pipe_func_files: dict[str, dict[str, TreeFileEntry]] | None = None,- bundle_resources: BundleResources | None = None,) -> LibraryCrate:"""Build a LibraryCrate from parsed bundle blueprints.@@ -54,12 +47,7 @@ class LibraryCrateFactory:7. Compute SHA-256 fingerprintArgs:- blueprints: List of parsed MTHDS bundle blueprints- pipe_func_files: Optional Python root -> the files a PipeFunc call of that root receives, captured (without- importing) in sandbox-hosted load mode. Attached verbatim to the crate; intentionally NOT folded- into the fingerprint (the fingerprint represents library structure for dedupe).- bundle_resources: Optional canonical path -> file submitted with a bundle loaded from content strings.- Attached verbatim to the crate and, like ``pipe_func_files``, NOT folded into the fingerprint.+ blueprints: List of parsed MTHDS bundle blueprints, each naming the method tree it belongs to, if anyReturns:A LibraryCrate with all content merged and fingerprinted@@ -68,20 +56,15 @@ class LibraryCrateFactory:pipes: dict[str, PipeBlueprintUnion] = {}domains: dict[str, DomainBlueprint] = {}source_map: dict[str, str] = {}- method_trees: dict[str, MethodTree] = {}tree_bundles: dict[str, TreeBundleRef] = {}elaboration_metadata: dict[str, ElaborationMetadata] = {}for blueprint in blueprints:domain_code = blueprint.domainsource = blueprint.source- # The member of its method tree the bundle was read as, which a step reading a file the bundle names resolves- # it in; None for a bundle parsed from a string.- tree_bundle_ref: TreeBundleRef | None = None- if blueprint.tree_bundle is not None:- tree_key = blueprint.tree_bundle.tree_key- method_trees.setdefault(tree_key, blueprint.tree_bundle.tree)- tree_bundle_ref = TreeBundleRef(tree_key=tree_key, tree_path=blueprint.tree_bundle.tree_path)+ # The method tree the bundle belongs to, by digest, which a step reading a file the bundle names resolves it+ # in; None for a bundle parsed from a string with no file submitted beside it.+ tree_bundle_ref = blueprint.tree_bundle.make_ref() if blueprint.tree_bundle is not None else None# Domain metadata: order-independent, omission-quiet merge (see merge_domain_metadata_field).if domain_code not in domains:@@ -188,12 +171,8 @@ class LibraryCrateFactory:pipes=pipes,domains=domains,source_map=source_map,- # Only the trees a winning declaration was read from: a tree whose every pipe lost a collision travels nowhere.- method_trees={tree_key: method_trees[tree_key].model_dump_json() for tree_key in sorted({ref.tree_key for ref in tree_bundles.values()})},tree_bundles=tree_bundles,elaboration_metadata=elaboration_metadata,- pipe_func_files={root_key: dict(files) for root_key, files in (pipe_func_files or {}).items()},- bundle_resources=dict(bundle_resources) if bundle_resources else {},fingerprint=fingerprint,)diff --git a/pipelex/libraries/library_manager.py b/pipelex/libraries/library_manager.pyindex 05c7d84b7..c73a50dc6 100644--- a/pipelex/libraries/library_manager.py+++ b/pipelex/libraries/library_manager.py@@ -1,5 +1,5 @@import uuid-from collections.abc import Generator+from collections.abc import Generator, Mappingfrom contextlib import ExitStack, contextmanagerfrom graphlib import CycleError, TopologicalSorterfrom pathlib import Path@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any, ForwardRef, Literal, get_args, get_originfrom kajson.class_registry import ClassRegistryfrom kajson.kajson_manager import KajsonManagerfrom mthds.method_tree.models import MethodTree, TreeLimits+from mthds.method_tree.tree_path import path_collisions, tree_path_violationfrom mthds.package.dependency_resolver import ResolvedDependency, determine_exported_pipes, resolve_all_dependenciesfrom mthds.package.discovery import find_package_manifestfrom mthds.package.exceptions import DependencyResolveError, ManifestError@@ -19,7 +20,8 @@ from pipelex import logfrom pipelex.base_exceptions import PipelexError, SecurityError, error_domain_is_input, iter_cause_chainfrom pipelex.cogt.exceptions import ModelChoiceNotFoundErrorfrom pipelex.config import is_pipe_func_sandbox_hosted-from pipelex.core.bundle_resources.bundle_resource import BundleResources+from pipelex.core.bundle_resources.bundle_resource import canonical_submitted_files+from pipelex.core.bundle_resources.exceptions import BundleResourcePathErrorfrom pipelex.core.concepts.concept_blueprint import ConceptBlueprintfrom pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.concepts.helpers import make_qualified_structure_class_name@@ -27,9 +29,9 @@ from pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.domains.domain_blueprint import DomainBlueprintfrom pipelex.core.domains.domain_factory import DomainFactoryfrom pipelex.core.exceptions import PipelexBundleBlueprintValidationErrorData, PipesAndConceptValidationErrorData-from pipelex.core.method_trees.building_bundle import building_pipe_of-from pipelex.core.method_trees.tree_bundle import tree_key_of-from pipelex.core.method_trees.tree_files import TreeFileEntry, encode_tree_file+from pipelex.core.method_trees.building_bundle import BuildingBundle, building_pipe_of+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES, HeldFile+from pipelex.core.method_trees.tree_bundle import TreeBundle, TreeBundleReffrom pipelex.core.method_trees.tree_python import TREE_PYTHON_HOLD, sharing_module_name_checksfrom pipelex.core.pipes.exceptions import PipeLoadRefusalError, PipeOperatorModelChoiceError, PipeValidationErrorfrom pipelex.core.qualified_ref import QualifiedRef@@ -45,7 +47,7 @@ from pipelex.libraries.exceptions import (LibraryLoadingError,)from pipelex.libraries.library import Library-from pipelex.libraries.library_crate import SUBMITTED_PYTHON_ROOT_KEY, LibraryCrate+from pipelex.libraries.library_crate import LibraryCratefrom pipelex.libraries.library_crate_factory import LibraryCrateFactoryfrom pipelex.libraries.library_factory import LibraryFactoryfrom pipelex.libraries.library_manager_abstract import LibraryManagerAbstract@@ -56,14 +58,14 @@ from pipelex.libraries.method_trees import (library_bundle_files_of,list_library_dir_trees,list_package_method_tree,+ listing_identity,local_tree_limits,- submitted_python_files,+ submitted_tree_files,tree_bundle_of_lone_file,tree_bundles_of,tree_python_sources,)from pipelex.libraries.pipe.exceptions import PipeLibraryError-from pipelex.libraries.pipe_func_call_files import holds_pipe_func_step, travels_with_call, tree_pipe_func_filesfrom pipelex.libraries.visibility_utils import check_visibility_for_blueprints, make_visibility_checkerfrom pipelex.methods.exceptions import MethodDependencyFetchError, MethodFetchDisabledErrorfrom pipelex.methods.fetch_on_miss import find_vendored_method, resolve_address_based_method@@ -88,11 +90,10 @@ from pipelex.tools.misc.semver import SemVerError, parse_constraint, parse_versifrom pipelex.validation_error_types import PipeValidationErrorTypeif TYPE_CHECKING:- from collections.abc import Iterable, Mapping+ from collections.abc import Iterablefrom pipelex.core.concepts.concept import Conceptfrom pipelex.core.domains.domain import Domain- from pipelex.core.method_trees.tree_bundle import TreeBundleMTHDS_METHODS_DIRNAME = ".mthds/methods"@@ -334,11 +335,11 @@ def _python_sources_by_tree(*, library_trees: list[LibraryTree], bundle_files: lThe library directories' trees come first, nested ones included, then the tree of each bundle file named alone; atree two of them list is read once."""- trees: dict[str, tuple[MethodTree, Path | None]] = {}+ trees: dict[tuple[str, str, bool], tuple[MethodTree, Path | None]] = {}for library_tree in library_trees:- trees.setdefault(tree_key_of(tree=library_tree.tree), (library_tree.tree, library_tree.library_dir))+ trees.setdefault(listing_identity(tree=library_tree.tree), (library_tree.tree, library_tree.library_dir))for bundle_file in bundle_files:- trees.setdefault(bundle_file.tree_bundle.tree_key, (bundle_file.tree_bundle.tree, None))+ trees.setdefault(listing_identity(tree=bundle_file.tree_bundle.tree), (bundle_file.tree_bundle.tree, None))sources_by_tree: dict[Path, dict[str, str]] = {}for tree, library_dir in trees.values():if tree.directory is None:@@ -355,11 +356,16 @@ class LibraryManager(LibraryManagerAbstract):self._blueprints: dict[str, list[PipelexBundleBlueprint]] = {} # library_id -> accumulated blueprintsself._crate_cache: dict[str, LibraryCrate] = {} # library_id -> cached crate from get_crate()self._loaded_fingerprints: dict[str, set[str]] = {} # library_id -> set of loaded crate fingerprints- # library_id -> Python root -> {tree path: file entry}. The files a sandbox-hosted PipeFunc call receives,- # captured (without importing) from the library directories in sandbox-hosted load mode, or held from a- # transported crate, threaded into get_crate() so the crate carries them to a sandbox, and read by a- # PipeFunc's validation in place of a disk that is another host's. Empty in local/direct mode.- self._pipe_func_files: dict[str, dict[str, dict[str, TreeFileEntry]]] = {}+ # library_id -> path -> file. The files submitted beside the bundles a library parses from content strings: the+ # files of its library directories whose own tree holds no bundle, and the files a caller submitted with the+ # contents. Those bundles sit at the root of the tree they make, which the library holds in the local method+ # file store, so their steps resolve a file they name in it and a run reads it by the tree's digest.+ self._submitted_files: dict[str, dict[str, HeldFile]] = {}+ # library_id -> the tree of its submitted files, as last held; dropped when a file joins.+ self._submitted_trees: dict[str, MethodTree] = {}+ # library_id -> the files its library directories submit, joined only when a bundle parsed from a content+ # string loads: a library that loads none never has two directories' files judged as one tree.+ self._library_dir_submissions: dict[str, list[dict[str, HeldFile]]] = {}############################################################# Manager lifecycle@@ -395,9 +401,13 @@ class LibraryManager(LibraryManagerAbstract):self._blueprints.pop(library_id, None)self._crate_cache.pop(library_id, None)self._loaded_fingerprints.pop(library_id, None)- self._pipe_func_files.pop(library_id, None)- # The library's runs are over: its hold on a method tree's Python, if a PipeFunc step took one, is released.+ self._submitted_files.pop(library_id, None)+ self._submitted_trees.pop(library_id, None)+ self._library_dir_submissions.pop(library_id, None)+ # The library's runs are over: its hold on a method tree's Python, if a PipeFunc step took one, is released,+ # and so are the trees it held for its runs to read.TREE_PYTHON_HOLD.release(holder=library_id)+ LOCAL_METHOD_FILES.release(holder=library_id)return True@override@@ -419,8 +429,11 @@ class LibraryManager(LibraryManagerAbstract):self._blueprints = {}self._crate_cache = {}self._loaded_fingerprints = {}- self._pipe_func_files = {}+ self._submitted_files = {}+ self._submitted_trees = {}+ self._library_dir_submissions = {}TREE_PYTHON_HOLD.release_all()+ LOCAL_METHOD_FILES.release_all()with ExitStack() as teardown_stack:for library in libraries:teardown_stack.callback(library.teardown)@@ -566,29 +579,101 @@ class LibraryManager(LibraryManagerAbstract):accumulated = self._blueprints.get(library_id)if not accumulated:return None- library = self._libraries.get(library_id)- # The files a sandbox-hosted PipeFunc call receives were read as the library loaded: building the crate reads no- # file, so it builds after the directories the library was read from are gone.- crate = LibraryCrateFactory.make_from_blueprints(- blueprints=accumulated,- pipe_func_files=self._pipe_func_files.get(library_id),- bundle_resources=library.bundle_resources if library is not None else None,- )+ # The crate names each tree by its digest and reads no file, so it builds after the directories the library was+ # read from are gone.+ crate = LibraryCrateFactory.make_from_blueprints(blueprints=accumulated)self._crate_cache[library_id] = cratereturn crate@override- def get_pipe_func_files(self, *, library_id: str, root_key: str) -> dict[str, TreeFileEntry] | None:- return self._pipe_func_files.get(library_id, {}).get(root_key)+ def add_submitted_files(self, *, library_id: str, submitted_files: "Mapping[str, bytes]") -> None:+ if not submitted_files:+ return+ if library_id not in self._libraries:+ msg = f"Trying to add submitted files to a library that does not exist: '{library_id}'"+ raise LibraryError(msg)+ canonical_files = canonical_submitted_files(files=submitted_files)+ self._join_submitted_files(+ library_id=library_id,+ files={path: HeldFile.of_bytes(data=data) for path, data in canonical_files.items()},+ )- @override- def add_bundle_resources(self, *, library_id: str, bundle_resources: BundleResources) -> None:- if not bundle_resources:+ def _join_submitted_files(self, *, library_id: str, files: "Mapping[str, HeldFile]") -> None:+ """Join files to the ones submitted beside the library's content strings, keyed by their path from the root.++ A file already joined under the same path is kept when the new one has the same bytes. Nothing is joined when+ any file is refused, so a refusal leaves the files already joined as they were.++ Raises:+ BundleResourcePathError: A path is not a tree path, collides with another once case-folded or as a+ directory, or names a file already joined with different bytes, so the files could not make one tree.+ The message names the files by their tree paths alone, never by a host path.+ """+ if not files:return- self.get_library(library_id=library_id).add_bundle_resources(bundle_resources=bundle_resources)- # The cached crate was built without them.+ self._submitted_files[library_id] = self._joined_submitted_files(held=self._submitted_files.get(library_id, {}), files=files)+ self._submitted_trees.pop(library_id, None)+ # The cached crate was built before them.self._crate_cache.pop(library_id, None)+ @staticmethod+ def _joined_submitted_files(*, held: "Mapping[str, HeldFile]", files: "Mapping[str, HeldFile]") -> dict[str, HeldFile]:+ """`held` with `files` joined to it, as a new mapping, `held` itself left untouched.++ Raises:+ BundleResourcePathError: The files could not make one tree with the ones held (`_join_submitted_files`).+ """+ joined = dict(held)+ for path, held_file in files.items():+ violation = tree_path_violation(path)+ if violation is not None:+ msg = f"The file '{path}' submitted beside the method cannot be a file of its tree: {violation}."+ raise BundleResourcePathError(msg)+ already_held = joined.get(path)+ if already_held is not None and already_held.sha256 != held_file.sha256:+ msg = (+ f"Two different files were submitted under the same path '{path}' for one library. The files submitted "+ "beside a method's content strings, from its library directories and with its request, make one tree, "+ "so each path names one file: give them distinct paths."+ )+ raise BundleResourcePathError(msg)+ joined[path] = held_file+ collisions = path_collisions(joined)+ if collisions:+ listed = ", ".join(f"'{collision}'" for collision in collisions)+ msg = f"The files submitted beside the method cannot make one tree: their paths collide at {listed}."+ raise BundleResourcePathError(msg)+ return joined++ def _submitted_tree(self, *, library_id: str) -> MethodTree | None:+ """The tree of the files submitted beside the library's content strings, held for its runs, or None when there are none.++ The files the library's directories submitted are joined all together or not at all: a refusal leaves every one+ of them pending, so the library's next run is refused again rather than run without them.++ Raises:+ BundleResourcePathError: The files cannot make one tree, such as two of them, from two library directories+ or from one and the request, sharing a path with different bytes.+ """+ pending = self._library_dir_submissions.get(library_id)+ if pending:+ joined: Mapping[str, HeldFile] = self._submitted_files.get(library_id, {})+ for library_dir_files in pending:+ joined = self._joined_submitted_files(held=joined, files=library_dir_files)+ self._submitted_files[library_id] = dict(joined)+ self._submitted_trees.pop(library_id, None)+ self._crate_cache.pop(library_id, None)+ del self._library_dir_submissions[library_id]+ tree = self._submitted_trees.get(library_id)+ if tree is not None:+ return tree+ files = self._submitted_files.get(library_id)+ if not files:+ return None+ tree = LOCAL_METHOD_FILES.hold_files(holder=library_id, files=files)+ self._submitted_trees[library_id] = tree+ return tree+############################################################# Private methods############################################################@@ -642,6 +727,15 @@ class LibraryManager(LibraryManagerAbstract):names_host_paths=True,)+ # A library directory whose own tree holds no bundle, such as the directory a server writes a request's+ # files into, submits its files beside the bundles parsed from content strings, which sit at the root of+ # the tree they make: nothing is read, each file being held by the hash its listing recorded.+ for library_tree in library_trees:+ library_dir_files = submitted_tree_files(library_tree=library_tree)+ if library_dir_files:+ self._library_dir_submissions.setdefault(library_id, []).append(library_dir_files)+ self._crate_cache.pop(library_id, None)+# Each file once, as the member of the first tree that holds it.seen_locations: set[Path] = set()bundle_files: list[LibraryBundleFile] = []@@ -664,10 +758,6 @@ class LibraryManager(LibraryManagerAbstract):ensure_no_structured_content_in_library_sources(sources_by_dir=_python_sources_by_tree(library_trees=library_trees, bundle_files=all_bundle_files),)- # The files a step of a tree's bundle calls with are captured once its blueprints load, per tree;- # those of a library directory whose own tree holds no bundle are captured here, to travel with each- # call of a PipeFunc parsed from a content string, whose import paths start at that directory.- self._capture_submitted_python(library_id=library_id, library_trees=library_trees)else:for library_dir in all_dirs:# Only import files that contain StructuredContent subclasses (uses AST pre-check), so@@ -705,8 +795,15 @@ class LibraryManager(LibraryManagerAbstract):return fingerprint in self._loaded_fingerprints.get(library_id, set())@override- def load_from_crate(self, *, library_id: str, crate: LibraryCrate, is_crate_prevalidated: bool = False) -> list[PipeAbstract]:- """Load a LibraryCrate into a live Library.+ def load_from_crate(+ self,+ *,+ library_id: str,+ crate: LibraryCrate,+ is_crate_prevalidated: bool = False,+ written_pipe_trees: "Mapping[str, MethodTree] | None" = None,+ ) -> list[PipeAbstract]:+ """Load a LibraryCrate into a live Library, reading no file but, for its validation, files of trees this process holds.Fingerprint idempotency: if a crate with the same fingerprint was already loadedinto this library_id, the load is skipped and an empty list is returned.@@ -735,14 +832,44 @@ class LibraryManager(LibraryManagerAbstract):to one another, the concept-cycle check, pipe construction with each pipe's static validation,and source tracking. Leave it False for any crate whose library was not validated by thispipelex version.+ written_pipe_trees: The trees this process wrote out for a step to run in, by that step's pipe ref, such as+ the tree of a `PipeFunc` call written for its function to import. That step is built as a member of the+ written tree, which holds none of its tree's bundles; no other step is, a sibling of the same tree+ included.++ Every other step is built as a member of its tree when the load validates the crate and a library of this+ process holds the tree under the digest the crate names, so its checks read the files they read where the+ crate was assembled, such as a `PipeDocGen` step's HTML template file, and reach the same verdict. Otherwise+ it names its tree by digest alone, resolves a file it names lexically, and reads nothing: a load that skips+ validation, such as one inside a workflow, never reads a file.Returns:List of all pipes that were loaded, or empty list if already loaded"""- return self._load_crate(library_id=library_id, crate=crate, is_crate_prevalidated=is_crate_prevalidated, refuses_unresolved_structures=False)+ held_trees: dict[str, MethodTree] = {}+ if not is_crate_prevalidated:+ for tree_digest in crate.tree_digests():+ held_tree = LOCAL_METHOD_FILES.held_tree(tree_digest=tree_digest)+ if held_tree is not None:+ held_trees[tree_digest] = held_tree+ return self._load_crate(+ library_id=library_id,+ crate=crate,+ is_crate_prevalidated=is_crate_prevalidated,+ refuses_unresolved_structures=False,+ live_trees=held_trees,+ written_pipe_trees=written_pipe_trees or {},+ )def _load_crate(- self, *, library_id: str, crate: LibraryCrate, is_crate_prevalidated: bool, refuses_unresolved_structures: bool+ self,+ *,+ library_id: str,+ crate: LibraryCrate,+ is_crate_prevalidated: bool,+ refuses_unresolved_structures: bool,+ live_trees: "Mapping[str, MethodTree]",+ written_pipe_trees: "Mapping[str, MethodTree] | None" = None,) -> list[PipeAbstract]:"""The load behind load_from_crate and load_from_blueprints.@@ -753,31 +880,23 @@ class LibraryManager(LibraryManagerAbstract):refuses_unresolved_structures: Whether a structure class still incomplete once the concepts are loadedrefuses the load. True only where the load resolved the bundle's dependencies first, so that areference which resolves to nothing is the bundle's own fault.+ live_trees: The trees this process holds, by digest: a pipe whose bundle's tree is one of them is built as a+ member of it, and every other as a member of a tree the crate names by digest alone.+ written_pipe_trees: As load_from_crate describes it: a step built in a tree this process wrote out for it,+ which wins over its tree in `live_trees`."""# Bind the target library as current for the whole load: PipeFactory and the concept# factories resolve concepts and the class registry through the ambient current library,# so a load into a non-current library must not read the caller's binding.with scoped_current_library(library_id=library_id), sharing_module_name_checks():# Cache the crate for a DIRECT crate-load (the transported-crate path used by the Temporal- # workflow, which never populates _blueprints). This lets get_crate() hand the crate — with- # its pipe_func_files — to the sandbox executor. The blueprint-derived path (load_libraries ->- # load_from_blueprints) leaves _blueprints populated and rebuilds from it instead, so it must- # NOT be shadowed by a cached crate here.+ # workflow, which never populates _blueprints). This lets get_crate() hand the crate to the+ # sandbox executor. The blueprint-derived path (load_libraries -> load_from_blueprints) leaves+ # _blueprints populated and rebuilds from it instead, so it must NOT be shadowed by a cached+ # crate here.if library_id not in self._blueprints:self._crate_cache[library_id] = crate- # The files a transported crate carries for its content-string bundles, held before the pipes are built,- # since a pipe reading one, such as a PipeDocGen step with an HTML template file, reads it as it is built.- if crate.bundle_resources:- self.get_library(library_id=library_id).add_bundle_resources(bundle_resources=crate.bundle_resources)-- # The files a transported crate carries for its PipeFunc calls, held before the pipes are validated: a- # PipeFunc's validation reads its module from them, the trees' directories being the host's that listed them.- if crate.pipe_func_files:- held_files = self._pipe_func_files.setdefault(library_id, {})- for root_key, root_files in crate.pipe_func_files.items():- held_files.setdefault(root_key, dict(root_files))-# Fingerprint idempotency: skip if this crate was already loaded into this libraryfingerprint = crate.fingerprintloaded_set = self._loaded_fingerprints.setdefault(library_id, set())@@ -832,9 +951,6 @@ class LibraryManager(LibraryManagerAbstract):# signature change across PipeFactory and belongs with the concept-side work.qualified_pipes = qualify_crate(crate).pipes- # The member of its method tree each pipe's bundle was read as, each tree read back once- tree_bundles_by_pipe_ref = crate.tree_bundles_by_pipe_ref()-# Load pipes with domain-filtered concept codesall_pipes: list[PipeAbstract] = []for pipe_ref, pipe_blueprint in qualified_pipes.items():@@ -848,13 +964,19 @@ class LibraryManager(LibraryManagerAbstract):concept_codes_for_domain = domain_concept_codes.get(domain_code, [])source = crate.source_map.get(pipe_ref)- # A pipe that reads a file its bundle names (a PipeDocGen `template_file`) resolves it in the method tree- # the host that assembled the crate listed its bundle in, and in nothing else: the pipe's `source` is- # cleared, so neither a caller's label (`source_map`) nor a `source` the bundle's text wrote on the pipe- # can point the read at a directory on this host. A bundle parsed from a string has no tree.+ # A pipe that reads a file its bundle names (a PipeDocGen `template_file`) resolves it in its bundle's+ # method tree, and in nothing else: the pipe's `source` is cleared, so neither a caller's label+ # (`source_map`) nor a `source` the bundle's text wrote on the pipe can point the read at a directory on+ # this host.pipe_blueprint = pipe_blueprint.model_copy(update={"source": None})with (- building_pipe_of(tree_bundle=tree_bundles_by_pipe_ref.get(pipe_ref)),+ building_pipe_of(+ tree_bundle=_building_bundle_of(+ tree_bundle_ref=crate.tree_bundles.get(pipe_ref),+ live_trees=live_trees,+ written_tree=(written_pipe_trees or {}).get(pipe_ref),+ )+ ),_locating_pipe_build_refusals(pipe_code=pipe_code, domain_code=domain_code, source=source, elaboration=crate.elaboration_metadata.get(pipe_ref)),@@ -921,10 +1043,17 @@ class LibraryManager(LibraryManagerAbstract):trees=[blueprint.tree_bundle.tree for blueprint in blueprints if blueprint.tree_bundle is not None],names_host_paths=True,)- if is_pipe_func_sandbox_hosted():- # Each call of a PipeFunc read from a method tree receives the tree's files in the sandbox: they are read- # now, while the directory the tree was listed from is certain to exist, and the crate carries them.- self._capture_tree_pipe_func_files(library_id=library_id, blueprints=blueprints)+ # Bundles parsed from content strings sit at the root of the tree of the files submitted beside them, when+ # there are any, so a step resolves a file it names there.+ content_blueprints = [blueprint for blueprint in blueprints if blueprint.tree_bundle is None and blueprint.host_bundle_file is None]+ if content_blueprints:+ submitted_tree = self._submitted_tree(library_id=library_id)+ if submitted_tree is not None:+ for blueprint in content_blueprints:+ blueprint.place_in_tree(tree_bundle=TreeBundle(tree=submitted_tree, tree_path=None))+ # The library holds every tree its bundles were read from for its runs, which read a file of one, a+ # PipeFunc call's or a PipeDocGen template, by the tree's digest through the method file store.+ live_trees = self._hold_trees_of(library_id=library_id, blueprints=blueprints)# Accumulate blueprints for later crate construction via get_crate()self._blueprints.setdefault(library_id, []).extend(blueprints)@@ -953,7 +1082,9 @@ class LibraryManager(LibraryManagerAbstract):# Load from crate (domains, concepts, pipes, validation). The dependencies were loaded above, so a# structure reference that still resolves to nothing is the bundle's own, and refuses the load.- all_pipes = self._load_crate(library_id=library_id, crate=crate, is_crate_prevalidated=False, refuses_unresolved_structures=True)+ all_pipes = self._load_crate(+ library_id=library_id, crate=crate, is_crate_prevalidated=False, refuses_unresolved_structures=True, live_trees=live_trees+ )# Also record the aggregate crate fingerprint: get_crate() rebuilds one crate from# ALL accumulated blueprints, so once the library holds more than one batch its@@ -1115,54 +1246,27 @@ class LibraryManager(LibraryManagerAbstract):# Private helper methods############################################################- def _capture_submitted_python(self, *, library_id: str, library_trees: list[LibraryTree]) -> None:- """Capture the files the library directories submit beside bundles parsed from content strings, as one Python root.+ @staticmethod+ def _hold_trees_of(*, library_id: str, blueprints: "Iterable[PipelexBundleBlueprint]") -> dict[str, MethodTree]:+ """Hold the trees these bundles were placed in, for the library's runs to read, and return them by digest.- Only a directory whose own tree holds no bundle submits files (`submitted_python_files`), and the sandbox writes- them all at their paths under one root, so two such directories holding different files at one path would- clobber each other and run the wrong function: the load fails loud instead.-- Raises:- LibraryError: Two directories submit different files at one path.+ A tree listed from this host's disk is served from it, each file checked against the hash its listing recorded;+ the tree of submitted files was held when it was assembled. Two trees with one digest hold the same files, so the+ first placed is the one returned, and each tree is held once, however many of its bundles load: a holder keeps+ the first sources it held a tree with."""- submitted = dict(self._pipe_func_files.get(library_id, {}).get(SUBMITTED_PYTHON_ROOT_KEY, {}))- for library_tree in library_trees:- for relpath, data in submitted_python_files(library_tree=library_tree).items():- if not travels_with_call(tree_path=relpath, data=data):- # The refusal accepted it as a copy of the method's own concepts, and the sandbox generates its own- # from those concepts, qualified. Shipping this one too would give the sandbox two `structures`- # modules, and a PipeFunc's import would reach either.- continue- entry = encode_tree_file(data=data)- if relpath in submitted and submitted[relpath] != entry:- msg = (- f"Duplicate PipeFunc file path '{relpath}' across library dirs while loading library '{library_id}'. "- "A sandbox receives the files submitted beside a method's bundles at their paths, so two dirs sharing "- "a path would clobber each other — give them distinct relative paths."- )- raise LibraryError(msg)- submitted[relpath] = entry- if submitted:- self._pipe_func_files.setdefault(library_id, {})[SUBMITTED_PYTHON_ROOT_KEY] = submitted-- def _capture_tree_pipe_func_files(self, *, library_id: str, blueprints: list[PipelexBundleBlueprint]) -> None:- """Capture, from this host's disk, the files of each method tree holding a `PipeFunc` step of these bundles.-- A tree already captured for the library is not read again, and a tree holding no `PipeFunc` step is never read.- """- held_files = self._pipe_func_files.get(library_id, {})- captured: dict[str, dict[str, TreeFileEntry]] = {}+ live_trees: dict[str, MethodTree] = {}for blueprint in blueprints:tree_bundle = blueprint.tree_bundle- if tree_bundle is None or tree_bundle.tree.directory is None or not holds_pipe_func_step(blueprint=blueprint):+ if tree_bundle is None:continue- tree_key = tree_bundle.tree_key- if tree_key in held_files or tree_key in captured:+ tree = tree_bundle.tree+ if tree.digest in live_trees:continue- captured[tree_key] = tree_pipe_func_files(tree=tree_bundle.tree)- if captured:- self._pipe_func_files.setdefault(library_id, {}).update(captured)- self._crate_cache.pop(library_id, None)+ live_trees[tree.digest] = tree+ if tree.directory is not None and not LOCAL_METHOD_FILES.holds(holder=library_id, tree_digest=tree.digest):+ LOCAL_METHOD_FILES.hold_tree(holder=library_id, tree=tree)+ return live_treesdef _load_mthds_files_into_library(self, *, library_id: str, bundle_files: list[LibraryBundleFile]) -> list[PipeAbstract]:"""Load MTHDS files into a specific library.@@ -1404,6 +1508,7 @@ class LibraryManager(LibraryManagerAbstract):for resolved_dep in resolved_deps:self._load_single_dependency(library=library,+ library_id=library_id,resolved_dep=resolved_dep,package_address=resolved_dep.address,tree_limits=tree_limits,@@ -1417,6 +1522,7 @@ class LibraryManager(LibraryManagerAbstract):self,library: Library,*,+ library_id: str,resolved_dep: ResolvedDependency,package_address: str,tree_limits: TreeLimits | None = None,@@ -1438,6 +1544,7 @@ class LibraryManager(LibraryManagerAbstract):Args:library: The main library to load into+ library_id: The id the manager holds the main library under, which holds the package's tree for its runsresolved_dep: The resolved dependency infopackage_address: The dependency's address as a reference names it, without any ``@<tag>``tree_limits: The limits the package's tree is listed under, read from the configuration when not given@@ -1458,6 +1565,9 @@ class LibraryManager(LibraryManagerAbstract):package_tree = list_package_method_tree(root=resolved_dep.package_root, package_address=package_address, limits=tree_limits)# The package's own requirements.txt is judged before any of its bundles loads, as the consumer's tree is.ensure_package_requirements_met(tree=package_tree, package_address=package_address)+ # Held for the consumer's runs, which read a file of the package's tree, such as one of its steps' template+ # files, by the tree's digest.+ LOCAL_METHOD_FILES.hold_tree(holder=library_id, tree=package_tree)for tree_bundle in tree_bundles_of(tree=package_tree):# The package's address and the bundle's tree path: never the host's path to the package.bundle_source = f"{package_address}/{tree_bundle.tree_path}"@@ -1686,6 +1796,7 @@ class LibraryManager(LibraryManagerAbstract):try:self._load_address_based_dependency(library=library,+ library_id=library_id,full_address=full_address,extra_search_dirs=extra_search_dirs,methods_dirs=methods_dirs,@@ -1720,6 +1831,7 @@ class LibraryManager(LibraryManagerAbstract):self,library: "Library",*,+ library_id: str,full_address: str,extra_search_dirs: list[Path] | None = None,methods_dirs: list[Path] | None = None,@@ -1734,6 +1846,7 @@ class LibraryManager(LibraryManagerAbstract):Args:library: The main library to load into+ library_id: The id the manager holds the main library under, which holds the package's tree for its runsfull_address: The full package address (e.g. "github.com/Pipelex/methods/documents")extra_search_dirs: Additional .mthds/methods/ directories to scanmethods_dirs: The load's own methods directories, searched before everything else and never written@@ -1759,6 +1872,7 @@ class LibraryManager(LibraryManagerAbstract):self._load_single_dependency(library=library,+ library_id=library_id,resolved_dep=resolved_dep,# The address the lookup matched (the manifest's address and the method's name), never a tag.package_address=f"{installed.manifest.address}/{installed.name}",@@ -2009,3 +2123,21 @@ class LibraryManager(LibraryManagerAbstract):# Check each concept as a starting pointfor concept in concepts:check_for_cycle(concept.concept_ref, visiting=set(), path=[])+++def _building_bundle_of(+ *, tree_bundle_ref: TreeBundleRef | None, live_trees: "Mapping[str, MethodTree]", written_tree: MethodTree | None+) -> BuildingBundle:+ """Where a pipe of a crate is built: in the tree written out for it, in a held tree the crate names, or by digest alone.++ A written tree holds none of its tree's bundles and may hold a generated `structures` module, so its own digest is+ not the crate's: the bundle carries the crate's, the one any other process knows the tree by.+ """+ if tree_bundle_ref is None:+ return None+ if written_tree is not None:+ return TreeBundle(tree=written_tree, tree_path=tree_bundle_ref.tree_path, named_digest=tree_bundle_ref.tree_digest)+ live_tree = live_trees.get(tree_bundle_ref.tree_digest)+ if live_tree is None:+ return tree_bundle_ref+ return TreeBundle(tree=live_tree, tree_path=tree_bundle_ref.tree_path)diff --git a/pipelex/libraries/library_manager_abstract.py b/pipelex/libraries/library_manager_abstract.pyindex 432da7250..08c3f8cd3 100644--- a/pipelex/libraries/library_manager_abstract.py+++ b/pipelex/libraries/library_manager_abstract.py@@ -1,16 +1,17 @@from abc import ABC, abstractmethod+from collections.abc import Mappingfrom pathlib import Pathfrom typing import TYPE_CHECKINGfrom kajson.class_registry import ClassRegistry-from pipelex.core.bundle_resources.bundle_resource import BundleResources-from pipelex.core.method_trees.tree_files import TreeFileEntryfrom pipelex.libraries.library_crate import LibraryCratefrom pipelex.mthds_parsing.pipelex_bundle_blueprint import PipelexBundleBlueprintfrom pipelex.pipe_machinery.pipe_abstract import PipeAbstractif TYPE_CHECKING:+ from mthds.method_tree.models import MethodTree+from pipelex.libraries.library import Library@@ -100,27 +101,17 @@ class LibraryManagerAbstract(ABC):"""@abstractmethod- def get_pipe_func_files(self, *, library_id: str, root_key: str) -> dict[str, TreeFileEntry] | None:- """The files a library captured for the `PipeFunc` calls of one Python root, or None when it captured none.-- A sandbox-hosted load captures them from the library directories, and a transported crate carries them, so a- `PipeFunc`'s validation reads its module there rather than from a disk that may be another host's.-- Args:- library_id: The library.- root_key: The Python root: a method tree's key, or `SUBMITTED_PYTHON_ROOT_KEY` for bundles parsed from strings.- """-- @abstractmethod- def add_bundle_resources(self, *, library_id: str, bundle_resources: BundleResources) -> None:+ def add_submitted_files(self, *, library_id: str, submitted_files: Mapping[str, bytes]) -> None:"""Hold the files submitted with bundles loaded from content strings, for their pipes to read.- Called before the bundles load, since a pipe that reads one, such as a `PipeDocGen` step with an HTML- `template_file`, reads it while it is built. The library's crate carries them from then on.+ Called before the bundles load: they are placed at the root of the tree these files make, with the files of the+ library directories whose own tree holds no bundle, and a pipe naming one, such as a `PipeDocGen` step with a+ `template_file`, resolves it there as it is built. The crate names that tree by its digest, and the library holds+ it in the local method file store until it is torn down.Args:library_id: The library the bundles load into- bundle_resources: The files, keyed by canonical bundle-relative path+ submitted_files: The files, keyed by canonical bundle-relative path"""@abstractmethod@@ -144,8 +135,15 @@ class LibraryManagerAbstract(ABC):"""@abstractmethod- def load_from_crate(self, *, library_id: str, crate: LibraryCrate, is_crate_prevalidated: bool = False) -> list[PipeAbstract]:- """Load a LibraryCrate into a live Library.+ def load_from_crate(+ self,+ *,+ library_id: str,+ crate: LibraryCrate,+ is_crate_prevalidated: bool = False,+ written_pipe_trees: "Mapping[str, MethodTree] | None" = None,+ ) -> list[PipeAbstract]:+ """Load a LibraryCrate into a live Library, reading no file but, for its validation, files of trees this process holds.Note: This method does NOT resolve cross-package address-based dependencies.Callers must handle dependency loading before calling this method.@@ -156,6 +154,10 @@ class LibraryManagerAbstract(ABC):is_crate_prevalidated: Skip the library validation that ends the load. Precondition: the cratewas built from a library that this same pipelex version loaded and validated (a runner'scrate, handed to the worker that executes it). Everything else the load does still happens.+ written_pipe_trees: The trees this process wrote out for a step to run in, by that step's pipe ref, such+ as the tree of a `PipeFunc` call written for its function to import: that step is built as a member of+ the written tree, which holds none of its tree's bundles, while every other step is built as the+ library crate names it."""@abstractmethoddiff --git a/pipelex/libraries/method_requirements.py b/pipelex/libraries/method_requirements.pyindex 7c5892dc8..6131b38b7 100644--- a/pipelex/libraries/method_requirements.py+++ b/pipelex/libraries/method_requirements.py@@ -37,9 +37,8 @@ from packaging.utils import canonicalize_namefrom packaging.version import InvalidVersion, Versionfrom pipelex.core.exceptions import PipelexBundleBlueprintValidationErrorData-from pipelex.core.method_trees.tree_bundle import tree_key_offrom pipelex.libraries.exceptions import MethodRequirementsFileError, MethodRequirementsNotMetError-from pipelex.libraries.method_trees import list_library_dir_trees, reporting_host_library_tree_faults+from pipelex.libraries.method_trees import list_library_dir_trees, listing_identity, reporting_host_library_tree_faultsfrom pipelex.libraries.package_environments import PythonPackageEnvironment, resolve_pipe_func_package_environmentREQUIREMENTS_FILE_NAME = "requirements.txt"@@ -364,12 +363,12 @@ def _ensure_judged_methods_met(*, judged_methods: Iterable[JudgedMethod], names_set for them."""environment: PythonPackageEnvironment | None = None- judged_tree_keys: set[str] = set()+ judged_trees: set[tuple[str, str, bool]] = set()for judged in judged_methods:- tree_key = tree_key_of(tree=judged.tree)- if tree_key in judged_tree_keys:+ tree_identity = listing_identity(tree=judged.tree)+ if tree_identity in judged_trees:continue- judged_tree_keys.add(tree_key)+ judged_trees.add(tree_identity)if not holds_requirements_to_check(tree=judged.tree):continueparsed = parse_requirements_text(text=_read_requirements_text(judged=judged))diff --git a/pipelex/libraries/method_trees.py b/pipelex/libraries/method_trees.pyindex 4fc67cb0e..c4240f816 100644--- a/pipelex/libraries/method_trees.py+++ b/pipelex/libraries/method_trees.py@@ -44,6 +44,7 @@ from mthds.method_tree.tree_path import nfcfrom mthds.method_tree.vocabulary import ExclusionRule, TreeRefusalCodefrom pipelex import log+from pipelex.core.method_trees.method_file_store import HeldFilefrom pipelex.core.method_trees.tree_bundle import TreeBundlefrom pipelex.hosted.execution import get_or_load_pipelex_configfrom pipelex.libraries.exceptions import HostLibraryRequirementsError, HostLibraryTreeError, MethodRequirementsError, MethodTreeLoadError@@ -515,15 +516,25 @@ def tree_python_sources(*, tree: MethodTree, library_dir: Path | None) -> dict[sreturn sources-def submitted_python_files(*, library_tree: LibraryTree) -> dict[str, bytes]:+def listing_identity(*, tree: MethodTree) -> tuple[str, str, bool]:+ """What makes two listings one tree on this host: their root, their digest, and whether they are a one-file tree.++ Two listings of one directory with the same files are one tree, and a one-file tree is never the directory tree of+ its folder, since only the latter lets a reference reach another file. A crate needs none of this: it names a tree by+ its digest alone, which names its files' bytes wherever they lie.+ """+ return (str(tree.directory), tree.digest, tree.is_one_file)+++def submitted_tree_files(*, library_tree: LibraryTree) -> dict[str, HeldFile]:"""The files a library directory submits beside bundles parsed from content strings, keyed by their path from it.- A directory whose own tree holds no bundle, such as the directory a server writes a request's Python into beside the- request's bundles, is where those bundles' import paths start, so its files other than bundles travel with each call- of their `PipeFunc` steps. A tree holding a bundle submits nothing: its steps' calls carry their own tree's files, so a- directory's files never travel twice, and two such directories never share one import root. Neither does a tree- nested in a library directory. The membership rule decides what the tree holds, so a `.gitignore`d file or a virtual- environment never travels.+ A directory whose own tree holds no bundle, such as the directory a server writes a request's files into beside the+ request's bundles, is where those bundles' references and import paths start, so its files join the tree of the files+ submitted with them, the bundles sitting at its root. A tree holding a bundle submits nothing: its steps read and+ call their own tree's files, so a directory's files never join two trees. Neither does a tree nested in a library+ directory. The membership rule decides what the tree holds, so a `.gitignore`d file or a virtual environment never+ joins. Nothing is read: each file is held by the hash its listing recorded, and read from the disk when it is used.Args:library_tree: A tree the library directory holds, as `list_library_dir_trees` listed it.@@ -536,8 +547,10 @@ def submitted_python_files(*, library_tree: LibraryTree) -> dict[str, bytes]:# Not the directory's own tree: one nested in it.return {}stripped_prefix = spelling[0]- files: dict[str, bytes] = {}- for tree_path in tree.tree_paths:- if tree_path.startswith(stripped_prefix):- files[tree_path.removeprefix(stripped_prefix)] = tree.file_location(tree_path).read_bytes()+ files: dict[str, HeldFile] = {}+ for tree_file in tree.files:+ if tree_file.path.startswith(stripped_prefix):+ files[tree_file.path.removeprefix(stripped_prefix)] = HeldFile(+ sha256=tree_file.sha256, size=tree_file.size, source=tree.file_location(tree_file.path)+ )return filesdiff --git a/pipelex/libraries/pipe_func_call_files.py b/pipelex/libraries/pipe_func_call_files.pyindex 5785d3c10..4ed23d7c3 100644--- a/pipelex/libraries/pipe_func_call_files.py+++ b/pipelex/libraries/pipe_func_call_files.py@@ -1,29 +1,24 @@-"""The files a sandbox-hosted `PipeFunc` call receives, captured onto the library crate without importing anything.--A sandbox-hosted deployment never imports a method's Python in its own process: every call to a `PipeFunc` runs in a-sandbox that receives the files of the step's Python root, every file except the `.mthds` files, at their paths-(`wip/extra-files/design.md`, "Inside a run"). They are read once, as the library loads, for each method tree holding a-`PipeFunc` step, and the crate carries them, per root, wherever the run travels, a Temporal workflow included, which may-read no file itself (`LibraryCrate.pipe_func_files`); a directory the load read them from may be gone by then, such as-the temporary one a server writes a request's files into.--The generated `structures` module is the one file left behind: the sandbox generates its own from the crate's concepts,-with the qualified class names the runtime checks a return type against, and a method's own copy beside it would give-the sandbox two modules of that name.-"""+"""The files an out-of-process `PipeFunc` call receives: its method tree's, read through the method file store.++A call to a `PipeFunc` that runs out of the process that loaded its method, in a sandbox or in an activity, receives the+files of the step's tree, every file except the `.mthds` files, at their tree paths (`wip/extra-files/design.md`, "Inside+a run"). The call names the tree by digest (`PipeFuncExecutionRequest.tree_digest`), and whoever runs it reads the files+through the method file store under the run's read scope, where IO is allowed, never in a workflow.-from mthds.method_tree.models import MethodTree+The generated `structures` module is the one file left behind: the process running the call generates its own from the+crate's concepts, with the qualified class names the runtime checks a return type against, and a method's own copy+beside it would give it two modules of that name.+"""-from pipelex.core.method_trees.tree_files import TreeFileEntry, read_call_files+from pipelex.core.method_trees.method_files import read_tree_files+from pipelex.core.method_trees.tree_files import is_bundle_filefrom pipelex.methods.structures_check import is_generated_structures_module-from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipelexBundleBlueprint_PYTHON_SUFFIX = ".py"-_PIPE_FUNC_TYPE = "PipeFunc"def travels_with_call(*, tree_path: str, data: bytes) -> bool:- """Whether a file of a `PipeFunc`'s Python root travels with its calls: every file but a generated `structures` module."""+ """Whether a file of a `PipeFunc`'s tree travels with its calls: every file but a generated `structures` module."""if not tree_path.endswith(_PYTHON_SUFFIX):return Truetry:@@ -33,11 +28,11 @@ def travels_with_call(*, tree_path: str, data: bytes) -> bool:return not is_generated_structures_module(source=source)-def holds_pipe_func_step(*, blueprint: PipelexBundleBlueprint) -> bool:- """Whether a bundle declares a `PipeFunc` step, whose calls carry its tree's files."""- return any(pipe_blueprint.type == _PIPE_FUNC_TYPE for pipe_blueprint in (blueprint.pipe or {}).values())-+async def read_pipe_func_call_files(*, tree_digest: str, read_scope: str | None) -> dict[str, bytes]:+ """The files a call of a `PipeFunc` of the tree `tree_digest` names receives, by tree path, read through the method file store.-def tree_pipe_func_files(*, tree: MethodTree) -> dict[str, TreeFileEntry]:- """The files every `PipeFunc` call of a method tree listed from this host's disk receives, read from the disk now."""- return read_call_files(tree=tree, keeps=travels_with_call)+ Raises:+ MethodFileUnavailableError: The store does not hold the tree or one of its files for this run.+ """+ files = await read_tree_files(tree_digest=tree_digest, read_scope=read_scope, keeps=lambda tree_path: not is_bundle_file(tree_path=tree_path))+ return {tree_path: data for tree_path, data in files.items() if travels_with_call(tree_path=tree_path, data=data)}diff --git a/pipelex/mthds_parsing/pipelex_bundle_blueprint.py b/pipelex/mthds_parsing/pipelex_bundle_blueprint.pyindex d138c8752..702e40f53 100644--- a/pipelex/mthds_parsing/pipelex_bundle_blueprint.py+++ b/pipelex/mthds_parsing/pipelex_bundle_blueprint.py@@ -132,20 +132,20 @@ class PipelexBundleBlueprint(BaseModel):# library manager lists the bundle's method tree from when no loader placed the bundle in one._host_bundle_file: Path | None = PrivateAttr(default=None)# The bundle as a member of its method tree, set by the loader that listed the tree. A step reads a file the bundle- # names, such as a PipeDocGen `template_file`, only by resolving it in this tree; a bundle parsed from a string has- # none, and reads only the files submitted with it.+ # names, such as a PipeDocGen `template_file`, only by resolving it in this tree. A bundle parsed from a string sits at+ # the root of the tree of the files submitted with it, with no tree path, and has no tree when none was submitted._tree_bundle: TreeBundle | None = PrivateAttr(default=None)@propertydef host_bundle_file(self) -> Path | None:"""The file on this host the bundle was read from, or None for a bundle parsed from a string."""- if self._tree_bundle is not None:+ if self._tree_bundle is not None and self._tree_bundle.tree_path is not None:return self._tree_bundle.locationreturn self._host_bundle_file@propertydef tree_bundle(self) -> TreeBundle | None:- """The bundle as a member of its method tree, or None for a bundle parsed from a string or not yet placed in one."""+ """The bundle as a member of its method tree, or None for a bundle not placed in one."""return self._tree_bundledef mark_read_from_host_file(self, *, bundle_file: Path) -> None:@@ -153,7 +153,9 @@ class PipelexBundleBlueprint(BaseModel):self._host_bundle_file = bundle_filedef place_in_tree(self, *, tree_bundle: TreeBundle) -> None:- """Record the bundle as `tree_bundle`, the member of the method tree a loader listed it in."""+ """Record the bundle as `tree_bundle`: the member of the method tree a loader listed it in, or a bundle parsed from a+ string at the root of the tree of the files submitted with it.+ """self._tree_bundle = tree_bundle@field_validator("domain", mode="before")diff --git a/pipelex/pipe_machinery/pipe_blueprint.py b/pipelex/pipe_machinery/pipe_blueprint.pyindex 814ce857a..104e3fee0 100644--- a/pipelex/pipe_machinery/pipe_blueprint.py+++ b/pipelex/pipe_machinery/pipe_blueprint.py@@ -6,7 +6,6 @@ from typing import Any, Self, cast, finalfrom pydantic import BaseModel, ConfigDict, Field, SerializerFunctionWrapHandler, field_validator, model_serializer, model_validator-from pipelex.core.bundle_resources.bundle_resource import BundleResourceReadStagefrom pipelex.core.concepts.exceptions import ConceptStringErrorfrom pipelex.core.concepts.validation import validate_concept_ref_or_codefrom pipelex.core.pipes.exceptions import PipeValidationError@@ -231,7 +230,7 @@ class PipeBlueprint(ABC, BaseModel):source: str | None = None"""Not an authoring field. The library manager clears it just before the pipe is built, so whatever a bundle's textwrites here is never read: a step finds a file its bundle names in the bundle's method tree, which the library- manager hands the factory (see `LibraryCrate.method_trees` and `building_pipe_of`)."""+ manager hands the factory (see `LibraryCrate.tree_bundles` and `building_pipe_of`)."""pipe_category: Any = Field(exclude=True) # Technical field for Union discrimination, not user-facingtype: Any # TODO: Find a better way to handle this.description: str@@ -291,14 +290,13 @@ class PipeBlueprint(ABC, BaseModel):return set()@property- def bundle_resource_reads(self) -> dict[str, BundleResourceReadStage]:- """The files of its bundle this pipe reads, keyed by the bundle-relative path it names, and when it reads each.+ def named_file_references(self) -> set[str]:+ """The files of its method tree this pipe names, as it writes them, relative to its bundle.- Overridden by a pipe that reads a file beside its bundle, such as a `PipeDocGen` step's `template_file`.- A bundle submitted as content strings brings exactly these files with it, and the one read only when the- step runs may travel with the run by reference.+ Overridden by a pipe that reads a file of its tree, such as a `PipeDocGen` step's `template_file`. A bundle+ submitted as content strings brings exactly these files with it."""- return {}+ return set()@propertydef ordered_pipe_dependencies(self) -> list[str] | None:diff --git a/pipelex/pipe_operators/doc_gen/doc_gen_rendering.py b/pipelex/pipe_operators/doc_gen/doc_gen_rendering.pynew file mode 100644index 000000000..85f041505--- /dev/null+++ b/pipelex/pipe_operators/doc_gen/doc_gen_rendering.py@@ -0,0 +1,55 @@+"""Rendering a `PipeDocGen` step's templates, in its compose stage and in its print stage alike.++Every template of a document renders with a strict undefined, so a value the template reads that does not exist fails+the step rather than printing as empty text. The compose stage renders the filename and an inline HTML template; the+print stage renders an HTML template file, which it reads through the method file store (`DocGenTemplateFileStage`).+Both raise the same errors, worded the same way.+"""++from typing import Any++from jinja2.exceptions import UndefinedError++from pipelex.cogt.templating.template_rendering import render_template+from pipelex.pipe_operators.doc_gen.exceptions import PipeDocGenRunError, PipeDocGenUndefinedValueError+from pipelex.tools.jinja2.exceptions import Jinja2TemplateRenderError+from pipelex.tools.jinja2.template_category import TemplateCategory+from pipelex.tools.templating.templating_style import TemplatingStyle+++async def render_doc_gen_template(+ *,+ pipe_code: str,+ template: str,+ category: TemplateCategory,+ context: dict[str, Any],+ label: str,+ templating_style: TemplatingStyle | None = None,+) -> str:+ """A template of the step `pipe_code` rendered with `context`, every value it reads required to exist.++ Raises:+ PipeDocGenUndefinedValueError: The template reads a value that does not exist.+ PipeDocGenRunError: The template could not be rendered for another reason.+ """+ try:+ return await render_template(+ template=template,+ category=category,+ context=context,+ templating_style=templating_style,+ is_undefined_strict=True,+ )+ except Jinja2TemplateRenderError as exc:+ undefined_error = exc.__cause__+ if isinstance(undefined_error, UndefinedError):+ # Raised from Jinja's own error rather than from the tools-layer wrapper, whose message quotes the+ # template and is not caller-facing, so that this is the root fault a verdict or a run report names.+ msg = (+ f"PipeDocGen '{pipe_code}' could not render its {label}: {undefined_error.message}. "+ "Every value a document's template reads must exist: check the name against the input's concept, "+ "or test an optional value first with {% if ... %}."+ )+ raise PipeDocGenUndefinedValueError(msg) from undefined_error+ msg = f"PipeDocGen '{pipe_code}' could not render its {label}: {exc}"+ raise PipeDocGenRunError(msg) from excdiff --git a/pipelex/pipe_operators/doc_gen/exceptions.py b/pipelex/pipe_operators/doc_gen/exceptions.pyindex da0e93915..d9dce6136 100644--- a/pipelex/pipe_operators/doc_gen/exceptions.py+++ b/pipelex/pipe_operators/doc_gen/exceptions.py@@ -42,3 +42,18 @@ class PipeDocGenTemplateCheckError(PipelexError):error_domain = ErrorDomain.INPUT_authors_caller_facing_message = True+++class PipeDocGenTemplateFileUncheckedError(PipelexError):+ """Raised when a ``PipeDocGen`` step built from a library crate is validated where its HTML template file is not at hand.++ An HTML template file's checks read the file: the variables it reads are inputs of the step, the fields it reads are+ fields of their concepts, and every reference to an optional input is guarded. A crate names the step's method tree+ by digest and carries none of its files, so a validation of the crate reads the file from a tree a library of this+ process holds, and reaches the verdict the load where the crate was assembled reached. Where no library holds the+ tree, the validation cannot reach it, and refuses rather than pass the step unchecked. The fault is where the crate+ was validated, not in the method, and the message names only the step and the template file's tree path.+ """++ error_domain = ErrorDomain.RUNTIME+ retryable = Falsediff --git a/pipelex/pipe_operators/doc_gen/pipe_doc_gen.py b/pipelex/pipe_operators/doc_gen/pipe_doc_gen.pyindex 59f11a990..b593dfb99 100644--- a/pipelex/pipe_operators/doc_gen/pipe_doc_gen.py+++ b/pipelex/pipe_operators/doc_gen/pipe_doc_gen.py@@ -1,53 +1,44 @@-import asyncio-from pathlib import Path-from typing import Any, Literal+from typing import TYPE_CHECKING, Any, Literal-from jinja2.exceptions import UndefinedError-from pydantic import Field+from pydantic import Field, PrivateAttrfrom typing_extensions import overridefrom pipelex import log-from pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItem-from pipelex.cogt.content_generation.read_authorization import authorize_assignment_readsfrom pipelex.cogt.doc_gen.doc_gen_engine import require_doc_gen_engine_declared, resolve_doc_gen_settingfrom pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSourcefrom pipelex.cogt.doc_gen.doc_gen_setting import DocGenModelChoice, DocGenSetting-from pipelex.cogt.doc_gen.doc_gen_worker_factory import DocGenWorkerFactory-from pipelex.cogt.doc_gen.document_composition import DocumentComposition+from pipelex.cogt.doc_gen.document_composition import ComposedTemplateFile, DocumentComposition, TemplateRenderContextfrom pipelex.cogt.doc_gen.input_shape import InputShape, shape_of_inputfrom pipelex.cogt.doc_gen.layout_builder import build_layout_document, humanizefrom pipelex.cogt.doc_gen.plain_data import plain_data-from pipelex.cogt.doc_gen.template_check import TemplateCheckRequest, TemplateFinding-from pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.models.model_deck_check import check_doc_gen_choice_with_deckfrom pipelex.cogt.templating.template_preprocessor import rewrite_template_sigils-from pipelex.cogt.templating.template_rendering import render_template-from pipelex.core.bundle_resources.bundle_resource import BundleResourcefrom pipelex.core.memory.working_memory import WorkingMemory+from pipelex.core.method_trees.tree_bundle import MethodFileReffrom pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecsfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.core.stuffs.document_content import DocumentContentfrom pipelex.core.stuffs.stuff_content import StuffContent+from pipelex.interpreter_hub import get_current_library, get_library_managerfrom pipelex.kernel.compose_ops import build_compose_contextfrom pipelex.kernel.memory_ops import store_resultfrom pipelex.kernel.templating_style_ops import resolve_templating_stylefrom pipelex.pipe_machinery.template_guard_lint import lint_authored_template-from pipelex.pipe_operators.doc_gen.exceptions import PipeDocGenRunError, PipeDocGenTemplateCheckError, PipeDocGenUndefinedValueError+from pipelex.pipe_operators.doc_gen.doc_gen_rendering import render_doc_gen_template+from pipelex.pipe_operators.doc_gen.exceptions import PipeDocGenRunError, PipeDocGenTemplateFileUncheckedErrorfrom pipelex.pipe_operators.doc_gen.template_field_check import check_template_field_paths-from pipelex.pipe_operators.doc_gen.template_file_resource import bundle_resource_of_template_filefrom pipelex.pipe_operators.pipe_operator import PipeOperator-from pipelex.pipe_run.dry_run_warning_collector import report_dry_run_warningfrom pipelex.pipe_run.pipe_run_params import PipeRunParams-from pipelex.runtime_hub import get_class_registry, get_content_generator, get_model_deck, get_report_delegate, get_storage_provider+from pipelex.runtime_hub import get_class_registry, get_content_generatorfrom pipelex.system.job_metadata import JobMetadata-from pipelex.tools.jinja2.exceptions import Jinja2TemplateRenderErrorfrom pipelex.tools.jinja2.jinja2_required_variables import detect_jinja2_required_variablesfrom pipelex.tools.jinja2.template_category import TemplateCategoryfrom pipelex.tools.misc.string_utils import get_root_from_dotted_pathfrom pipelex.tools.storage.storage_file_name import path_safe_file_namefrom pipelex.tools.templating.templating_style import TemplatingStyle-from pipelex.tools.uri.uri_read_scope import UriReference-from pipelex.validation_error_types import TemplateCheckErrorType++if TYPE_CHECKING:+ from pipelex.core.stuffs.stuff import Stuffclass PipeDocGenOutput(PipeOutput):@@ -57,24 +48,52 @@ class PipeDocGenOutput(PipeOutput):class PipeDocGen(PipeOperator[PipeDocGenOutput]):"""Turn the step's inputs into a stored document file, in two stages. It calls no AI model.- The **compose stage** is pure: it builds the layout tree of the inputs, or renders the HTML template, or- gathers the inputs as plain data for a template file, and it renders the filename, every template with a- strict undefined so a missing field fails rather than printing as empty text. The **print stage** is the- content generator's `make_rendered_document`: the step's engine prints the composition, and the bytes are- stored through the run's storage provider as a `DocumentContent`. The engine is a `doc_gen` model, the one the- step names or the model deck's default for its format and source, checked when the method loads. A dry run- composes for real, which checks the templates against mock inputs, runs the engine's template checker on a- template file, and prints and stores nothing.+ The **compose stage** is pure, and reads no file: it builds the layout tree of the inputs, or renders the inline+ HTML template, or names the template file, a file of the step's method tree, with what the print stage needs to+ use it, and it renders the filename, every template with a strict undefined so a missing field fails rather than+ printing as empty text. The **print stage** is the content generator's `make_rendered_document`, an activity on a+ hosted plane: it reads the template file through the method file store, renders an HTML one with the step's data,+ the step's engine prints the composition, and the bytes are stored through the run's storage provider as a+ `DocumentContent`. The engine is a `doc_gen` model, the one the step names or the model deck's default for its+ format and source, checked when the method loads. A dry run composes for real, which checks the templates against+ mock inputs; its print reads and renders the template file and runs the engine's template checker on an office+ one, and prints and stores nothing."""type: Literal["PipeDocGen"] = "PipeDocGen"doc_gen_format: DocGenFormat = Field(strict=False)doc_gen_choice: DocGenModelChoice | None = Field(default=None, description="The engine the step names, or None for the deck's default")- template: str | None = Field(default=None, description="The HTML template of a pdf step, inline or read from its template file")+ template: str | None = Field(default=None, description="The inline HTML template of a pdf step")template_file: str | None = Field(default=None, description="The template file as the method names it")- template_path: str | None = Field(default=None, description="The resolved path of an office template file, which its engine fills")+ template_file_ref: MethodFileRef | None = Field(+ default=None, description="The template file as a file of the step's method tree, which the print stage reads"+ )filename: str | None = None+ # The text of an HTML template file, read when the step was built in a method tree this process holds, for the checks+ # of the method's load: a bundle's, or a crate's whose load validates it where a library holds its tree. None for a+ # step built from a crate by digest alone, which reads no file, and which a validation refuses rather than pass+ # unchecked (`validate_inputs_with_library`).+ _template_file_text: str | None = PrivateAttr(default=None)++ def hold_template_file_text(self, *, template_file_text: str) -> None:+ """Keep the text of the step's HTML template file, read at load, for the load's checks."""+ self._template_file_text = template_file_text++ @property+ def template_file_text(self) -> str | None:+ """The text of the step's HTML template file as the load read and checked it, or None when the load read none."""+ return self._template_file_text++ @property+ def _checked_html_template(self) -> tuple[str, str] | None:+ """The HTML template the load checks, with how a message names it: the inline one, or the file's text when read."""+ if self.template is not None:+ return self.template, "template"+ if self._template_file_text is not None:+ return self._template_file_text, f"template file '{self.template_file}'"+ return None+@propertydef source(self) -> DocGenSource:return DocGenSource.for_step(doc_gen_format=self.doc_gen_format, has_template=self.template is not None or self.template_file is not None)@@ -86,7 +105,9 @@ class PipeDocGen(PipeOperator[PipeDocGenOutput]):@overridedef required_variables(self) -> set[str]:roots: set[str] = set()- for template_source, category in ((self.template, TemplateCategory.HTML), (self.filename, TemplateCategory.BASIC)):+ checked_html_template = self._checked_html_template+ html_template = checked_html_template[0] if checked_html_template is not None else None+ for template_source, category in ((html_template, TemplateCategory.HTML), (self.filename, TemplateCategory.BASIC)):if template_source is None:continuefor path in detect_jinja2_required_variables(template_category=category, template_source=rewrite_template_sigils(template_source)):@@ -116,14 +137,16 @@ class PipeDocGen(PipeOperator[PipeDocGenOutput]):# The same template lints as PipeCompose: no private names, and every reference to a declared-optional input# guarded. The filename gets both too, since it renders as strictly as the template does.- if self.template is not None:+ checked_html_template = self._checked_html_template+ if checked_html_template is not None:+ html_template, html_template_label = checked_html_templatelint_authored_template(pipe_code=self.code,domain_code=self.domain_code,inputs=self.inputs,- template_source=self.template,+ template_source=html_template,template_category=TemplateCategory.HTML,- template_label=f"template file '{self.template_file}'" if self.template_file is not None else "template",+ template_label=html_template_label,)if self.filename is not None:lint_authored_template(@@ -137,13 +160,25 @@ class PipeDocGen(PipeOperator[PipeDocGenOutput]):@overridedef validate_inputs_with_library(self):+ # A step built from a crate by digest alone holds no text of its HTML template file, so no check of it ran: the+ # validation refuses rather than reach a verdict the template could contradict. A load that skips validation,+ # such as a worker's load of the crate a validated library made, never gets here.+ if self.template_file is not None and self.doc_gen_format.is_template_html and self._template_file_text is None:+ msg = (+ f"PipeDocGen '{self.code}' prints from the HTML template file '{self.template_file}', which this validation "+ "cannot check: the step was built from a library crate, which names its method tree by digest and carries "+ "none of its files, and no library of this process holds that tree. Validate the method where its files are."+ )+ raise PipeDocGenTemplateFileUncheckedError(msg)# Every field a template reads exists on its input's concept, which is known once the library is loaded.- if self.template is not None:+ checked_html_template = self._checked_html_template+ if checked_html_template is not None:+ html_template, html_template_label = checked_html_templatecheck_template_field_paths(pipe_code=self.code,- template_source=self.template,+ template_source=html_template,template_category=TemplateCategory.HTML,- label=f"template file '{self.template_file}'" if self.template_file is not None else "template",+ label=html_template_label,inputs=self.inputs,)if self.filename is not None:@@ -185,30 +220,18 @@ class PipeDocGen(PipeOperator[PipeDocGenOutput]):async def _render(self, *, template: str, category: TemplateCategory, context: dict[str, Any], label: str, templating_style: TemplatingStyle | None = None) -> str:- try:- return await render_template(- template=template,- category=category,- context=context,- templating_style=templating_style,- is_undefined_strict=True,- )- except Jinja2TemplateRenderError as exc:- undefined_error = exc.__cause__- if isinstance(undefined_error, UndefinedError):- # Raised from Jinja's own error rather than from the tools-layer wrapper, whose message quotes the- # template and is not caller-facing, so that this is the root fault a verdict or a run report names.- msg = (- f"PipeDocGen '{self.code}' could not render its {label}: {undefined_error.message}. "- "Every value a document's template reads must exist: check the name against the input's concept, "- "or test an optional value first with {% if ... %}."- )- raise PipeDocGenUndefinedValueError(msg) from undefined_error- msg = f"PipeDocGen '{self.code}' could not render its {label}: {exc}"- raise PipeDocGenRunError(msg) from exc+ return await render_doc_gen_template(+ pipe_code=self.code, template=template, category=category, context=context, label=label, templating_style=templating_style+ )async def compose(self, *, working_memory: WorkingMemory, pipe_run_params: PipeRunParams) -> DocumentComposition:- """The pure half of the step: everything the print stage needs, and nothing printed yet."""+ """The pure half of the step: everything the print stage needs, and nothing printed yet.++ It reads no file, so it runs where the step runs, in a workflow on a hosted plane. An inline HTML template is+ rendered here, its text being the bundle's own; a template file is named by its tree's digest and its tree path,+ for the print stage to read it: an HTML one with the step's data and the run's crate, which the print stage+ renders it with, an office one with the step's data as plain data and the shapes of its inputs.+ """context = build_compose_context(memory=working_memory, runtime_params=pipe_run_params.params)rendered_filename = self.codeif self.filename is not None:@@ -235,68 +258,78 @@ class PipeDocGen(PipeOperator[PipeDocGenOutput]):layout=build_layout_document(title=title, named_contents=named_contents),)case DocGenSource.HTML:- if self.template is None:- msg = f"PipeDocGen '{self.code}' composes from HTML but has no HTML template."- raise PipeDocGenRunError(msg)- html = await self._render(- template=self.template,- category=TemplateCategory.HTML,- context=context,- label="template",- templating_style=resolve_templating_style(authored=None),+ if self.template is not None:+ html = await self._render(+ template=self.template,+ category=TemplateCategory.HTML,+ context=context,+ label="template",+ templating_style=resolve_templating_style(authored=None),+ )+ return DocumentComposition(format=self.doc_gen_format, source=source, filename=filename, title=title, html=html)+ return DocumentComposition(+ format=self.doc_gen_format,+ source=source,+ filename=filename,+ title=title,+ template_file=self._composed_template_file(+ render_context=self._render_context(working_memory=working_memory, pipe_run_params=pipe_run_params)+ ),)- return DocumentComposition(format=self.doc_gen_format, source=source, filename=filename, title=title, html=html)case DocGenSource.TEMPLATE_FILE:return DocumentComposition(format=self.doc_gen_format,source=source,filename=filename,title=title,- template_path=self.template_path,- template_resource=self._template_resource(),- template_name=self.template_file,+ template_file=self._composed_template_file(input_shapes=self._input_shapes()),data={name: plain_data(content) for name, content in named_contents},)- def _template_resource(self) -> BundleResource | None:- """The office template submitted with the bundle, or None when the step reads it beside its bundle on disk.+ def _composed_template_file(+ self, *, render_context: TemplateRenderContext | None = None, input_shapes: dict[str, InputShape] | None = None+ ) -> ComposedTemplateFile:+ """The step's template file as its print stage reads it.- Looked up when the step composes, in the library the step runs in: the submitter's own, or the one a remote- worker loaded from the run's crate, whose copy may be a reference to the run's storage.+ Raises:+ PipeDocGenRunError: The step names no template file in its method tree."""- if self.template_path is not None or self.template_file is None:- return None- resource = bundle_resource_of_template_file(template_file=self.template_file)- if resource is None:- msg = f"PipeDocGen '{self.code}' names the template file '{self.template_file}', which the library it runs in does not hold."+ if self.template_file is None or self.template_file_ref is None:+ msg = f"PipeDocGen '{self.code}' prints from a template file but names none in its method tree."raise PipeDocGenRunError(msg)- return resource+ return ComposedTemplateFile(+ file=self.template_file_ref,+ name=self.template_file,+ pipe_ref=self.pipe_ref,+ render_context=render_context,+ input_shapes=input_shapes or {},+ )- async def _read_template_file(self, *, job_metadata: JobMetadata) -> bytes:- """The office template's bytes, from beside the bundle on disk or from the files submitted with it.+ def _render_context(self, *, working_memory: WorkingMemory, pipe_run_params: PipeRunParams) -> TemplateRenderContext:+ """What the print stage renders the step's HTML template file with, wherever it runs.- A submitted file the run stored before it left the process is read back under the run's read scope, as the- print stage reads it.+ Only the stuffs the step's inputs name travel, under those names: the load checked that the template reads no other+ variable but the run's params. The run's crate travels as its concepts and domains alone, which type them.Raises:- UriReadRefusedError: the stored file lies outside the run's read scope.+ PipeDocGenRunError: The library the step runs in has no crate."""- if self.template_path is not None:- return Path(self.template_path).read_bytes()- resource = self._template_resource()- if resource is None:- msg = f"PipeDocGen '{self.code}' has no template file to read."+ library_id = get_current_library()+ crate = get_library_manager().get_crate(library_id=library_id)+ if crate is None:+ msg = f"PipeDocGen '{self.code}' cannot name its template file's data: the library it runs in has no crate."raise PipeDocGenRunError(msg)- if resource.uri is not None:- authorize_assignment_reads(- job_metadata=job_metadata,- uri_references=[UriReference(uri=resource.uri, position=f"the template file '{self.template_file}'")],- )- return await resource.read_bytes(storage_provider=get_storage_provider())-- ####################################################################################################################- # Template file check, at the dry run- ####################################################################################################################+ input_stuffs: dict[str, Stuff] = {}+ for input_name in self.inputs.variables:+ stuff = working_memory.get_optional_stuff(input_name)+ if stuff is not None:+ input_stuffs[input_name] = stuff+ return TemplateRenderContext(+ crate_fingerprint=crate.fingerprint,+ concepts_crate=crate.concepts_only().model_dump(mode="json"),+ working_memory_raw=WorkingMemory(root=input_stuffs).dump_for_transport(),+ runtime_params=dict(pipe_run_params.params),+ )def _input_shapes(self) -> dict[str, InputShape]:shapes: dict[str, InputShape] = {}@@ -307,63 +340,6 @@ class PipeDocGen(PipeOperator[PipeDocGenOutput]):shapes[input_name] = shape_of_input(content_class=content_class, is_list=stuff_spec.is_multiple())return shapes- async def check_template_file(self, *, job_metadata: JobMetadata, working_memory: WorkingMemory) -> None:- """Run the engine's template checker on the step's template file, when its engine has one.-- The inputs in memory are the dry run's mocks, so the checker can fill the template in memory with them.- A warning finding is reported to the validation sweep, which puts it in the verdict's `warnings`, or logged- when no sweep collects this dry run's warnings.-- Raises:- PipeDocGenTemplateCheckError: the checker reported errors.- UriReadRefusedError: the template file was stored outside the run's read scope.- """- # Only an office template file is the engine's to check; an HTML one was checked against the inputs at load.- if self.template is not None or self.template_file is None:- return- doc_gen_setting = self.resolve_engine()- inference_model = get_model_deck().get_required_inference_model(model_handle=doc_gen_setting.model, model_type=ModelType.DOC_GEN)- worker = DocGenWorkerFactory.make_doc_gen_worker(inference_model=inference_model, reporting_delegate=get_report_delegate())- request = TemplateCheckRequest(- format=self.doc_gen_format,- template=await self._read_template_file(job_metadata=job_metadata),- template_name=self.template_file,- inputs=self._input_shapes(),- data={name: plain_data(content) for name, content in self._named_contents(working_memory)},- )- findings = await asyncio.to_thread(worker.check_template, request=request)- errors = [finding for finding in findings if finding.severity.is_error]- for finding in findings:- if not finding.severity.is_error:- self._report_template_warning(finding=finding, template_file=self.template_file)- if errors:- listed = "\n".join(f"- {finding.message}" + (f" ({finding.location})" if finding.location else "") for finding in errors)- msg = f"PipeDocGen '{self.code}': the template file '{self.template_file}' does not fit the step's inputs:\n{listed}"- raise PipeDocGenTemplateCheckError(msg)-- def _report_template_warning(self, *, finding: TemplateFinding, template_file: str) -> None:- """Report a warning of the template check as an advisory item, located at this step, its file and the place in it.-- An engine that answers an empty location names no place, so the item's `template_location` is left unset.- """- location = finding.location or None- location_suffix = f" ({location})" if location is not None else ""- warning = ValidationErrorItem(- category=ValidationErrorCategory.DRY_RUN,- error_type=TemplateCheckErrorType.TEMPLATE_CHECK_WARNING,- pipe_code=self.code,- domain_code=self.domain_code,- template_file=template_file,- template_location=location,- message=f"PipeDocGen '{self.code}', template file '{template_file}': {finding.message}{location_suffix}",- )- if report_dry_run_warning(warning=warning):- return- finding_fields: dict[str, str] = {"pipe_code": self.code, "template_file": template_file, "finding_message": finding.message}- if location is not None:- finding_fields["finding_location"] = location- log.warning("The template check of a PipeDocGen found a warning in its template file", fields=finding_fields)-##################################################################################################################### Runs####################################################################################################################@@ -429,9 +405,8 @@ class PipeDocGen(PipeOperator[PipeDocGenOutput]):output_name: str | None = None,) -> PipeDocGenOutput:# The live path with the dry mode riding into the leaf: the compose stage runs for real against the mock- # inputs, which checks the templates, and the leaf prints and stores nothing. The template file's checker- # runs first, since only a dry run has inputs to fill it with and nothing to spend.- await self.check_template_file(job_metadata=job_metadata, working_memory=working_memory)+ # inputs, which checks the inline templates, and the leaf reads and checks the template file, rendering an HTML+ # one and handing an office one to its engine's checker, and prints and stores nothing.return await self._live_run_operator_pipe(job_metadata=job_metadata,working_memory=working_memory,diff --git a/pipelex/pipe_operators/doc_gen/pipe_doc_gen_blueprint.py b/pipelex/pipe_operators/doc_gen/pipe_doc_gen_blueprint.pyindex 0951bb65b..7868667a1 100644--- a/pipelex/pipe_operators/doc_gen/pipe_doc_gen_blueprint.py+++ b/pipelex/pipe_operators/doc_gen/pipe_doc_gen_blueprint.py@@ -7,7 +7,6 @@ from pipelex.cogt.doc_gen.doc_gen_format import DocGenFormatfrom pipelex.cogt.doc_gen.doc_gen_setting import DocGenModelChoicefrom pipelex.cogt.templating.exceptions import TemplateSigilSyntaxErrorfrom pipelex.cogt.templating.template_preprocessor import preprocess_template-from pipelex.core.bundle_resources.bundle_resource import BundleResourceReadStagefrom pipelex.core.method_trees.file_references import BundleFileOrigin, bundle_file_origin, file_reference_refusalfrom pipelex.core.pipes.variable_multiplicity import parse_concept_with_multiplicityfrom pipelex.pipe_machinery.pipe_blueprint import PipeBlueprint@@ -114,13 +113,10 @@ class PipeDocGenBlueprint(PipeBlueprint):@property@override- def bundle_resource_reads(self) -> dict[str, BundleResourceReadStage]:- # An HTML template is read and checked against the inputs when the method loads; an office template is read- # only when the step prints, or when a dry run hands it to the engine's checker.+ def named_file_references(self) -> set[str]:if self.template_file is None:- return {}- stage = BundleResourceReadStage.LOAD if self.format.is_template_html else BundleResourceReadStage.RUN- return {self.template_file: stage}+ return set()+ return {self.template_file}@overridedef validate_inputs(self):diff --git a/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.py b/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.pyindex d3108e087..9f3ab24bc 100644--- a/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.py+++ b/pipelex/pipe_operators/doc_gen/pipe_doc_gen_factory.py@@ -1,15 +1,13 @@-from collections.abc import Callable-from pathlib import Pathfrom typing import Anyfrom mthds.method_tree.exceptions import MethodTreeRefusedErrorfrom typing_extensions import override-from pipelex.core.bundle_resources.bundle_resource import BundleResourcefrom pipelex.core.concepts.native.concept_native import NativeConceptCodefrom pipelex.core.method_trees.building_bundle import get_building_tree_bundle-from pipelex.core.method_trees.file_references import reference_refusal_reason, resolve_bundle_file_reference-from pipelex.core.method_trees.tree_bundle import TreeBundle+from pipelex.core.method_trees.file_references import reference_refusal_reason, resolve_bundle_file_reference, resolve_crate_file_reference+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES+from pipelex.core.method_trees.tree_bundle import MethodFileRef, TreeBundle, TreeBundleReffrom pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecsfrom pipelex.core.pipes.stuff_spec.stuff_spec import StuffSpecfrom pipelex.interpreter_hub import get_concept_library, get_native_concept@@ -17,7 +15,6 @@ from pipelex.pipe_machinery.pipe_factory import PipeFactoryProtocolfrom pipelex.pipe_operators.doc_gen.exceptions import PipeDocGenFactoryErrorfrom pipelex.pipe_operators.doc_gen.pipe_doc_gen import PipeDocGenfrom pipelex.pipe_operators.doc_gen.pipe_doc_gen_blueprint import PipeDocGenBlueprint, template_required_roots-from pipelex.pipe_operators.doc_gen.template_file_resource import bundle_resource_of_template_filefrom pipelex.tools.jinja2.template_category import TemplateCategory@@ -44,29 +41,41 @@ class PipeDocGenFactory(PipeFactoryProtocol[PipeDocGenBlueprint, PipeDocGen]):)raise PipeDocGenFactoryError(msg)- template = blueprint.template- template_path: str | None = None+ template_file_ref: MethodFileRef | None = None+ template_file_text: str | None = Noneif blueprint.template_file is not None:- tree_bundle = get_building_tree_bundle()- read_template_bytes: Callable[[], bytes]- if tree_bundle is None:- # A bundle loaded from content strings reads only the files submitted with it, never this host's disk. An- # office template is read from them when the step prints, so the pipe keeps only its name, and the run- # carries the file in its crate.- read_template_bytes = cls._submitted_template_file(pipe_code=pipe_code, template_file=blueprint.template_file).inline_bytes- else:- # A bundle this host read from its disk finds its template file in its method tree, and never among- # submitted files.- resolved_path = cls._resolve_template_file(pipe_code=pipe_code, template_file=blueprint.template_file, tree_bundle=tree_bundle)- read_template_bytes = resolved_path.read_bytes- if not blueprint.format.is_template_html:- template_path = str(resolved_path)- if blueprint.format.is_template_html:- # An HTML template is read and checked now, from disk as from the submitted bytes, as written.- template = cls._html_template_file_text(pipe_code=pipe_code, template_file=blueprint.template_file, read_bytes=read_template_bytes)- cls._check_html_template_file(pipe_code=pipe_code, template=template, inputs=inputs, template_file=blueprint.template_file)+ template_file = blueprint.template_file+ match get_building_tree_bundle():+ case TreeBundle() as tree_bundle:+ # A bundle this process holds finds its template file in its method tree: read from this host's disk+ # as a member of the tree, or parsed from a content string at the root of the tree of the files+ # submitted with it.+ resolved_tree_path = cls._resolve_template_file(pipe_code=pipe_code, template_file=template_file, tree_bundle=tree_bundle)+ template_file_ref = MethodFileRef(tree_digest=tree_bundle.digest, tree_path=resolved_tree_path)+ if blueprint.format.is_template_html:+ # An HTML template file is read and checked now, as written, for the method's load; the print+ # stage reads it again, where the step prints.+ template_file_text = cls._html_template_file_text(+ pipe_code=pipe_code,+ template_file=template_file,+ data=cls._read_tree_file(tree_bundle=tree_bundle, tree_path=resolved_tree_path),+ )+ cls._check_html_template_file(pipe_code=pipe_code, template=template_file_text, inputs=inputs, template_file=template_file)+ case TreeBundleRef() as tree_bundle_ref:+ # A step built from a crate reads nothing: the crate names its tree by digest, and the host that+ # assembled it resolved the reference in the tree and checked the file. The print stage reads it.+ try:+ resolved_tree_path = resolve_crate_file_reference(reference=template_file, tree_bundle_ref=tree_bundle_ref)+ except MethodTreeRefusedError as exc:+ msg = (+ f"PipeDocGen '{pipe_code}' names the template file '{template_file}', which its method tree cannot give it. {exc.message}"+ )+ raise PipeDocGenFactoryError(msg) from exc+ template_file_ref = MethodFileRef(tree_digest=tree_bundle_ref.tree_digest, tree_path=resolved_tree_path)+ case None:+ raise PipeDocGenFactoryError(cls._unsubmitted_template_file_message(pipe_code=pipe_code, template_file=template_file))- return PipeDocGen(+ pipe_doc_gen = PipeDocGen(domain_code=domain_code,code=pipe_code,description=description,@@ -74,50 +83,67 @@ class PipeDocGenFactory(PipeFactoryProtocol[PipeDocGenBlueprint, PipeDocGen]):output=output,doc_gen_format=blueprint.format,doc_gen_choice=blueprint.model,- template=template,+ template=blueprint.template,template_file=blueprint.template_file,- template_path=template_path,+ template_file_ref=template_file_ref,filename=blueprint.filename,)+ if template_file_text is not None:+ pipe_doc_gen.hold_template_file_text(template_file_text=template_file_text)+ return pipe_doc_gen@classmethod- def _resolve_template_file(cls, *, pipe_code: str, template_file: str, tree_bundle: TreeBundle) -> Path:- """Where the template file lies on this host, resolved in the bundle's method tree.+ def _resolve_template_file(cls, *, pipe_code: str, template_file: str, tree_bundle: TreeBundle) -> str:+ """The tree path of the template file, resolved in the bundle's method tree.The file is the tree's file the reference names, resolved against the bundle's tree path, `..` included as longas it stays in the tree, by a lookup in the tree's set of tree paths: a file the membership rule keeps out of the- tree, or any file outside it, is refused, and its path is never opened. The messages name the template file as- the method does and files by their tree paths, never the host's path to them: the bundle a refusal is located in- already says which one, and a dependency's install path is not the caller's to read.+ tree, or any file outside it, is refused, and its path is never opened. Bundles parsed from content strings+ resolve it from the root of the tree of the files submitted with them. The messages name the template file as+ the method does and files by their tree paths, never the host's path to them: the bundle a refusal is located+ in already says which one, and a dependency's install path is not the caller's to read."""try:- resolved_tree_path = resolve_bundle_file_reference(reference=template_file, tree_bundle=tree_bundle)+ return resolve_bundle_file_reference(reference=template_file, tree_bundle=tree_bundle)except MethodTreeRefusedError as exc:+ if tree_bundle.tree_path is None:+ msg = cls._unsubmitted_template_file_message(pipe_code=pipe_code, template_file=template_file)+ raise PipeDocGenFactoryError(msg) from excreason = reference_refusal_reason(refusal_error=exc, tree_bundle=tree_bundle)msg = f"PipeDocGen '{pipe_code}' names the template file '{template_file}', which its method tree cannot give it. {reason}"raise PipeDocGenFactoryError(msg) from exc- return tree_bundle.tree.file_location(resolved_tree_path)++ @staticmethod+ def _unsubmitted_template_file_message(*, pipe_code: str, template_file: str) -> str:+ return (+ f"PipeDocGen '{pipe_code}' names the template file '{template_file}', which was not supplied with its "+ "bundle. A bundle loaded from content strings has no directory to find the file in, so the file must be "+ f"submitted with it, keyed by the same path, '{template_file}'. A bundle loaded from a folder "+ "finds it in its method tree."+ )@classmethod- def _submitted_template_file(cls, *, pipe_code: str, template_file: str) -> BundleResource:- """The template file submitted with a bundle loaded from content strings, which the current library holds."""- resource = bundle_resource_of_template_file(template_file=template_file)- if resource is None:- msg = (- f"PipeDocGen '{pipe_code}' names the template file '{template_file}', which was not supplied with its "- "bundle. A bundle loaded from content strings has no directory to find the file in, so the file must be "- f"submitted with it, keyed by the same path, '{template_file}'. A bundle loaded from a folder "- "finds it in its method tree."- )- raise PipeDocGenFactoryError(msg)- return resource+ def _read_tree_file(cls, *, tree_bundle: TreeBundle, tree_path: str) -> bytes | None:+ """The bytes of a file of the bundle's tree, as a library of this process holds the tree, checked against its hash.++ A tree a step is built in is always held: the library holds every tree it loads before it builds a pipe of one.+ None when the file's bytes are no longer the ones the tree's listing recorded, such as a file edited, removed or+ swapped for a link since: nothing is read from the disk past the hash check.+ """+ return LOCAL_METHOD_FILES.read_held_file(tree_digest=tree_bundle.tree.digest, tree_path=tree_path)@classmethod- def _html_template_file_text(cls, *, pipe_code: str, template_file: str, read_bytes: Callable[[], bytes]) -> str:+ def _html_template_file_text(cls, *, pipe_code: str, template_file: str, data: bytes | None) -> str:"""An HTML template file's text, decoded from its bytes as written, line endings included."""+ if data is None:+ msg = (+ f"PipeDocGen '{pipe_code}' could not read the template file '{template_file}' as its method tree listed it: "+ "the file changed or went missing since the tree was listed."+ )+ raise PipeDocGenFactoryError(msg)try:- return read_bytes().decode("utf-8")- except (OSError, UnicodeError) as exc:+ return data.decode("utf-8")+ except UnicodeError as exc:msg = f"PipeDocGen '{pipe_code}' could not read the template file '{template_file}' as UTF-8 text."raise PipeDocGenFactoryError(msg) from excdiff --git a/pipelex/pipe_operators/doc_gen/template_file_resource.py b/pipelex/pipe_operators/doc_gen/template_file_resource.pydeleted file mode 100644index 659e52128..000000000--- a/pipelex/pipe_operators/doc_gen/template_file_resource.py+++ /dev/null@@ -1,15 +0,0 @@-from pipelex.core.bundle_resources.bundle_resource import BundleResource, canonical_resource_path_or_none-from pipelex.interpreter_hub import get_library---def bundle_resource_of_template_file(*, template_file: str) -> BundleResource | None:- """The file submitted with the bundle under the path a step's `template_file` names, or None when none was.-- Looked up in the current library, which holds the files submitted with the bundles it loaded from content strings- and the ones a transported crate carries: the factory reads an HTML template from it when the step is built, and- the step reads an office template from it when it composes, so the run's own copy is the one it prints.- """- canonical_path = canonical_resource_path_or_none(path=template_file)- if canonical_path is None:- return None- return get_library().bundle_resources.get(canonical_path)diff --git a/pipelex/pipe_operators/doc_gen/template_file_stage.py b/pipelex/pipe_operators/doc_gen/template_file_stage.pynew file mode 100644index 000000000..feabc51bb--- /dev/null+++ b/pipelex/pipe_operators/doc_gen/template_file_stage.py@@ -0,0 +1,209 @@+"""The interpreter's part in a `PipeDocGen` print from a template file, installed on the runtime hub at boot.++The print stage, a kernel-layer leaf, reads the template file through the method file store and hands this stage what+needs the method itself (`pipelex.cogt.doc_gen.template_file_stage`):++- an HTML template file is rendered with the step's data as the compose stage of a `PipeCompose` renders an HTML+ template, with the whole stack, its filters included: the stuffs the step's inputs name are typed again by the+ concepts of the run's library crate, in the run's own library when this process holds it, such as in a local run, and+ otherwise, such as in an activity on a worker, in a library loaded from those concepts alone, which this process keeps+ for the prints that follow (`RenderLibraryCache`);+- the findings of the engine's check of an office template file, at a dry print, fail the step when one is an error,+ and join the validation verdict's warnings otherwise, or the log when no validation collects them.+"""++import threading+import uuid+from collections import OrderedDict+from collections.abc import Generator+from contextlib import contextmanager+from typing import NamedTuple++from typing_extensions import override++from pipelex import log+from pipelex.base_exceptions import ValidationErrorCategory, ValidationErrorItem+from pipelex.cogt.doc_gen.document_composition import ComposedTemplateFile, TemplateRenderContext+from pipelex.cogt.doc_gen.template_check import TemplateFinding+from pipelex.cogt.doc_gen.template_file_stage import TemplateFileStageProtocol+from pipelex.core.qualified_ref import QualifiedRef+from pipelex.interpreter_hub import get_current_library_id_or_none, get_library_manager, scoped_current_library+from pipelex.kernel.compose_ops import build_compose_context+from pipelex.kernel.templating_style_ops import resolve_templating_style+from pipelex.libraries.library_crate import LibraryCrate+from pipelex.pipe_operators.doc_gen.doc_gen_rendering import render_doc_gen_template+from pipelex.pipe_operators.doc_gen.exceptions import PipeDocGenRunError, PipeDocGenTemplateCheckError+from pipelex.pipe_run.dry_run_warning_collector import report_dry_run_warning+from pipelex.runtime_bridge.primitives.hydration import hydrate_working_memory+from pipelex.tools.jinja2.template_category import TemplateCategory+from pipelex.validation_error_types import TemplateCheckErrorType++_RENDER_LIBRARY_PREFIX = "doc_gen_template_render"+# How many libraries typing the data of HTML template files this process keeps once no print uses them: one per set of+# concepts, so a worker printing for a handful of methods loads each one's concepts once, and one printing for many+# keeps the ones it used last. A library a print is using is never torn down, however many there are.+_RENDER_LIBRARY_CAPACITY = 8+++class _RenderLibrary(NamedTuple):+ library_id: str+ users: int+++class RenderLibraryCache:+ """The libraries this process loaded from the concepts of a run's crate to type the data of HTML template files, by fingerprint.++ Loading a crate builds its concepts' classes, which costs more than the render, so a library is kept after its print+ for the next print typing data with the same concepts, such as the next document of the same method. Libraries no+ print is using are torn down beyond the capacity, the least recently used first. A library torn down by someone else,+ such as by the library manager's teardown of every library, is loaded again.+ """++ def __init__(self, *, capacity: int) -> None:+ self._capacity = capacity+ self._lock = threading.Lock()+ self._libraries: OrderedDict[str, _RenderLibrary] = OrderedDict()++ @contextmanager+ def library_for(self, *, concepts_crate: LibraryCrate) -> Generator[str, None, None]:+ """A library holding the crate's concepts, held for the block, the one kept for its fingerprint or one loaded for it."""+ library_id = self._acquire(concepts_crate=concepts_crate)+ try:+ yield library_id+ finally:+ self._release(fingerprint=concepts_crate.fingerprint)++ def held_library_ids(self) -> list[str]:+ """The libraries kept, in use or not, the least recently used first."""+ with self._lock:+ return [render_library.library_id for render_library in self._libraries.values()]++ def release_idle(self) -> None:+ """Tear down every library kept that no print is using."""+ with self._lock:+ idle = [fingerprint for fingerprint, render_library in self._libraries.items() if render_library.users <= 0]+ to_tear_down = [self._libraries.pop(fingerprint).library_id for fingerprint in idle]+ for library_id in to_tear_down:+ get_library_manager().teardown(library_id=library_id)++ def _acquire(self, *, concepts_crate: LibraryCrate) -> str:+ library_manager = get_library_manager()+ fingerprint = concepts_crate.fingerprint+ with self._lock:+ kept = self._libraries.get(fingerprint)+ if kept is not None and library_manager.is_crate_loaded(library_id=kept.library_id, fingerprint=fingerprint):+ self._libraries[fingerprint] = kept._replace(users=kept.users + 1)+ self._libraries.move_to_end(fingerprint)+ return kept.library_id+ library_id, _ = library_manager.open_library(library_id=f"{_RENDER_LIBRARY_PREFIX}_{uuid.uuid4().hex}")+ try:+ # The crate's concepts were validated where the run's method was loaded.+ library_manager.load_from_crate(library_id=library_id, crate=concepts_crate, is_crate_prevalidated=True)+ except BaseException:+ library_manager.teardown(library_id=library_id)+ raise+ # A library kept under this fingerprint and torn down by someone else is replaced.+ self._libraries[fingerprint] = _RenderLibrary(library_id=library_id, users=1)+ self._libraries.move_to_end(fingerprint)+ return library_id++ def _release(self, *, fingerprint: str) -> None:+ to_tear_down: list[str] = []+ with self._lock:+ kept = self._libraries.get(fingerprint)+ if kept is not None:+ self._libraries[fingerprint] = kept._replace(users=kept.users - 1)+ idle = [kept_fingerprint for kept_fingerprint, render_library in self._libraries.items() if render_library.users <= 0]+ for kept_fingerprint in idle[: max(0, len(idle) - self._capacity)]:+ to_tear_down.append(self._libraries.pop(kept_fingerprint).library_id)+ for library_id in to_tear_down:+ get_library_manager().teardown(library_id=library_id)+++#: The libraries this process keeps to type the data of HTML template files.+RENDER_LIBRARIES = RenderLibraryCache(capacity=_RENDER_LIBRARY_CAPACITY)+++@contextmanager+def _library_typing(*, render_context: TemplateRenderContext) -> Generator[None, None, None]:+ """Make current a library whose concepts type the step's data: the run's own when current, or one holding its concepts.++ The current library is the run's own in the process that loaded the run's method, so its concepts' classes are the+ ones the step's data was built with. Anywhere else, such as in an activity on a worker, the data is typed in a library+ loaded from the run's concepts alone, which reads no file, and which this process keeps for the prints that follow.+ """+ library_manager = get_library_manager()+ current_library_id = get_current_library_id_or_none()+ if current_library_id is not None and library_manager.is_crate_loaded(+ library_id=current_library_id, fingerprint=render_context.crate_fingerprint+ ):+ yield+ return+ concepts_crate = LibraryCrate.model_validate(render_context.concepts_crate)+ with RENDER_LIBRARIES.library_for(concepts_crate=concepts_crate) as library_id, scoped_current_library(library_id=library_id):+ yield+++def _step_codes(*, template_file: ComposedTemplateFile) -> tuple[str | None, str]:+ """The domain and the code of the step naming the template file."""+ parsed = QualifiedRef.parse_pipe_ref(raw=template_file.pipe_ref)+ return parsed.domain_path, parsed.local_code+++class DocGenTemplateFileStage(TemplateFileStageProtocol):+ """Renders an HTML template file with its step's data, and reports the findings of an office template's check."""++ @override+ async def render_html_template_file(self, *, template_file: ComposedTemplateFile, template_source: str) -> str:+ _domain_code, pipe_code = _step_codes(template_file=template_file)+ render_context = template_file.render_context+ if render_context is None:+ msg = f"PipeDocGen '{pipe_code}' names the template file '{template_file.name}' with nothing to render it with."+ raise PipeDocGenRunError(msg)+ with _library_typing(render_context=render_context):+ working_memory = hydrate_working_memory(render_context.working_memory_raw)+ context = build_compose_context(memory=working_memory, runtime_params=render_context.runtime_params)+ return await render_doc_gen_template(+ pipe_code=pipe_code,+ template=template_source,+ category=TemplateCategory.HTML,+ context=context,+ label=f"template file '{template_file.name}'",+ templating_style=resolve_templating_style(authored=None),+ )++ @override+ def report_template_findings(self, *, template_file: ComposedTemplateFile, findings: list[TemplateFinding]) -> None:+ domain_code, pipe_code = _step_codes(template_file=template_file)+ for finding in findings:+ if not finding.severity.is_error:+ _report_template_warning(domain_code=domain_code, pipe_code=pipe_code, template_file=template_file.name, finding=finding)+ errors = [finding for finding in findings if finding.severity.is_error]+ if errors:+ listed = "\n".join(f"- {finding.message}" + (f" ({finding.location})" if finding.location else "") for finding in errors)+ msg = f"PipeDocGen '{pipe_code}': the template file '{template_file.name}' does not fit the step's inputs:\n{listed}"+ raise PipeDocGenTemplateCheckError(msg)+++def _report_template_warning(*, domain_code: str | None, pipe_code: str, template_file: str, finding: TemplateFinding) -> None:+ """Report a warning of the template check as an advisory item, located at its step, its file and the place in it.++ An engine that answers an empty location names no place, so the item's `template_location` is left unset.+ """+ location = finding.location or None+ location_suffix = f" ({location})" if location is not None else ""+ warning = ValidationErrorItem(+ category=ValidationErrorCategory.DRY_RUN,+ error_type=TemplateCheckErrorType.TEMPLATE_CHECK_WARNING,+ pipe_code=pipe_code,+ domain_code=domain_code,+ template_file=template_file,+ template_location=location,+ message=f"PipeDocGen '{pipe_code}', template file '{template_file}': {finding.message}{location_suffix}",+ )+ if report_dry_run_warning(warning=warning):+ return+ finding_fields: dict[str, str] = {"pipe_code": pipe_code, "template_file": template_file, "finding_message": finding.message}+ if location is not None:+ finding_fields["finding_location"] = location+ log.warning("The template check of a PipeDocGen found a warning in its template file", fields=finding_fields)diff --git a/pipelex/pipe_operators/func/direct_pipe_func_executor.py b/pipelex/pipe_operators/func/direct_pipe_func_executor.pyindex 8d0a4e8a6..e43ba053f 100644--- a/pipelex/pipe_operators/func/direct_pipe_func_executor.py+++ b/pipelex/pipe_operators/func/direct_pipe_func_executor.py@@ -4,6 +4,7 @@ import tempfilefrom pathlib import Pathfrom mthds.method_tree.exceptions import MethodTreeRefusedError, TreeSourceError+from mthds.method_tree.models import MethodTreefrom mthds.method_tree.written_tree import read_written_treefrom typing_extensions import override@@ -18,6 +19,7 @@ from pipelex.core.stuffs.stuff_factory import StuffFactoryfrom pipelex.interpreter_hub import get_library_manager, get_required_pipefrom pipelex.kernel.func_ops import call_functionfrom pipelex.libraries.library_crate import LibraryCrate+from pipelex.libraries.pipe_func_call_files import read_pipe_func_call_filesfrom pipelex.pipe_operators.func.exceptions import PipeFuncExecutionErrorfrom pipelex.pipe_operators.func.pipe_func import PipeFuncfrom pipelex.pipe_operators.func.pipe_func_call_context import function_of_call_in_flight@@ -29,7 +31,7 @@ from pipelex.system.job_metadata import JobMetadata# The library id the transported run rebuilds under. Internal to one process (a fresh sandbox box or a# one-shot subprocess), so a fixed id is safe — there is no other library to collide with.-_TRANSPORTED_LIBRARY_ID = "pipe_func_transported_lib"+TRANSPORTED_LIBRARY_ID = "pipe_func_transported_lib"def resolve_pipe_func(*, pipe_code: str) -> PipeFunc:@@ -87,7 +89,7 @@ class DirectPipeFuncExecutor(PipeFuncExecutorProtocol):@overrideasync def run_pipe_func_transported(self, *, request: PipeFuncExecutionRequest) -> PipeFuncExecutionResponse:- """Write the call's files, rebuild the library + memory, run the one PipeFunc, transport the output.+ """Read and write the call's files, rebuild the library + memory, run the one PipeFunc, transport the output.The far-from-caller half of out-of-process execution, and the single source of truth for it: asandbox box runs exactly this (its entrypoint is a thin shell over this call), and it pulls in@@ -96,28 +98,33 @@ class DirectPipeFuncExecutor(PipeFuncExecutorProtocol):isolation boundary. The output rides back wrapped in a working memory so it round-trips with itsconcept (and thus its dynamic-class identity), rebound against the receiver's registry.- The call's files are written into a fresh temporary directory, removed on every path.+ The call's files are read through the method file store under the run's read scope, which this process must+ reach, and written into a fresh temporary directory, removed on every path. A sandbox, which reaches no store,+ receives them from its client instead, unpacked into the directory `run_pipe_func_transported_at` runs in."""# Resolved, so the root the hold puts on sys.path is the one the import system reports for its modules# (`/var` is `/private/var` on macOS).tree_root = Path(tempfile.mkdtemp(prefix="pipelex_pipe_func_")).resolve()try:+ if request.tree_digest is not None:+ call_files = await read_pipe_func_call_files(tree_digest=request.tree_digest, read_scope=request.job_metadata.run_metadata.read_scope)+ write_call_files(files=call_files, destination=tree_root)return await self.run_pipe_func_transported_at(request=request, tree_root=tree_root)finally:shutil.rmtree(tree_root, ignore_errors=True)async def run_pipe_func_transported_at(self, *, request: PipeFuncExecutionRequest, tree_root: Path) -> PipeFuncExecutionResponse:- """Run a transported call with its Python root at `tree_root`, a directory the caller may have filled already.+ """Run a transported call with its Python root at `tree_root`, a directory holding the files of the call's tree.- A sandbox client may unpack the call's tree into the sandbox itself, such as from one archive per call, and hand- the directory over; the files the request carries are written there too, at their tree paths. The directory is- the call's import root: it goes first on `sys.path` under the process's hold on its Python, and the function is- imported from it under its real import path.+ The caller wrote the files of the tree the request names there, every one but the `.mthds` files, at their tree+ paths (`read_pipe_func_call_files`, `write_call_files`): a sandbox client unpacks them into the sandbox itself,+ such as from one archive per call, and hands the directory over. The directory is the call's import root: it goes+ first on `sys.path` under the process's hold on its Python, and the function is imported from it under its real+ import path.Raises:PipeFuncExecutionError: The call's files cannot be read back as a tree, or the function runs past its timeout."""- write_call_files(files=request.files, destination=tree_root)self._write_generated_structures(crate=request.crate, tree_root=tree_root)try:tree = read_written_tree(tree_root)@@ -127,11 +134,14 @@ class DirectPipeFuncExecutor(PipeFuncExecutorProtocol):# The call's Python is held for the transported library until the run ends, and unloaded before its directory# is removed.- TREE_PYTHON_HOLD.acquire(tree=tree, holder=_TRANSPORTED_LIBRARY_ID, label=f"the method tree of the call to '{request.pipe_code}'")+ TREE_PYTHON_HOLD.acquire(tree=tree, holder=TRANSPORTED_LIBRARY_ID, label=f"the method tree of the call to '{request.pipe_code}'")try:- return await self._run_transported(request=request, crate=self._crate_rooted_at(request=request, tree_json=tree.model_dump_json()))+ # The step called, and it alone, is built in the tree written here, which holds none of its tree's bundles:+ # every other step, a sibling of the same tree included, names its tree by the digest the crate names it by.+ written_pipe_trees = {request.pipe_code: tree} if request.tree_digest is not None else {}+ return await self._run_transported(request=request, written_pipe_trees=written_pipe_trees)finally:- TREE_PYTHON_HOLD.release(holder=_TRANSPORTED_LIBRARY_ID)+ TREE_PYTHON_HOLD.release(holder=TRANSPORTED_LIBRARY_ID)TREE_PYTHON_HOLD.unload_if_unheld()@staticmethod@@ -160,31 +170,15 @@ class DirectPipeFuncExecutor(PipeFuncExecutorProtocol):generated_target.parent.mkdir(parents=True, exist_ok=True)generated_target.write_text(emitted.content, encoding="utf-8")- @staticmethod- def _crate_rooted_at(*, request: PipeFuncExecutionRequest, tree_json: str) -> LibraryCrate:- """The request's crate with the called step's method tree replaced by the tree written here.-- A step read from a tree resolves its function, and any file its tree's other steps name, in that tree, which the- crate carries as the host that assembled it listed it; here the tree is the call's files as written in this- process. A step parsed from a content string has no tree, and imports from this process's import path, which- the hold starts with the call's root.- """- crate = request.crate- tree_bundle_ref = crate.tree_bundles.get(request.pipe_code)- if tree_bundle_ref is None:- return crate- method_trees = dict(crate.method_trees)- method_trees[tree_bundle_ref.tree_key] = tree_json- return crate.model_copy(update={"method_trees": method_trees})-- async def _run_transported(self, *, request: PipeFuncExecutionRequest, crate: LibraryCrate) -> PipeFuncExecutionResponse:- # The crate was validated where it was assembled; its other steps may name files of trees this process never- # receives, so it is loaded as it is, and the one step called checks its function as it binds it.+ async def _run_transported(self, *, request: PipeFuncExecutionRequest, written_pipe_trees: dict[str, MethodTree]) -> PipeFuncExecutionResponse:+ # The crate was validated where it was assembled; its other steps name trees this process never receives, so it+ # is loaded as it is, and the one step called checks its function as it binds it.working_memory = rehydrate_library_and_memory(- library_id=_TRANSPORTED_LIBRARY_ID,- crate=crate,+ library_id=TRANSPORTED_LIBRARY_ID,+ crate=request.crate,working_memory_raw=request.working_memory_raw,is_crate_prevalidated=True,+ written_pipe_trees=written_pipe_trees,)if working_memory is None:msg = f"Transported rehydration produced no working memory for pipe '{request.pipe_code}'"@@ -217,7 +211,7 @@ class DirectPipeFuncExecutor(PipeFuncExecutorProtocol):raise PipeFuncExecutionError(msg) from exc# Wrap the output in a memory so it round-trips with its concept (and thus its class identity).- pipe = get_library_manager().get_library(library_id=_TRANSPORTED_LIBRARY_ID).pipe_library.get_required_pipe(pipe_code=request.pipe_code)+ pipe = get_library_manager().get_library(library_id=TRANSPORTED_LIBRARY_ID).pipe_library.get_required_pipe(pipe_code=request.pipe_code)output_stuff = StuffFactory.make_stuff(concept=pipe.output.concept, content=execution_result.content)working_memory.set_new_main_stuff(stuff=output_stuff)diff --git a/pipelex/pipe_operators/func/pipe_func.py b/pipelex/pipe_operators/func/pipe_func.pyindex ef0695f43..c3a56bd9e 100644--- a/pipelex/pipe_operators/func/pipe_func.py+++ b/pipelex/pipe_operators/func/pipe_func.py@@ -1,7 +1,9 @@from collections.abc import Callablefrom contextlib import nullcontext+from pathlib import Pathfrom typing import Any, Literal, cast, get_args, get_origin, get_type_hints+from mthds.method_tree.models import MethodTreefrom mthds.method_tree.tree_path import nfcfrom pydantic import PrivateAttr, field_validatorfrom typing_extensions import override@@ -12,8 +14,10 @@ from pipelex.core.concepts.concept_factory import ConceptFactoryfrom pipelex.core.memory.exceptions import WorkingMemoryStuffNotFoundErrorfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactory+from pipelex.core.method_trees.building_bundle import BuildingBundlefrom pipelex.core.method_trees.exceptions import TreePythonError-from pipelex.core.method_trees.tree_bundle import TreeBundle+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES+from pipelex.core.method_trees.tree_bundle import TreeBundle, TreeBundleReffrom pipelex.core.method_trees.tree_python import check_tree_module_names, top_level_module_names, tree_label_holdingfrom pipelex.core.pipes.exceptions import PipeRunError, PipeValidationErrorfrom pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecs, TypedNamedStuffSpec@@ -21,9 +25,8 @@ from pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.core.stuffs.list_content import ListContentfrom pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.core.stuffs.stuff_factory import StuffFactory-from pipelex.interpreter_hub import get_current_library_id_or_none, get_library_manager, get_pipe_func_executor+from pipelex.interpreter_hub import get_current_library_id_or_none, get_pipe_func_executorfrom pipelex.kernel.memory_ops import store_result-from pipelex.libraries.library_crate import SUBMITTED_PYTHON_ROOT_KEYfrom pipelex.pipe_operators.func.exceptions import PipeFuncFunctionErrorfrom pipelex.pipe_operators.func.function_name import function_name_form_violationfrom pipelex.pipe_operators.func.pipe_func_call_context import pipe_func_call_in_flight@@ -56,16 +59,17 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):The function is located and its form proven at validation, without running Python; it is imported, and its callingconvention and return type checked, when the step first runs, dry or live. In `direct` mode it is imported inthis process, under the process's hold on the tree's Python; in a sandbox-hosted mode it never is, and the call- travels to the sandbox with the tree's files. See `pipe_func_python` for where a `function_name` resolves.+ names the tree by its digest, the files being read where the call runs. See `pipe_func_python` for where a+ `function_name` resolves."""type: Literal["PipeFunc"] = "PipeFunc"function_name: str- # The member of its method tree the step's bundle was read as, which the function's import path resolves in; None- # for a bundle parsed from a content string. Set by the factory, never serialized: a pipe is rebuilt from its- # blueprint wherever it travels, and the crate carries the tree.- _tree_bundle: TreeBundle | None = PrivateAttr(default=None)+ # Where the step's bundle lies, which the function's import path resolves in: a tree this process holds, a tree a+ # crate names by digest, or None for a bundle parsed from a content string with no file submitted beside it. Set+ # by the factory, never serialized: a pipe is rebuilt from its blueprint wherever it travels.+ _tree_bundle: BuildingBundle = PrivateAttr(default=None)# The function once imported and checked, with the holder its import was made for._bound_function: tuple[str, Callable[..., Any]] | None = PrivateAttr(default=None)# Whether validation located the function and proved its form, which a dependency package's step, validated as it is@@ -91,12 +95,12 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):raise ValueError(violation)return nfc(function_name)- def place_in_tree(self, *, tree_bundle: TreeBundle | None) -> None:- """Record the member of its method tree the step's bundle was read as, or None for a bundle parsed from a string."""+ def place_in_tree(self, *, tree_bundle: BuildingBundle) -> None:+ """Record where the step's bundle lies, as `BuildingBundle` describes it."""self._tree_bundle = tree_bundle@property- def tree_bundle(self) -> TreeBundle | None:+ def tree_bundle(self) -> BuildingBundle:return self._tree_bundle@override@@ -138,54 +142,62 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):"""Locate the module where the step's import root puts it, prove the function's form, and check the tree's module names.A sandbox-hosted deployment imports the function in a sandbox, whose packages are not this process's, so there- a module name is checked against the standard library only.+ a module name is checked against the standard library only. A step built from a crate that names its tree by+ digest alone is not checked again: its tree holds no file here, and the host that assembled the crate proved the+ function before the run was dispatched.Raises:PipeFuncFunctionError: The module is not found, or the form is not proven.TreeModuleShadowingError: A top-level module of the tree, or of the submitted Python, would shadow another."""- library_id = get_current_library_id_or_none()imports_in_this_process = not is_pipe_func_sandbox_hosted()- tree_bundle = self._tree_bundlemodule_source: PipeFuncModuleSource- if tree_bundle is not None:- tree = tree_bundle.tree- # A crate loaded on another host carries the tree's files when its library captured them; the tree's- # directory is then the host that listed it, so the files are read in place of the disk.- captured = (- get_library_manager().get_pipe_func_files(library_id=library_id, root_key=tree_bundle.tree_key) if library_id is not None else None- )- try:- module_source = locate_in_tree(function_name=self.function_name, tree=tree, files=captured)- except OSError as exc:- msg = f"The module of the function_name '{self.function_name}' cannot be read from the method tree on this host."- raise PipeFuncFunctionError(msg) from exc- check_pipe_func_definition(module_source=module_source)- on_disk = captured is None and tree.directory is not None- check_tree_module_names(- top_level_modules=top_level_module_names(tree_paths=captured.keys() if captured is not None else tree.members),- # Named by the bundle it holds, never by its directory, which is a path on this host.- tree_label=tree_label_holding(tree_path=tree_bundle.tree_path),- root=tree.directory.resolve() if on_disk and tree.directory is not None else None,- checks_this_process=imports_in_this_process,- )- elif not imports_in_this_process:- submitted = (- get_library_manager().get_pipe_func_files(library_id=library_id, root_key=SUBMITTED_PYTHON_ROOT_KEY)- if library_id is not None- else None- )- module_source = locate_in_files(function_name=self.function_name, files=submitted or {})- check_pipe_func_definition(module_source=module_source)- check_tree_module_names(- top_level_modules=top_level_module_names(tree_paths=(submitted or {}).keys()),- tree_label="the Python submitted with the method",- root=None,- checks_this_process=False,- )- else:- module_source = locate_on_import_path(function_name=self.function_name)- check_pipe_func_definition(module_source=module_source)+ match self._tree_bundle:+ case TreeBundleRef():+ return+ case TreeBundle(tree=MethodTree(directory=Path() as tree_directory)) as tree_bundle:+ tree = tree_bundle.tree+ try:+ module_source = locate_in_tree(function_name=self.function_name, tree=tree)+ except OSError as exc:+ msg = f"The module of the function_name '{self.function_name}' cannot be read from the method tree on this host."+ raise PipeFuncFunctionError(msg) from exc+ check_pipe_func_definition(module_source=module_source)+ check_tree_module_names(+ top_level_modules=top_level_module_names(tree_paths=tree.members),+ # Named by the bundle it holds, never by its directory, which is a path on this host.+ tree_label=self._tree_label(tree_bundle=tree_bundle),+ root=tree_directory.resolve(),+ checks_this_process=imports_in_this_process,+ )+ case TreeBundle() as tree_bundle if not imports_in_this_process:+ # The files submitted with bundles parsed from content strings, which this process holds in memory: a+ # sandbox imports the function from them.+ tree = tree_bundle.tree+ module_source = locate_in_files(function_name=self.function_name, files=_held_files_of(tree_bundle=tree_bundle))+ check_pipe_func_definition(module_source=module_source)+ check_tree_module_names(+ top_level_modules=top_level_module_names(tree_paths=tree.members),+ tree_label=self._tree_label(tree_bundle=tree_bundle),+ root=None,+ checks_this_process=False,+ )+ case None if not imports_in_this_process:+ # No file was submitted with the bundle, so a sandbox would have no module to import.+ module_source = locate_in_files(function_name=self.function_name, files={})+ check_pipe_func_definition(module_source=module_source)+ case TreeBundle() | None:+ # A bundle parsed from a content string imports its function from this process's import path, where+ # the library directories loaded beside it put their Python.+ module_source = locate_on_import_path(function_name=self.function_name)+ check_pipe_func_definition(module_source=module_source)++ @staticmethod+ def _tree_label(*, tree_bundle: TreeBundle) -> str:+ """How a message names the step's tree: by the bundle it holds, or as the submitted Python for content strings."""+ if tree_bundle.tree_path is None:+ return "the Python submitted with the method"+ return tree_label_holding(tree_path=tree_bundle.tree_path)def bind_function(self) -> Callable[..., Any]:"""Import the function in this process and check it, once per holder: the `direct` mode's way to reach it.@@ -202,15 +214,23 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):if bound is not None and bound[0] == holder:return bound[1]function: Callable[..., Any]- if self._tree_bundle is not None:- function = bind_tree_function(- function_name=self.function_name,- tree=self._tree_bundle.tree,- holder=holder,- tree_label=tree_label_holding(tree_path=self._tree_bundle.tree_path),- )- else:- function = bind_import_path_function(function_name=self.function_name)+ match self._tree_bundle:+ case TreeBundle(tree=MethodTree(directory=Path())) as tree_bundle:+ function = bind_tree_function(+ function_name=self.function_name,+ tree=tree_bundle.tree,+ holder=holder,+ tree_label=self._tree_label(tree_bundle=tree_bundle),+ )+ case TreeBundleRef() as tree_bundle_ref:+ msg = (+ f"The method tree '{tree_bundle_ref.tree_digest}' holding this step was named by a crate and is not on "+ "this host, so its function cannot be imported here: run the step where its tree's files are written."+ )+ raise PipeFuncFunctionError(msg)+ case TreeBundle() | None:+ # A bundle parsed from a content string imports its function from this process's import path.+ function = bind_import_path_function(function_name=self.function_name)self._check_return_type(function=function)self._bound_function = (holder, function)return function@@ -485,3 +505,21 @@ class PipeFunc(PipeOperator[PipeFuncOutput]):self, *, job_metadata: JobMetadata, working_memory: WorkingMemory, pipe_run_params: PipeRunParams, output_name: str | None = None):pass+++def _held_files_of(*, tree_bundle: TreeBundle) -> dict[str, bytes]:+ """The Python files of a tree this process assembled in memory, read from the local method file store.++ Raises:+ PipeFuncFunctionError: The store no longer holds one of the tree's files.+ """+ files: dict[str, bytes] = {}+ for tree_path in tree_bundle.tree.tree_paths:+ if not tree_path.endswith(".py"):+ continue+ data = LOCAL_METHOD_FILES.read_held_file(tree_digest=tree_bundle.tree.digest, tree_path=tree_path)+ if data is None:+ msg = f"The file '{tree_path}' submitted with the method is no longer held by this process."+ raise PipeFuncFunctionError(msg)+ files[tree_path] = data+ return filesdiff --git a/pipelex/pipe_operators/func/pipe_func_execution_dtos.py b/pipelex/pipe_operators/func/pipe_func_execution_dtos.pyindex 505297d85..c21b639d5 100644--- a/pipelex/pipe_operators/func/pipe_func_execution_dtos.py+++ b/pipelex/pipe_operators/func/pipe_func_execution_dtos.py@@ -2,7 +2,6 @@ from typing import Anyfrom pydantic import BaseModel, ConfigDict, Field-from pipelex.core.method_trees.tree_files import TreeFileEntryfrom pipelex.libraries.library_crate import LibraryCratefrom pipelex.pipe_run.pipe_run_params import PipeRunParamsfrom pipelex.system.job_metadata import JobMetadata@@ -26,25 +25,25 @@ class PipeFuncExecutionRequest(BaseModel):The generic transport primitive for out-of-process PipeFunc execution — sibling to theruntime-bridge serialization, carrying only open pipelex types. A backend (a sandbox box, a localsubprocess) runs it and returns a ``PipeFuncExecutionResponse``; a host runtime (a Temporal- activity) forwards it across its boundary. Carries the crate (the method, without the files of its- PipeFunc calls), the call's files (``files``, the Python root of the step called), the transported+ activity) forwards it across its boundary. Carries the crate (the method, naming its trees by digest and+ carrying none of their files), the digest of the called step's tree (``tree_digest``), the transportedworking memory (the function's inputs), and the identity of the pipe/function to run. Deliberately- carries NO secrets.+ carries NO secrets, and no file's bytes: whoever runs the call reads the tree's files through the method+ file store, where IO is allowed, never in a workflow."""model_config = ConfigDict(extra="forbid")crate: LibraryCrate- files: dict[str, TreeFileEntry] = Field(- default_factory=dict,+ tree_digest: str | None = Field(+ default=None,description=(- "The files of the called step's Python root, by tree path, written where the call runs before the function is "- "imported: every file of the step's method tree except its .mthds files, or for a step parsed from a content "- "string, the files submitted beside it. Each is a file entry of the MTHDS standard, its text or {'base64': ...}. "- "The root goes first on sys.path and the function is imported by its import path from there, so it imports "- "its sibling modules and reads a file beside its module as it does locally. A sandbox client may move them "- "out of the request and unpack them itself, such as from one archive per call, and hand the directory to the "- "entrypoint."+ "The digest of the method tree the called step belongs to, whose files, every one but its .mthds files, are "+ "written at the call's import root before the function is imported, so it imports its sibling modules and "+ "reads a file beside its module as it does locally. For a step parsed from a content string, the tree of the "+ "files submitted beside it; None when none was. The process that runs the call reads them through the method "+ "file store under the run's read scope (`read_pipe_func_call_files`); a sandbox client reads them there and "+ "hands the sandbox the directory it unpacked them into."),)working_memory_raw: dict[str, Any]diff --git a/pipelex/pipe_operators/func/pipe_func_execution_transport.py b/pipelex/pipe_operators/func/pipe_func_execution_transport.pyindex 84028034e..6728766fc 100644--- a/pipelex/pipe_operators/func/pipe_func_execution_transport.py+++ b/pipelex/pipe_operators/func/pipe_func_execution_transport.py@@ -1,6 +1,5 @@from pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.interpreter_hub import get_current_library, get_library_manager-from pipelex.libraries.library_crate import SUBMITTED_PYTHON_ROOT_KEYfrom pipelex.pipe_operators.func.exceptions import PipeFuncTransportErrorfrom pipelex.pipe_operators.func.pipe_func_execution_dtos import (DEFAULT_PIPE_FUNC_TIMEOUT_SECONDS,@@ -27,7 +26,7 @@ def build_pipe_func_execution_request(pipe_run_params: PipeRunParams,timeout_seconds: float = DEFAULT_PIPE_FUNC_TIMEOUT_SECONDS,) -> PipeFuncExecutionRequest:- """Package one PipeFunc call for out-of-process execution: the current library's crate, the call's files, and the transported inputs.+ """Package one PipeFunc call for out-of-process execution: the current library's crate, the call's tree, and the transported inputs.Shared by every out-of-process executor — the in-process sandbox one and the Temporal in-workflowone — so the request shape is defined once. Reads the crate from the current library via the@@ -44,20 +43,15 @@ def build_pipe_func_execution_request(library_id = get_current_library()crate = get_library_manager().get_crate(library_id=library_id)if crate is None:- msg = (- f"Cannot run PipeFunc '{function_name}' out-of-process: no crate is available for the current library "- f"'{library_id}'. The library must be loaded in sandbox-hosted mode so the customer files travel on the crate."- )+ msg = f"Cannot run PipeFunc '{function_name}' out-of-process: no crate is available for the current library '{library_id}'."raise PipeFuncTransportError(msg)- # The call carries its own Python root's files and no other: the files of the method tree its step was read from,- # or the files submitted beside the bundles parsed from content strings. The crate travels without them.+ # The call names its own Python root by digest: the method tree its step was read from, or the tree of the files+ # submitted beside the bundles parsed from content strings. No file's bytes travel with it.tree_bundle_ref = crate.tree_bundles.get(pipe_code)- root_key = tree_bundle_ref.tree_key if tree_bundle_ref is not None else SUBMITTED_PYTHON_ROOT_KEY- call_files = crate.pipe_func_files.get(root_key, {})return PipeFuncExecutionRequest(- crate=crate.model_copy(update={"pipe_func_files": {}}),- files=dict(call_files),+ crate=crate,+ tree_digest=tree_bundle_ref.tree_digest if tree_bundle_ref is not None else None,working_memory_raw=working_memory.dump_for_transport(),pipe_code=pipe_code,function_name=function_name,diff --git a/pipelex/pipe_operators/func/pipe_func_python.py b/pipelex/pipe_operators/func/pipe_func_python.pyindex 59231ecf3..0816a55ff 100644--- a/pipelex/pipe_operators/func/pipe_func_python.py+++ b/pipelex/pipe_operators/func/pipe_func_python.py@@ -32,7 +32,6 @@ from mthds.method_tree.exceptions import MethodTreeRefusedErrorfrom mthds.method_tree.models import MethodTreefrom mthds.method_tree.python_modules import locate_function-from pipelex.core.method_trees.tree_files import TreeFileEntry, tree_file_bytesfrom pipelex.core.method_trees.tree_python import TREE_PYTHON_HOLD, import_held_tree_modulefrom pipelex.pipe_operators.func.exceptions import PipeFuncFunctionErrorfrom pipelex.pipe_operators.func.function_name import split_function_name@@ -50,13 +49,13 @@ class PipeFuncModuleSource(NamedTuple):source: str-def locate_in_tree(*, function_name: str, tree: MethodTree, files: Mapping[str, TreeFileEntry] | None = None) -> PipeFuncModuleSource:+def locate_in_tree(*, function_name: str, tree: MethodTree, files: Mapping[str, bytes] | None = None) -> PipeFuncModuleSource:"""Locate the module of a `function_name` among a method tree's files, and read it.Args:function_name: The step's `function_name`.tree: The method tree the step's bundle is a member of.- files: The tree's files as captured for a call, read in place of the disk when given.+ files: The tree's files by tree path, read in place of the disk when given.Raises:PipeFuncFunctionError: The tree holds no such module, or holds it twice.@@ -68,7 +67,7 @@ def locate_in_tree(*, function_name: str, tree: MethodTree, files: Mapping[str,raise PipeFuncFunctionError(str(exc)) from excsource_bytes: bytesif files is not None and location.module in files:- source_bytes = tree_file_bytes(entry=files[location.module])+ source_bytes = files[location.module]else:source_bytes = tree.file_location(location.module).read_bytes()return PipeFuncModuleSource(@@ -79,13 +78,13 @@ def locate_in_tree(*, function_name: str, tree: MethodTree, files: Mapping[str,)-def locate_in_files(*, function_name: str, files: Mapping[str, TreeFileEntry]) -> PipeFuncModuleSource:+def locate_in_files(*, function_name: str, files: Mapping[str, bytes]) -> PipeFuncModuleSource:"""Locate the module of a `function_name` among submitted files keyed by their path from the import root, and read it.Raises:PipeFuncFunctionError: The files hold no such module, or hold it twice."""- contents = {tree_path: tree_file_bytes(entry=entry) for tree_path, entry in files.items()}+ contents = dict(files)tree = MethodTree(files=tree_files_from_contents(contents), digest=digest_of_contents(contents))return locate_in_tree(function_name=function_name, tree=tree, files=files)diff --git a/pipelex/pipe_operators/func/pipe_func_transported_entrypoint.py b/pipelex/pipe_operators/func/pipe_func_transported_entrypoint.pyindex 2ab8cf037..70fce9de0 100644--- a/pipelex/pipe_operators/func/pipe_func_transported_entrypoint.py+++ b/pipelex/pipe_operators/func/pipe_func_transported_entrypoint.py@@ -2,17 +2,18 @@Invoked as a subprocess INSIDE an isolated sandbox (a Daytona box or a local subprocess): it reads aserialized ``PipeFuncExecutionRequest``, runs it via the ``direct`` executor's transported path (which-writes the call's files, imports the step's function by its import path from their root, and runs the-one function), and writes the serialized ``PipeFuncExecutionResponse``.+imports the step's function by its import path from the root of the call's files, and runs the one+function), and writes the serialized ``PipeFuncExecutionResponse``.-An optional third argument names a directory the sandbox client already unpacked the call's files into,-such as from one archive per call: it becomes the call's import root, and is left in place. Without it,-the files the request carries are written into a temporary directory, removed after the call.+The third argument names the directory the sandbox client unpacked the call's files into, such as from one+archive per call: it becomes the call's import root, and is left in place. A sandbox reaches no method file+store, so its client reads the files of the tree the request names there (``read_pipe_func_call_files``),+where it runs, and hands them over; the request carries no file's bytes.It lives in open ``pipelex`` and imports no sandbox code, so a box needs only ``pipelex`` installed —the sandbox *client* (box provisioning, upload/download, teardown) is a worker-side concern that staysin the out-of-tree plugin. This is the module a sandbox client runs as-``python -m pipelex.pipe_operators.func.pipe_func_transported_entrypoint <request_json> <result_json> [<tree_root>]``.+``python -m pipelex.pipe_operators.func.pipe_func_transported_entrypoint <request_json> <result_json> <tree_root>``.On any failure the process exits non-zero with a diagnostic on stderr, which the calling sandbox clientturns into a sandbox error.@@ -27,10 +28,12 @@ from pipelex.pipe_operators.func.pipe_func_execution_dtos import PipeFuncExecutidef main() -> None:- """argv: <request_json_path> <result_json_path> [<tree_root>]."""+ """argv: <request_json_path> <result_json_path> <tree_root>."""+ if len(sys.argv) != 4:+ sys.exit("usage: python -m pipelex.pipe_operators.func.pipe_func_transported_entrypoint <request_json> <result_json> <tree_root>")request_path = Path(sys.argv[1])result_path = Path(sys.argv[2])- tree_root = Path(sys.argv[3]).resolve() if len(sys.argv) > 3 else None+ tree_root = Path(sys.argv[3]).resolve()request = PipeFuncExecutionRequest.model_validate_json(request_path.read_text(encoding="utf-8"))# Import here so module import (e.g. for tests) stays cheap and free of boot side effects.@@ -39,10 +42,7 @@ def main() -> None:Pipelex.make(needs_inference=False)executor = DirectPipeFuncExecutor()try:- if tree_root is None:- result = asyncio.run(executor.run_pipe_func_transported(request=request))- else:- result = asyncio.run(executor.run_pipe_func_transported_at(request=request, tree_root=tree_root))+ result = asyncio.run(executor.run_pipe_func_transported_at(request=request, tree_root=tree_root))finally:Pipelex.teardown_if_needed()result_path.write_text(result.model_dump_json(), encoding="utf-8")diff --git a/pipelex/pipe_run/remote_dispatch.py b/pipelex/pipe_run/remote_dispatch.pydeleted file mode 100644index a417ee183..000000000--- a/pipelex/pipe_run/remote_dispatch.py+++ /dev/null@@ -1,34 +0,0 @@-"""A pipe job as an orchestrator outside this process receives it.--A job handed to an orchestrator other than the in-process one, such as Temporal, travels as that orchestrator's-payloads, which it bounds: Temporal refuses a payload over 2 MB. The files submitted with the job's bundles travel in-its crate, so before the job leaves, every file a step reads only when it runs, such as an office template, moves to the-run's storage and the crate carries a reference to it. The files read when the method loads, such as an HTML template,-stay inline, and their size is bounded when the bundle loads (`MAX_LOAD_STAGE_RESOURCES_BYTES`).--Every dispatcher calls `prepare_job_for_remote_dispatch` at the moment the job leaves the process:-`PipelexMTHDSProtocol.execute` when the hub's pipe run belongs to a boot orchestrator's plugin, and a host dispatching-through an orchestrator of the registry, such as the API server, for every mode but `direct`.-"""--from pipelex.libraries.bundle_resources import relocate_run_resources-from pipelex.pipe_run.pipe_job import PipeJob-from pipelex.runtime_hub import get_storage_provider-from pipelex.system.storage_scope import DRY_RUN_STORAGE_SCOPE---async def prepare_job_for_remote_dispatch(*, pipe_job: PipeJob) -> PipeJob:- """The job with the files its steps read only when they run stored under the run's scope and carried by reference.-- A dry run's files move too, since a dry run hands its office templates to the engine's checker, which reads them- back under the run's read scope as a print does. A run whose storage scope is the dry-run placeholder stores- nothing, so its files stay inline. The job is returned unchanged when it carries no submitted file.- """- crate = pipe_job.library_crate- if crate is None or not crate.bundle_resources:- return pipe_job- storage_scope = pipe_job.job_metadata.run_metadata.storage_scope- if storage_scope == DRY_RUN_STORAGE_SCOPE:- return pipe_job- relocated_crate = await relocate_run_resources(crate=crate, storage_provider=get_storage_provider(), storage_scope=storage_scope)- return pipe_job.model_copy(update={"library_crate": relocated_crate})diff --git a/pipelex/pipelex.py b/pipelex/pipelex.pyindex dc9545c3f..dc36a538a 100644--- a/pipelex/pipelex.py+++ b/pipelex/pipelex.py@@ -34,6 +34,7 @@ from pipelex.libraries.library_manager import LibraryManagerfrom pipelex.libraries.library_manager_abstract import LibraryManagerAbstractfrom pipelex.observer.observer_protocol import ObserverProtocolfrom pipelex.pipe_machinery.registry_models import PipeRegistryModels+from pipelex.pipe_operators.doc_gen.template_file_stage import DocGenTemplateFileStagefrom pipelex.pipe_operators.func.pipe_func_executor_protocol import PipeFuncExecutorProtocolfrom pipelex.pipe_run.pipe_router import PipeRouterfrom pipelex.pipe_run.pipe_router_protocol import PipeRouterProtocol@@ -182,6 +183,12 @@ class Pipelex(RuntimeBoot):self.interpreter_hub.set_pipeline_manager(pipeline_manager=self.pipeline_manager)self.pipeline_manager.setup()+ # --- Template file stage ---------------------------------------------------------------+ # The print stage of a PipeDocGen step reads its template file through the method file store, then needs the+ # loaded method for what it does with it: rendering an HTML one with the step's data, reporting what the+ # engine's check of an office one found. A kernel-only boot installs none, and prints no template file.+ self.runtime_hub.set_template_file_stage(template_file_stage=DocGenTemplateFileStage())+# Two manifests, one registry: core's value model (registered by the runtime setup above) and# the pipe kinds. They are disjoint by construction and pinned as such by# tests/unit/pipelex/test_registry_models_split.py, so the two calls landing in different@@ -203,12 +210,11 @@ class Pipelex(RuntimeBoot):# --- Pipe Run --------------------------------------------------------------------------# No explicit param for pipe_run: plugin slot-claim thunk > core default. A boot orchestrator's pipe run hands- # each job to that orchestrator, outside this process, which is what decides how the job's files travel- # (`prepare_job_for_remote_dispatch`); core's runs it here.+ # each job to that orchestrator, outside this process; the job carries no method file's bytes either way, its+ # crate naming each tree by digest, so nothing about the job changes with where it runs.self.interpreter_hub.set_pipe_run(- self._resolve_hub_slot(slot=HubSlot.PIPE_RUN, default=lambda: PipeRun(pipe_router=self.interpreter_hub.get_required_pipe_router())),- leaves_process=self._is_hub_slot_claimed(slot=HubSlot.PIPE_RUN),+ self._resolve_hub_slot(slot=HubSlot.PIPE_RUN, default=lambda: PipeRun(pipe_router=self.interpreter_hub.get_required_pipe_router())))@overridediff --git a/pipelex/pipeline/direct_bundle_validator.py b/pipelex/pipeline/direct_bundle_validator.pyindex ecec1d84d..4fafe771a 100644--- a/pipelex/pipeline/direct_bundle_validator.py+++ b/pipelex/pipeline/direct_bundle_validator.py@@ -18,11 +18,10 @@ from pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_in_process import validate_bundles_in_processif TYPE_CHECKING:- from collections.abc import Sequence+ from collections.abc import Mapping, Sequencefrom pathlib import Pathfrom pipelex.base_exceptions import ErrorReport- from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.pipeline.validation_report import PipelexValidationReportfrom pipelex.system.caller_identity import CallerIdentity@@ -45,7 +44,7 @@ class DirectBundleValidator:library_dirs: Sequence[Path] | None,caller_identity: CallerIdentity | None,graph_pipe_code: str | None,- bundle_resources: BundleResources | None,+ submitted_files: Mapping[str, bytes] | None,) -> PipelexValidationReport | ErrorReport:try:return await validate_bundles_in_process(@@ -56,7 +55,7 @@ class DirectBundleValidator:graph_pipe_code=graph_pipe_code,log_context="API validate",caller_identity=caller_identity,- bundle_resources=bundle_resources,+ submitted_files=submitted_files,)except ValidateBundleError as exc:# An invalid bundle is a produced verdict, not a fault: surface its structureddiff --git a/pipelex/pipeline/execution_seams.py b/pipelex/pipeline/execution_seams.pyindex ab5328cfe..3b640982c 100644--- a/pipelex/pipeline/execution_seams.py+++ b/pipelex/pipeline/execution_seams.py@@ -19,7 +19,7 @@ Two pure-ish building blocks composed by both the single-run wrapperlibrary mutation."""-from collections.abc import Sequence+from collections.abc import Mapping, Sequencefrom contextlib import AbstractContextManager, nullcontextfrom pathlib import Pathfrom typing import TYPE_CHECKING@@ -28,7 +28,6 @@ from mthds.protocol.pipeline_inputs import PipelineInputsfrom pipelex import logfrom pipelex.base_exceptions import PipelexUnexpectedError-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.core.memory.absence import AbsenceKind, AbsenceRecordfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactory@@ -42,7 +41,7 @@ from pipelex.interpreter_hub import (set_current_library,)from pipelex.kernel.memory_ops import shape_inputs-from pipelex.libraries.bundle_resources import check_bundle_resources+from pipelex.libraries.bundle_resources import check_submitted_filesfrom pipelex.libraries.method_trees import reporting_host_library_tree_faultsfrom pipelex.mthds_parsing.parser import MthdsParserfrom pipelex.pipe_machinery.pipe_abstract import PipeAbstract@@ -85,7 +84,7 @@ def acquire_library(bundle_uris: list[str] | None = None,library_dirs_are_callers: bool = False,methods_dirs: list[Path] | None = None,- bundle_resources: BundleResources | None = None,+ submitted_files: Mapping[str, bytes] | None = None,) -> tuple[str, str | None]:"""Set the current library, open it, and load dirs + blueprints into it.@@ -127,18 +126,17 @@ def acquire_library(Every other content belongs to no method tree and reads only the files submitted with it, so a step naming a filenone of them could be keyed by, such as one through a ``..`` segment, is refused when its blueprint validates.- ``bundle_resources`` are the files submitted with the ``mthds_contents`` that their steps read, such as a+ ``submitted_files`` are the files submitted with the ``mthds_contents`` that their steps read, such as a``PipeDocGen`` step's ``template_file``, keyed by canonical bundle-relative path. The library holds them before the- contents load, and its crate carries them with the run. A file none of the contents' steps names is refused with a- ``BundleResourceNotNamedError``, and files read at load too large to travel with the method with a- ``BundleResourcesTooLargeError``.+ contents load, as files of the tree the contents sit at the root of, and the run's crate names that tree by its+ digest. A file none of the contents' steps names is refused with a ``BundleResourceNotNamedError``.Returns the ``library_id`` and the bundle's qualified ``main_pipe`` ref(``domain.pipe_code``) when an ``mthds_contents`` bundle declares one, else``None``. Pipe resolution is the caller's responsibility."""- if bundle_resources and not mthds_contents:- msg = "bundle_resources accompany mthds_contents: a bundle loaded from a directory reads the files beside it on disk"+ if submitted_files and not mthds_contents:+ msg = "submitted_files accompany mthds_contents: a bundle loaded from a directory reads the files of its method tree"raise PipelexUnexpectedError(msg)library_manager = get_library_manager()prev_library_id = get_current_library_id_or_none()@@ -184,9 +182,9 @@ def acquire_library()for content, host_bundle_file in zip(mthds_contents, host_bundle_files, strict=True)]- if bundle_resources:- check_bundle_resources(blueprints=all_blueprints, bundle_resources=bundle_resources)- library_manager.add_bundle_resources(library_id=library_id, bundle_resources=bundle_resources)+ if submitted_files:+ check_submitted_files(blueprints=all_blueprints, submitted_files=submitted_files)+ library_manager.add_submitted_files(library_id=library_id, submitted_files=submitted_files)# Filter out blueprints whose URIs are already loaded (e.g. via PIPELEXPATH), and record the file on this# host each of the others was read from, so its steps read beside it as when its directory loads.@@ -401,6 +399,12 @@ async def prepare_pipe_job(# certain to reach a pipe whose model cannot read its format.check_file_inputs_against_consumers(entry_pipe=pipe, file_inputs=collect_file_inputs(working_memory))+ # Build the library crate from all accumulated blueprints for Temporal dispatch.+ library_crate = get_library_manager().get_crate(library_id=library_id)+ # The run records the method it ran twice over: the digest of the tree its pipe was read from, which changes with+ # any byte of it, and the crate's fingerprint, which changes only with the meaning of its concepts and pipes.+ tree_bundle_ref = library_crate.tree_bundles.get(pipe.pipe_ref) if library_crate is not None else None+job_metadata = JobMetadata(run_metadata=RunMetadata(user_id=user_id,@@ -412,6 +416,8 @@ async def prepare_pipe_job(# function; the parameter stays nullable only so every existing call# site can keep omitting it.extras=extras,+ method_tree_digest=tree_bundle_ref.tree_digest if tree_bundle_ref is not None else None,+ crate_fingerprint=library_crate.fingerprint if library_crate is not None else None,),otel_context=otel_context,trace_context=trace_context,@@ -424,9 +430,6 @@ async def prepare_pipe_job(is_mock_usage=is_mock_usage,)- # Build the library crate from all accumulated blueprints for Temporal dispatch.- library_crate = get_library_manager().get_crate(library_id=library_id)-return PipeJobFactory.make_pipe_job(pipe=pipe,pipe_run_params=pipe_run_params,diff --git a/pipelex/pipeline/method_entry.py b/pipelex/pipeline/method_entry.pyindex a3b61ca4e..83c5d5c91 100644--- a/pipelex/pipeline/method_entry.py+++ b/pipelex/pipeline/method_entry.py@@ -12,14 +12,13 @@ reads a tree listed from this host's disk.from typing import NamedTuple-from mthds.method_tree.discovery import MANIFEST_NAME+from mthds.method_tree.discovery import BUNDLE_SUFFIX, MANIFEST_NAMEfrom mthds.method_tree.models import MethodTreefrom mthds.package.discovery import read_package_manifest_atfrom mthds.package.exceptions import ManifestErrorfrom mthds.package.manifest.schema import MethodsManifestfrom pipelex.base_exceptions import PipelexUnexpectedError-from pipelex.libraries.method_trees import tree_bundles_offrom pipelex.mthds_parsing.parser import MthdsParserfrom pipelex.mthds_parsing.pipelex_bundle_blueprint import PipelexBundleBlueprintfrom pipelex.pipe_machinery.pipe_factory import PipeFactory@@ -148,8 +147,9 @@ def select_method_entry(*, tree: MethodTree) -> MethodEntry:raise MethodEntryError(msg)method_label = f"at '{tree.directory}'"candidates = [- EntryCandidate(tree_path=tree_bundle.tree_path, blueprint=MthdsParser.make_pipelex_bundle_blueprint(bundle_path=tree_bundle.location))- for tree_bundle in tree_bundles_of(tree=tree)+ EntryCandidate(tree_path=tree_path, blueprint=MthdsParser.make_pipelex_bundle_blueprint(bundle_path=tree.file_location(tree_path)))+ for tree_path in tree.tree_paths+ if tree_path.endswith(BUNDLE_SUFFIX)]manifest: MethodsManifest | None = Noneif MANIFEST_NAME in tree.members:diff --git a/pipelex/pipeline/pipeline_run_setup.py b/pipelex/pipeline/pipeline_run_setup.pyindex 3229d023d..e90c57824 100644--- a/pipelex/pipeline/pipeline_run_setup.py+++ b/pipelex/pipeline/pipeline_run_setup.py@@ -1,3 +1,4 @@+from collections.abc import Mappingfrom pathlib import Pathfrom typing import TYPE_CHECKING@@ -5,7 +6,6 @@ from mthds.protocol.pipeline_inputs import PipelineInputsfrom pipelex import logfrom pipelex.config import get_config-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.qualified_ref import QualifiedReffrom pipelex.graph.graph_tracer_manager import GraphTracerManager@@ -78,7 +78,7 @@ async def pipeline_run_setup(inputs_base_dir: Path | None = None,library_dirs_are_callers: bool = False,methods_dirs: list[Path] | None = None,- bundle_resources: BundleResources | None = None,+ submitted_files: Mapping[str, bytes] | None = None,) -> tuple[PipeJob, str, str]:"""Set up a pipeline for execution.@@ -187,11 +187,11 @@ async def pipeline_run_setup(``mthds_contents``, for this run alone. An address-based reference is looked up there before theinstalled stores and fetch-on-miss, and a package found there is never installed. See:func:`acquire_library`.- bundle_resources:+ submitted_files:The files submitted with ``mthds_contents`` that their steps read, such as a ``PipeDocGen``- step's ``template_file``, keyed by canonical bundle-relative path. The run library holds them, and- the job's crate carries them inline; a host that hands the job to a remote orchestrator moves the- ones read only when a step runs to the run's storage first (``relocate_run_resources``). See+ step's ``template_file``, keyed by canonical bundle-relative path. The run library holds them as the+ files of the tree the contents sit at the root of, and the job's crate names that tree by its digest,+ carrying none of their bytes: the step that uses one reads it through the method file store. See:func:`acquire_library`.Returns:@@ -332,7 +332,7 @@ async def pipeline_run_setup(bundle_uris=bundle_uris,library_dirs_are_callers=library_dirs_are_callers,methods_dirs=methods_dirs,- bundle_resources=bundle_resources,+ submitted_files=submitted_files,)library_acquired = Truediff --git a/pipelex/pipeline/resolve_bundle.py b/pipelex/pipeline/resolve_bundle.pyindex 1b5377393..93bb85d5f 100644--- a/pipelex/pipeline/resolve_bundle.py+++ b/pipelex/pipeline/resolve_bundle.py@@ -12,16 +12,16 @@ no dry-run sweep, matching `pipelex resolve` — the crate is emitted from a loavalidated** library (D6), and runnability is `validate`'s vocabulary, not resolution's."""+from collections.abc import Mappingfrom typing import Sequencefrom mthds.package.manifest.schema import MTHDS_STANDARD_VERSIONfrom pipelex.base_exceptions import PipelexUnexpectedError-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.core.method_trees.file_references import BundleFileOriginfrom pipelex.core.qualified_ref import QualifiedReffrom pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, set_current_library-from pipelex.libraries.bundle_resources import check_bundle_resources+from pipelex.libraries.bundle_resources import check_submitted_filesfrom pipelex.libraries.crate_normalization import normalize_cratefrom pipelex.libraries.library_crate import LibraryCratefrom pipelex.libraries.pipe.exceptions import PipeLibraryError@@ -34,7 +34,7 @@ def resolve_crate_from_contents(*,mthds_contents: list[str],mthds_sources: Sequence[str | None] | None = None,- bundle_resources: BundleResources | None = None,+ submitted_files: Mapping[str, bytes] | None = None,) -> LibraryCrate:"""Assemble, validate, and normalize a library crate from in-memory MTHDS contents.@@ -50,9 +50,9 @@ def resolve_crate_from_contents(onto each blueprint so diagnostics carry a real ``source``; a ``None`` entry leavesthat content source-less. Must match ``mthds_contents`` in length when provided — amismatch is a host-wiring bug.- bundle_resources: The files submitted with the contents that their steps read, such as a ``PipeDocGen``- step's ``template_file``, keyed by canonical bundle-relative path. The load reads them; the normalized- crate, a standard artifact, does not carry them.+ submitted_files: The files submitted with the contents that their steps read, such as a ``PipeDocGen``+ step's ``template_file``, keyed by canonical bundle-relative path. The load resolves the steps' references+ among them; the normalized crate, a standard artifact, carries neither them nor their tree.Returns:The normalized library crate (fully qualified, natives materialized, fingerprint set).@@ -85,9 +85,9 @@ def resolve_crate_from_contents(for content, source in zip(mthds_contents, content_sources, strict=True)]_reject_address_based_dependencies(blueprints=blueprints)- if bundle_resources:- check_bundle_resources(blueprints=blueprints, bundle_resources=bundle_resources)- library_manager.add_bundle_resources(library_id=library_id, bundle_resources=bundle_resources)+ if submitted_files:+ check_submitted_files(blueprints=blueprints, submitted_files=submitted_files)+ library_manager.add_submitted_files(library_id=library_id, submitted_files=submitted_files)# load_from_blueprints ends in load_from_crate, whose last step is# library.validate_library() — so a crate read after it satisfies the D6# "built only from a valid library" contract.diff --git a/pipelex/pipeline/runner.py b/pipelex/pipeline/runner.pyindex 5339e2616..aab053990 100644--- a/pipelex/pipeline/runner.py+++ b/pipelex/pipeline/runner.py@@ -20,14 +20,12 @@ from pipelex.config import get_configfrom pipelex.graph.graph_tracer_manager import GraphTracerManagerfrom pipelex.interpreter_hub import (clear_current_library,- does_pipe_run_leave_process,get_current_library_id_or_none,get_library_manager,get_pipe_run,get_pipeline_manager,set_current_library,)-from pipelex.pipe_run.remote_dispatch import prepare_job_for_remote_dispatchfrom pipelex.pipeline.exceptions import PipeExecutionError, PipelineExecutionErrorfrom pipelex.pipeline.pipeline_response import PipelexRunResultExecute, PipelexRunResultStart, RunStatefrom pipelex.pipeline.pipeline_run_setup import pipeline_run_setup@@ -43,12 +41,12 @@ from pipelex.tools.typing.pydantic_utils import format_pydantic_validation_errorif TYPE_CHECKING:import asyncio+ from collections.abc import Mappingfrom mthds.protocol.pipe_output import VariableMultiplicityfrom mthds.protocol.pipeline_inputs import PipelineInputsfrom mthds.protocol.working_memory import WorkingMemoryAbstract- from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.pipe_run.delivery_assignment import DeliveryAssignment@@ -191,8 +189,8 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):# a label here would put every such run into one shared entity.extras: dict[str, str] | None = None,execution_config: PipelineExecutionConfig | None = None,- # The pipe run to hand each job to instead of the hub's. One that hands the job to an orchestrator outside this- # process prepares it with `prepare_job_for_remote_dispatch` first, as the hub's path does here.+ # The pipe run to hand each job to instead of the hub's, such as one handing it to an orchestrator outside this+ # process: the job carries no method file's bytes, its crate naming each tree by digest.pipe_run: PipeRunProtocol | None = None,inputs_base_dir: Path | None = None,# Whose `library_dirs` are: the caller's own on a local CLI run, so a refusal while loading@@ -204,15 +202,15 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):# not, and resolves such a reference through the installed stores and fetch-on-miss only.methods_dirs: list[Path] | None = None,# The files a caller submits with the contents it runs or validates that their steps read, such as a- # PipeDocGen step's `template_file`, keyed by canonical bundle-relative path (`make_bundle_resources`).- # A bundle loaded from a directory reads beside itself on disk instead.- bundle_resources: BundleResources | None = None,+ # PipeDocGen step's `template_file`, keyed by canonical bundle-relative path (`canonical_submitted_files`).+ # A bundle loaded from a directory reads the files of its method tree instead.+ submitted_files: Mapping[str, bytes] | None = None,):self.library_id = library_idself.library_dirs = library_dirsself.library_dirs_are_callers = library_dirs_are_callersself.methods_dirs = methods_dirs- self.bundle_resources = bundle_resources+ self.submitted_files = submitted_filesself.bundle_uris = bundle_urisself.pipe_run_mode = pipe_run_modeself.is_mock_usage = is_mock_usage@@ -360,14 +358,10 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):inputs_base_dir=self.inputs_base_dir,library_dirs_are_callers=self.library_dirs_are_callers,methods_dirs=self.methods_dirs,- bundle_resources=self.bundle_resources,+ submitted_files=self.submitted_files,request_id=request_id,)effective_pipe_run = self._pipe_run or get_pipe_run()- if self._pipe_run is None and does_pipe_run_leave_process():- # The hub's pipe run hands the job to the boot orchestrator, outside this process, so the files its- # steps read when they run travel by reference. An injected pipe run dispatches the job itself.- pipe_job = await prepare_job_for_remote_dispatch(pipe_job=pipe_job)with method_source_scope(source=self._method_source(mthds_contents=mthds_contents)):pipe_output = await effective_pipe_run.run(pipe_job, delivery_assignment=delivery_assignment)except PipelexError as exc:@@ -555,7 +549,7 @@ class PipelexMTHDSProtocol(MTHDSProtocol["PipeOutput"]):caller_identity=self.caller_identity,# The same ownership a run of this runtime reads: the caller's own directories keep their paths.library_dirs_are_callers=self.library_dirs_are_callers,- bundle_resources=self.bundle_resources,+ submitted_files=self.submitted_files,)@overridediff --git a/pipelex/pipeline/validate_bundle.py b/pipelex/pipeline/validate_bundle.pyindex dcaefbfaf..fa9866289 100644--- a/pipelex/pipeline/validate_bundle.py+++ b/pipelex/pipeline/validate_bundle.py@@ -1,4 +1,5 @@import asyncio+from collections.abc import Mappingfrom contextlib import AbstractContextManager, nullcontextfrom pathlib import Pathfrom typing import Sequence@@ -11,7 +12,6 @@ from typing_extensions import TypedDictfrom pipelex import logfrom pipelex.base_exceptions import PipelexUnexpectedError-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.core.method_trees.file_references import BundleFileOriginfrom pipelex.core.qualified_ref import QualifiedReffrom pipelex.interpreter_hub import (@@ -21,7 +21,7 @@ from pipelex.interpreter_hub import (resolve_library_dirs,set_current_library,)-from pipelex.libraries.bundle_resources import check_bundle_resources+from pipelex.libraries.bundle_resources import check_submitted_filesfrom pipelex.libraries.library_utils import get_pipelex_mthds_files_from_dirsfrom pipelex.libraries.method_trees import reporting_host_library_tree_faultsfrom pipelex.libraries.pipe.exceptions import EntryPipeNotFoundError@@ -128,15 +128,14 @@ async def validate_bundle(caller_identity: CallerIdentity | None = None,library_dirs_are_callers: bool = False,collect_dry_run_warnings: bool = False,- bundle_resources: BundleResources | None = None,+ submitted_files: Mapping[str, bytes] | None = None,) -> ValidateBundleResult:"""Load one bundle into a fresh library and dry-run its pipes.- ``bundle_resources`` are the files submitted with ``mthds_contents`` that their steps read, such as a+ ``submitted_files`` are the files submitted with ``mthds_contents`` that their steps read, such as a``PipeDocGen`` step's ``template_file``, keyed by canonical bundle-relative path (see- ``make_bundle_resources``). A file none of the submitted steps names is refused with a- ``BundleResourceNotNamedError``, and files read at load that total more than ``MAX_LOAD_STAGE_RESOURCES_BYTES`` with- a ``BundleResourcesTooLargeError``, neither a verdict. A bundle file reads beside itself on disk and takes none.+ ``canonical_submitted_files``). A file none of the submitted steps names is refused with a+ ``BundleResourceNotNamedError``, not a verdict. A bundle file reads the files of its method tree and takes none.``caller_identity`` is who asked for the validation, when the host knows it; the dry-runsweep is attributed to that caller (see ``BundleValidator.validate_pipes``). ``None``@@ -186,8 +185,8 @@ async def validate_bundle(msg = "mthds_sources, when provided, must be a per-item source list matching mthds_contents in length"raise PipelexUnexpectedError(msg)- if bundle_resources and mthds_contents is None:- msg = "bundle_resources accompany mthds_contents: a bundle file reads the files beside it on disk"+ if submitted_files and mthds_contents is None:+ msg = "submitted_files accompany mthds_contents: a bundle file reads the files of its method tree"raise PipelexUnexpectedError(msg)library_manager = get_library_manager()@@ -237,9 +236,9 @@ async def validate_bundle()for content, source in zip(mthds_contents, content_sources, strict=True)]- if bundle_resources:- check_bundle_resources(blueprints=loaded_blueprints, bundle_resources=bundle_resources)- library_manager.add_bundle_resources(library_id=library_id, bundle_resources=bundle_resources)+ if submitted_files:+ check_submitted_files(blueprints=loaded_blueprints, submitted_files=submitted_files)+ library_manager.add_submitted_files(library_id=library_id, submitted_files=submitted_files)loaded_pipes = library_manager.load_from_blueprints(library_id=library_id, blueprints=loaded_blueprints)dry_run_results = await BundleValidator().validate_pipes(pipes=_pipes_to_dry_run(loaded_pipes, dry_run_pipe_codes=dry_run_pipe_codes),diff --git a/pipelex/pipeline/validate_bundle_translation.py b/pipelex/pipeline/validate_bundle_translation.pyindex 4fe5ce840..c90448b35 100644--- a/pipelex/pipeline/validate_bundle_translation.py+++ b/pipelex/pipeline/validate_bundle_translation.py@@ -19,7 +19,7 @@ from pydantic import ValidationErrorfrom pipelex.base_exceptions import PipelexError, SecurityError, error_domain_is_inputfrom pipelex.config import get_config-from pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError, BundleResourcesTooLargeError+from pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError, BundleResourcePathErrorfrom pipelex.core.exceptions import DryRunFailureErrorData, PipelexBundleBlueprintValidationErrorData, PipesAndConceptValidationErrorDatafrom pipelex.core.pipes.exceptions import (PipeFactoryError,@@ -98,7 +98,7 @@ def translate_to_validate_bundle_error() -> Generator[None, None, None]:no verdict, along with the refusals that must keep their own class: ``PipeNotFoundError`` (itsdedicated not-found handler), a ``SecurityError`` (never absorbed by a domain handler), a``ValidateBundleError`` already produced (never re-wrapped), and a ``BundleResourceNotNamedError`` or a- ``BundleResourcesTooLargeError``, which refuse the files submitted with the bundle rather than the bundle.+ ``BundleResourcePathError``, which refuse the files submitted with the bundle rather than the bundle."""try:yield@@ -189,7 +189,7 @@ def translate_to_validate_bundle_error() -> Generator[None, None, None]:message=model_choice_error.message,pipe_validation_errors=[categorize_pipe_operator_model_choice_error(model_choice_error=model_choice_error)],) from model_choice_error- except (ValidateBundleError, SecurityError, BundleResourceNotNamedError, BundleResourcesTooLargeError):+ except (ValidateBundleError, SecurityError, BundleResourceNotNamedError, BundleResourcePathError):# All are PipelexErrors the general arm below would otherwise catch. A verdict already produced# (e.g. by a nested load) passes through as it is: re-wrapping it would flatten its items into one.# A security refusal is never absorbed into a domain answer, verdict included. A file submitted withdiff --git a/pipelex/pipeline/validate_in_process.py b/pipelex/pipeline/validate_in_process.pyindex cd6d890b4..032ae97d7 100644--- a/pipelex/pipeline/validate_in_process.py+++ b/pipelex/pipeline/validate_in_process.py@@ -19,13 +19,12 @@ content strings, so `blueprint.source` stays `None` on that path too. (The CLI ppoint that bypasses this orchestrator.)"""-from collections.abc import Sequence+from collections.abc import Mapping, Sequencefrom pathlib import Pathfrom typing import TYPE_CHECKINGfrom pipelex import logfrom pipelex.base_exceptions import PipelexError, ValidationErrorItem-from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.interpreter_hub import clear_current_library, get_current_library_id_or_none, get_library_manager, set_current_libraryfrom pipelex.pipe_run.dry_run_in_process import best_effort_graph_specfrom pipelex.pipe_run.dry_run_warning_collector import collecting_dry_run_warnings@@ -55,7 +54,7 @@ async def validate_bundles_in_process(log_context: str = "validate",caller_identity: CallerIdentity | None = None,library_dirs_are_callers: bool = False,- bundle_resources: BundleResources | None = None,+ submitted_files: Mapping[str, bytes] | None = None,) -> PipelexValidationReport:"""Parse, validate, and dry-run MTHDS bundles in-process; assemble the canonical report.@@ -87,7 +86,7 @@ async def validate_bundles_in_process(library_dirs_are_callers: Whether ``library_dirs`` are the caller's own, whose files theverdict may name; by default they are a host's, whose files it withholds (see``validate_bundle``).- bundle_resources: The files submitted with ``mthds_contents`` that their steps read, such as a+ submitted_files: The files submitted with ``mthds_contents`` that their steps read, such as a``PipeDocGen`` template file, keyed by canonical bundle-relative path. The dry run reads them, so thetemplate check runs on them.@@ -106,7 +105,7 @@ async def validate_bundles_in_process(graph_pipe_code=graph_pipe_code,log_context=log_context,library_dirs_are_callers=library_dirs_are_callers,- bundle_resources=bundle_resources,+ submitted_files=submitted_files,validation_report=validation_report,)@@ -120,7 +119,7 @@ async def _validate_bundles_in_scope(graph_pipe_code: str | None,log_context: str,library_dirs_are_callers: bool,- bundle_resources: BundleResources | None,+ submitted_files: Mapping[str, bytes] | None,validation_report: MethodValidationReport,) -> PipelexValidationReport:"""The body of :func:`validate_bundles_in_process`, run inside the caller's scope and timed by `validation_report`."""@@ -148,7 +147,7 @@ async def _validate_bundles_in_scope(allow_signatures=allow_signatures,library_dirs_are_callers=library_dirs_are_callers,collect_dry_run_warnings=True,- bundle_resources=bundle_resources,+ submitted_files=submitted_files,)# Capture the validation library id ONCE, right after validate_bundle leaves it# current — the graph arm and the finally must target the SAME library even ifdiff --git a/pipelex/plugins/bundle_validator_registry.py b/pipelex/plugins/bundle_validator_registry.pyindex ed7a9e1fc..00d8b2fbf 100644--- a/pipelex/plugins/bundle_validator_registry.py+++ b/pipelex/plugins/bundle_validator_registry.py@@ -33,11 +33,9 @@ from pipelex.runtime_bridge.orchestration_mode import OrchestrationModefrom pipelex.system.caller_identity import CallerIdentityif TYPE_CHECKING:- from collections.abc import Sequence+ from collections.abc import Mapping, Sequencefrom pathlib import Path- from pipelex.core.bundle_resources.bundle_resource import BundleResources-# The verdict a validator returns: valid arm = the protocol validation report (at runtime# always the canonical PipelexValidationReport subtype), invalid arm = the structured# ErrorReport. Bound at runtime (not just under TYPE_CHECKING) so an external validator@@ -76,13 +74,13 @@ class BundleValidatorProtocol(Protocol):does not resolve degrades the graph to ``None``, like any other graph-arm failure, andnever changes the verdict.- ``bundle_resources`` are the files submitted with ``mthds_contents`` that their steps read,+ ``submitted_files`` are the files submitted with ``mthds_contents`` that their steps read,such as a ``PipeDocGen`` step's ``template_file``, keyed by canonical bundle-relative path,- each carrying its bytes inline. The validation loads the bundles with them and its dry run- reads them, the template check included. It is required for the same reason as- ``caller_identity``, with ``None`` meaning none were submitted: a validator that dropped them- would refuse a valid bundle for a missing file. A worker-dispatched arm carries them to its- worker, by reference to storage rather than inline when they are large.+ with their bytes. The validation loads the bundles with them and its dry run reads them, the+ template check included. It is required for the same reason as ``caller_identity``, with+ ``None`` meaning none were submitted: a validator that dropped them would refuse a valid bundle+ for a missing file. A worker-dispatched arm hands them to its worker through the method file+ store, the crate naming their tree by digest."""async def validate_bundles(@@ -94,7 +92,7 @@ class BundleValidatorProtocol(Protocol):library_dirs: "Sequence[Path] | None",caller_identity: CallerIdentity | None,graph_pipe_code: str | None,- bundle_resources: "BundleResources | None",+ submitted_files: "Mapping[str, bytes] | None",) -> BundleValidationVerdict: ...diff --git a/pipelex/plugins/contract.py b/pipelex/plugins/contract.pyindex 6b6b04a92..a86b8f8e2 100644--- a/pipelex/plugins/contract.py+++ b/pipelex/plugins/contract.py@@ -54,7 +54,18 @@ if TYPE_CHECKING:# the media type its source gives it, where it returned the bytes alone. An engine written against v5 would receive# the model where it expects bytes and fail in the middle of a print, with a ``TypeError`` raised deep inside its# rendering library; the bump turns that into a discovery-time mismatch naming the plugin.-PLUGIN_API_VERSION: int = 6+#+# v7 changed what a run hands an orchestration plugin, now that a run's library crate names each method tree by its+# digest and carries no file's bytes. A bundle validator's ``validate_bundles`` receives ``submitted_files``, a mapping+# from the path a step names to the file's bytes, where it received ``bundle_resources``; a PipeFunc executor's+# transported request names its tree by ``tree_digest`` where it carried the call's ``files``, and the transported+# entrypoint takes the directory the call's files were unpacked into as a required argument; and an orchestrator that+# runs a job out of process copies the trees the job's crate names before its ``execute`` or ``start`` returns+# (``OrchestratorProtocol``). A validator or an executor written against v6 would be called with a keyword it does not+# accept, or read a field that is gone, on its first call; the bump turns that into a discovery-time mismatch naming+# the plugin. ``claim_method_file_store``, the hub slot an activity reads method files through by their tree's digest+# (``MethodFileStoreProtocol`` in ``pipelex.core.method_trees.method_file_store``), joined the menu with it.+PLUGIN_API_VERSION: int = 7@runtime_checkablediff --git a/pipelex/plugins/orchestrator_registry.py b/pipelex/plugins/orchestrator_registry.pyindex 809415168..54e1e2231 100644--- a/pipelex/plugins/orchestrator_registry.py+++ b/pipelex/plugins/orchestrator_registry.py@@ -31,6 +31,18 @@ class OrchestratorProtocol(Protocol):cannot do genuine async, rather than silently running blocking and acking. Anorchestrator with ``supports_fire_and_forget = False`` implements ``start`` byraising — the gate keeps it unreachable.++ The method files a job reads travel by reference: its ``library_crate`` names each method+ tree by its digest and carries none of its files, which this process's libraries hold for+ the request (``LOCAL_METHOD_FILES``), served from the bytes a request submitted or from the+ directory a tree was listed from, which may be a temporary directory the runner deletes. An+ orchestrator that runs the job out of process, on a worker reading another store, copies+ every tree the job's crate names into that store before its ``execute`` or ``start``+ returns, since the runner may drop the library and the files as soon as it does:+ ``read_stored_trees(tree_digests=pipe_job.library_crate.tree_digests(), read_scope=...)``+ (``pipelex.core.method_trees.method_files``) reads each one as a store keeps it, its listing+ under the tree's digest and its files under their hashes, checked. An orchestrator running+ the job in this process copies nothing."""supports_fire_and_forget: booldiff --git a/pipelex/plugins/registrar.py b/pipelex/plugins/registrar.pyindex 11f4c54c0..b6198bca6 100644--- a/pipelex/plugins/registrar.py+++ b/pipelex/plugins/registrar.py@@ -88,6 +88,7 @@ class HubSlot(StrEnum):PIPE_RUN = "pipe_run"TASK_MANAGER = "task_manager"ISOLATED_EXECUTION_PROBE = "isolated_execution_probe"+ METHOD_FILE_STORE = "method_file_store"@propertydef is_interpreter_layer(self) -> bool:@@ -97,7 +98,7 @@ class HubSlot(StrEnum):runs the kernel boot and not the interpreter tail, so it can never apply an interpreterclaim — which is exactly what a kernel-group plugin must not be able to reach.- For the five slots that hand a value back to core, the returned type corroborates the+ For the slots that hand a value back to core, the returned type corroborates theclassification — the interpreter ones yield a ``Pipe``-aware object, the kernel ones do not.``TASK_MANAGER`` is why that reading cannot govern on its own: its thunk is invoked for itsside effects and its return is *discarded*, so there is no handed-back object to classify.@@ -110,7 +111,7 @@ class HubSlot(StrEnum):match self:case HubSlot.PIPE_FUNC_EXECUTOR | HubSlot.PIPE_ROUTER | HubSlot.PIPE_RUN:return True- case HubSlot.CONTENT_GENERATOR | HubSlot.TASK_MANAGER | HubSlot.ISOLATED_EXECUTION_PROBE:+ case HubSlot.CONTENT_GENERATOR | HubSlot.TASK_MANAGER | HubSlot.ISOLATED_EXECUTION_PROBE | HubSlot.METHOD_FILE_STORE:return False@@ -512,6 +513,14 @@ class PluginRegistrar:def claim_isolated_execution_probe(self, factory: Callable[[], Any]) -> None:self._claim(slot=HubSlot.ISOLATED_EXECUTION_PROBE, factory=factory)+ def claim_method_file_store(self, factory: Callable[[], Any]) -> None:+ """Claim where activities read method files, by their tree's digest: the factory returns a `MethodFileStoreProtocol`.++ Claimed by a host whose activities run apart from the process that listed a run's method trees, such as a+ Temporal worker reading the hosted plane's blob store; unclaimed, a process reads the trees its own libraries hold.+ """+ self._claim(slot=HubSlot.METHOD_FILE_STORE, factory=factory)+def add_teardown(self, callback: Callable[[], None]) -> None:self.teardown_callbacks.append(callback)self._active.contributions.append("teardown callback")diff --git a/pipelex/runtime_boot.py b/pipelex/runtime_boot.pyindex 25932dabd..731f2e718 100644--- a/pipelex/runtime_boot.py+++ b/pipelex/runtime_boot.py@@ -70,6 +70,7 @@ from pipelex.cogt.model_backends.backend_credentials import (from pipelex.cogt.models.model_manager import ModelManagerfrom pipelex.cogt.models.model_manager_abstract import ModelManagerAbstractfrom pipelex.config import get_config+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILESfrom pipelex.core.registry_models import CoreRegistryModelsfrom pipelex.core.stuffs.stuff_template_set import STUFF_TEMPLATE_SETfrom pipelex.core.validation import raise_config_setup_error, report_config_refusal@@ -651,6 +652,15 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.if isolated_execution_probe_factory is not None:self.runtime_hub.set_isolated_execution_probe(isolated_execution_probe_factory())+ # --- Method file store -----------------------------------------------------------------+ # Where an activity reads a method file, by its tree's digest: a PipeFunc call's tree, a PipeDocGen step's+ # template file. Claimed by a host whose activities run apart from the process that listed the run's trees+ # (a Temporal worker reads the hosted plane's blob store); unclaimed, the local store serves the trees this+ # process's libraries hold.+ self.runtime_hub.set_method_file_store(+ method_file_store=self._resolve_hub_slot(slot=HubSlot.METHOD_FILE_STORE, default=lambda: LOCAL_METHOD_FILES)+ )+def _resolve_hub_slot(self, *, slot: HubSlot, default: Callable[[], _HubSlotImplT]) -> _HubSlotImplT:"""Resolve a process-global hub slot: a plugin's claimed thunk if present, else the core default.diff --git a/pipelex/runtime_bridge/primitives/rehydration.py b/pipelex/runtime_bridge/primitives/rehydration.pyindex ac2cec3b3..26ae1c538 100644--- a/pipelex/runtime_bridge/primitives/rehydration.py+++ b/pipelex/runtime_bridge/primitives/rehydration.py@@ -1,5 +1,8 @@+from collections.abc import Mappingfrom typing import Any+from mthds.method_tree.models import MethodTree+from pipelex.core.memory.working_memory import WorkingMemoryfrom pipelex.interpreter_hub import get_library_manager, set_current_libraryfrom pipelex.libraries.library_crate import LibraryCrate@@ -12,6 +15,7 @@ def rehydrate_library_and_memory(crate: LibraryCrate,working_memory_raw: dict[str, Any] | None,is_crate_prevalidated: bool = False,+ written_pipe_trees: Mapping[str, MethodTree] | None = None,) -> WorkingMemory | None:"""Open a fresh library from a transported crate and hydrate a transported working memory.@@ -32,7 +36,9 @@ def rehydrate_library_and_memory(``is_crate_prevalidated`` skips the pipes' validation, for a crate the sender validated where it was assembled,such as the one a `PipeFunc` call carries to a sandbox, whose other steps may name files of trees the sandbox- never receives.+ never receives. ``written_pipe_trees`` are the trees this process wrote out for a step to run in, by that step's+ pipe ref, such as the tree of a `PipeFunc` call written for its function to import: that step, and no other, is+ built in it.Returns the hydrated WorkingMemory, or None when there was nothing to hydrate."""@@ -40,7 +46,9 @@ def rehydrate_library_and_memory(library_manager.open_fresh_library(library_id=library_id)set_current_library(library_id=library_id)- library_manager.load_from_crate(library_id=library_id, crate=crate, is_crate_prevalidated=is_crate_prevalidated)+ library_manager.load_from_crate(+ library_id=library_id, crate=crate, is_crate_prevalidated=is_crate_prevalidated, written_pipe_trees=written_pipe_trees+ )if working_memory_raw is None:return Nonediff --git a/pipelex/runtime_hub.py b/pipelex/runtime_hub.pyindex 87f051f8a..ca642e419 100644--- a/pipelex/runtime_hub.py+++ b/pipelex/runtime_hub.py@@ -39,6 +39,7 @@ from pipelex.cogt.inference.inference_manager_protocol import InferenceManagerPrfrom pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstractfrom pipelex.cogt.models.model_deck import ModelDeckfrom pipelex.cogt.models.model_manager_abstract import ModelManagerAbstract+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES, MethodFileStoreProtocolfrom pipelex.plugins.sdk_client_manager import SdkClientManagerfrom pipelex.reporting.reporting_protocol import ReportingProtocolfrom pipelex.system.configuration.config_loader import config_manager@@ -60,6 +61,7 @@ if TYPE_CHECKING:# Rich is the `cli` extra: the console is built when it is first asked for, never at import or at boot.from rich.console import Console+ from pipelex.cogt.doc_gen.template_file_stage import TemplateFileStageProtocolfrom pipelex.cogt.inference.service_error_vocabulary import ServiceErrorVocabularyfrom pipelex.plugins.bundle_validator_registry import BundleValidatorRegistryfrom pipelex.plugins.inference_backend_registry import InferenceBackendRegistry@@ -110,6 +112,11 @@ class RuntimeHub:self._console_print_stream: TextIO | None = Noneself._secrets_provider: SecretsProviderAbstract | None = Noneself._storage_provider: StorageProviderAbstract | None = None+ # Where an activity reads a method file, by its tree's digest: the local store unless a plugin claims+ # HubSlot.METHOD_FILE_STORE for a host whose activities run apart from the process that listed the trees.+ self._method_file_store: MethodFileStoreProtocol = LOCAL_METHOD_FILES+ # What the print stage of a PipeDocGen step needs a loaded method for, installed by the interpreter's boot.+ self._template_file_stage: TemplateFileStageProtocol | None = Noneself._telemetry_manager: TelemetryManagerAbstract | None = None# cogtself._models_manager: ModelManagerAbstract | None = None@@ -224,6 +231,8 @@ class RuntimeHub:self._config = Noneself._is_dry_run_forced = Falseself._boot_orchestrator = None+ self._method_file_store = LOCAL_METHOD_FILES+ self._template_file_stage = Noneself._isolated_execution_probe = _never_in_isolated_executionif self._pretty_print_mode_before_boot is not None:PrettyPrinter.mode = self._pretty_print_mode_before_boot@@ -266,6 +275,12 @@ class RuntimeHub:def set_storage_provider(self, storage_provider: StorageProviderAbstract | None):self._storage_provider = storage_provider+ def set_method_file_store(self, *, method_file_store: MethodFileStoreProtocol) -> None:+ self._method_file_store = method_file_store++ def set_template_file_stage(self, *, template_file_stage: "TemplateFileStageProtocol | None") -> None:+ self._template_file_stage = template_file_stage+def set_telemetry_manager(self, telemetry_manager: TelemetryManagerAbstract):self._telemetry_manager = telemetry_manager@@ -379,6 +394,15 @@ class RuntimeHub:raise RuntimeError(msg)return self._storage_provider+ def get_method_file_store(self) -> MethodFileStoreProtocol:+ return self._method_file_store++ def get_template_file_stage(self) -> "TemplateFileStageProtocol":+ if self._template_file_stage is None:+ msg = "The template file stage is not installed: a process booted with the kernel layer alone prints no template file"+ raise RuntimeError(msg)+ return self._template_file_stage+def get_telemetry_manager(self) -> TelemetryManagerAbstract:if self._telemetry_manager is None:msg = "TelemetryManager is not initialized"@@ -494,6 +518,16 @@ def get_storage_provider() -> StorageProviderAbstract:return get_runtime_hub().get_storage_provider()+def get_method_file_store() -> MethodFileStoreProtocol:+ """The store activities read method files through, by their tree's digest (`pipelex.core.method_trees.method_files`)."""+ return get_runtime_hub().get_method_file_store()+++def get_template_file_stage() -> "TemplateFileStageProtocol":+ """What the print stage of a `PipeDocGen` step needs a loaded method for, as the interpreter installed it."""+ return get_runtime_hub().get_template_file_stage()++def get_class_registry() -> ClassRegistryAbstract:"""Return the active class registry, respecting per-workflow library scoping.diff --git a/pipelex/system/job_metadata.py b/pipelex/system/job_metadata.pyindex b8da2f1f7..35fb93685 100644--- a/pipelex/system/job_metadata.py+++ b/pipelex/system/job_metadata.py@@ -153,6 +153,13 @@ class RunMetadata(BaseModel):# with a single tenant.read_scope: str | None+ # The method the run ran, recorded twice over (`wip/extra-files/design.md`, "The tree digest"): the digest of the+ # method tree its pipe was read from, which names its exact files and changes with any byte of them, and the+ # fingerprint of the run's library crate, the semantic identity of its concepts and pipes, which changes only with+ # their meaning. None when the run's pipe belongs to no tree, or when it was built from no crate.+ method_tree_digest: str | None = None+ crate_fingerprint: str | None = None+# The API-inbound ``X-Request-ID`` (set by the dispatcher when an external# HTTP request enters Pipelex). Rides here so it crosses the Temporal# serialization boundary — every activity / workflow can correlate logs anddiff --git a/subject_grants.toml b/subject_grants.tomlindex ac1eacb4e..1e4a3cf79 100644--- a/subject_grants.toml+++ b/subject_grants.toml@@ -4700,6 +4700,10 @@ rationale = "Registers the factory callable as the sole operand."param = "factory"rationale = "Registers the factory callable as the sole operand."+["pipelex/plugins/registrar.py::PluginRegistrar.claim_method_file_store"]+param = "factory"+rationale = "Registers the factory callable as the sole operand, as every other hub slot claim does."+["pipelex/plugins/registrar.py::PluginRegistrar.claim_pipe_func_executor"]param = "factory"rationale = "Registrar claim: claims the pipe-func executor hub slot with a factory; single self-labelling operand, consistent with sibling claims."diff --git a/tests/data/errors/error_identity.txt b/tests/data/errors/error_identity.txtindex 79afcf4b7..72560a479 100644--- a/tests/data/errors/error_identity.txt+++ b/tests/data/errors/error_identity.txt@@ -24,10 +24,8 @@ BindingPathUnresolvedError | Binding path unresolved | https://docs.pipelex.com/BindingStepRunError | Binding step run | https://docs.pipelex.com/latest/errors/binding-step-run-error/BrokenPluginError | Broken plugin | https://docs.pipelex.com/latest/errors/broken-plugin-error/BundleElaboratorError | Bundle elaborator | https://docs.pipelex.com/latest/errors/bundle-elaborator-error/-BundleResourceError | Bundle resource | https://docs.pipelex.com/latest/errors/bundle-resource-error/BundleResourceNotNamedError | Bundle resource not named | https://docs.pipelex.com/latest/errors/bundle-resource-not-named-error/BundleResourcePathError | Bundle resource path | https://docs.pipelex.com/latest/errors/bundle-resource-path-error/-BundleResourcesTooLargeError | Bundle resources too large | https://docs.pipelex.com/latest/errors/bundle-resources-too-large-error/CodegenError | Codegen error | https://docs.pipelex.com/latest/errors/codegen-error/CodegenLockError | Codegen lock error | https://docs.pipelex.com/latest/errors/codegen-lock-error/CodegenStampError | Codegen stamp error | https://docs.pipelex.com/latest/errors/codegen-stamp-error/@@ -49,7 +47,6 @@ ConstructFieldBlueprintValueError | Construct field blueprint value | https://doContextProviderError | Context provider | https://docs.pipelex.com/latest/errors/context-provider-error/CoreUnconditionalPluginDisabledError | Core unconditional plugin disabled | https://docs.pipelex.com/latest/errors/core-unconditional-plugin-disabled-error/CostRegistryError | Cost registry | https://docs.pipelex.com/latest/errors/cost-registry-error/-CrateIntegrityError | Crate integrity error | https://docs.pipelex.com/latest/errors/crate-integrity-error/CrateNormalizationError | Crate normalization error | https://docs.pipelex.com/latest/errors/crate-normalization-error/CredentialsError | Missing or invalid credentials | https://docs.pipelex.com/latest/errors/credentials-error/CsvCoercionError | CSV coercion error | https://docs.pipelex.com/latest/errors/csv-coercion-error/@@ -190,6 +187,7 @@ MethodDependencyFetchError | Method dependency fetch | https://docs.pipelex.com/MethodEntryError | Method entry | https://docs.pipelex.com/latest/errors/method-entry-error/MethodFetchDisabledError | Method fetch disabled | https://docs.pipelex.com/latest/errors/method-fetch-disabled-error/MethodFetchError | Method fetch | https://docs.pipelex.com/latest/errors/method-fetch-error/+MethodFileUnavailableError | Method file unavailable | https://docs.pipelex.com/latest/errors/method-file-unavailable-error/MethodInstallError | Method install | https://docs.pipelex.com/latest/errors/method-install-error/MethodPackageAmbiguityError | Method package ambiguity | https://docs.pipelex.com/latest/errors/method-package-ambiguity-error/MethodPackageNotFoundError | Method package not found | https://docs.pipelex.com/latest/errors/method-package-not-found-error/@@ -243,6 +241,7 @@ PipeControllerOutputConceptMismatchError | Pipe controller output concept mismatPipeDocGenFactoryError | Pipe doc gen factory | https://docs.pipelex.com/latest/errors/pipe-doc-gen-factory-error/PipeDocGenRunError | Pipe doc gen run | https://docs.pipelex.com/latest/errors/pipe-doc-gen-run-error/PipeDocGenTemplateCheckError | Pipe doc gen template check | https://docs.pipelex.com/latest/errors/pipe-doc-gen-template-check-error/+PipeDocGenTemplateFileUncheckedError | Pipe doc gen template file unchecked | https://docs.pipelex.com/latest/errors/pipe-doc-gen-template-file-unchecked-error/PipeDocGenUndefinedValueError | Pipe doc gen undefined value | https://docs.pipelex.com/latest/errors/pipe-doc-gen-undefined-value-error/PipeExecutionError | Pipe execution | https://docs.pipelex.com/latest/errors/pipe-execution-error/PipeExtractFactoryError | Pipe extract factory | https://docs.pipelex.com/latest/errors/pipe-extract-factory-error/diff --git a/tests/integration/pipelex/libraries/test_hosted_pipe_func_load.py b/tests/integration/pipelex/libraries/test_hosted_pipe_func_load.pyindex 92a29f98a..6ec721a7b 100644--- a/tests/integration/pipelex/libraries/test_hosted_pipe_func_load.py+++ b/tests/integration/pipelex/libraries/test_hosted_pipe_func_load.py@@ -1,14 +1,19 @@+import reimport shutilimport sysimport tempfilefrom pathlib import Pathimport pytest+from mthds.method_tree.digest import digest_of_contents+from mthds.method_tree.lister import list_method_tree+from pipelex.core.bundle_resources.exceptions import BundleResourcePathError+from pipelex.core.method_trees.exceptions import MethodFileUnavailableErrorfrom pipelex.core.pipes.exceptions import PipeValidationErrorfrom pipelex.interpreter_hub import get_library_manager, scoped_current_library-from pipelex.libraries.exceptions import LibraryError-from pipelex.libraries.library_crate import SUBMITTED_PYTHON_ROOT_KEY+from pipelex.libraries.pipe_func_call_files import read_pipe_func_call_files+from pipelex.mthds_parsing.parser import MthdsParserHOSTED_DEMO_MTHDS = """\domain = "hosted_demo"@@ -84,12 +89,14 @@ def _write_shadowing_method(*, library_dir: Path) -> None:class TestHostedPipeFuncLoad:- """Sandbox-hosted load: the method's files are captured on the crate and NEVER imported in this process,- yet the method still loads, its PipeFunc validated from its module's source.+ """Sandbox-hosted load: the method's files are NEVER imported in this process, yet the method still loads, its PipeFunc+ validated from its module's source, and its crate names the step's tree by digest, the call reading the tree's files+ through the method file store."""+ @pytest.mark.asyncio@pytest.mark.usefixtures("sandbox_hosted_mode")- def test_hosted_load_captures_the_tree_files_without_importing(self):+ async def test_hosted_load_names_the_tree_and_its_calls_read_its_files_through_the_store(self):library_manager = get_library_manager()# Guard the precondition: the customer module must not already be imported in this process.assert "hosted_demo_funcs" not in sys.modules@@ -113,25 +120,27 @@ class TestHostedPipeFuncLoad:# The customer code was NOT imported in this process.assert "hosted_demo_funcs" not in sys.modules- # Every file of the step's tree but its bundles rode along on the crate, ready to travel to a- # sandbox; a file the tree excludes did not.+ # The crate names the step's tree by digest and carries none of its files; a call reads every file+ # of the tree but its bundles through the method file store, and a file the tree excludes is none.crate = library_manager.get_crate(library_id=library_id)assert crate is not None- (tree_key,) = {tree_bundle_ref.tree_key for tree_bundle_ref in crate.tree_bundles.values()}- assert sorted(crate.pipe_func_files[tree_key]) == ["hosted_demo_funcs.py", "notes/greeting.txt"]- assert crate.pipe_func_files[tree_key]["hosted_demo_funcs.py"] == CUSTOMER_FUNC_PY- # Carrying files leaves the structural fingerprint untouched.- assert crate.fingerprint == crate.compute_fingerprint()+ (tree_digest,) = crate.tree_digests()+ assert "hello from the sandbox" not in crate.model_dump_json()+ call_files = await read_pipe_func_call_files(tree_digest=tree_digest, read_scope=None)+ assert sorted(call_files) == ["hosted_demo_funcs.py", "notes/greeting.txt"]+ assert call_files["hosted_demo_funcs.py"] == CUSTOMER_FUNC_PY.encode("utf-8")finally:library_manager.teardown(library_id=library_id)- # Side-state is cleaned up on teardown: a fresh crate for the same id is gone.+ # Side-state is cleaned up on teardown: the crate is gone, and the store no longer serves the library's tree.assert library_manager.get_crate(library_id=library_id) is None+ with pytest.raises(MethodFileUnavailableError):+ await read_pipe_func_call_files(tree_digest=tree_digest, read_scope=None)@pytest.mark.usefixtures("sandbox_hosted_mode")- def test_hosted_load_rejects_colliding_source_paths(self):- """Two library dirs sharing a file path (with different content) must fail loud, not- silently overwrite one customer's PipeFunc body — the sandbox writes the files at their paths.+ def test_two_library_directories_submitting_different_files_at_one_path_beside_content_strings_are_refused(self):+ """The files beside content strings make one tree, so two library directories' files at one path must fail loud,+ not silently overwrite one customer's PipeFunc body: the call writes the files at their paths."""library_manager = get_library_manager()@@ -146,14 +155,51 @@ class TestHostedPipeFuncLoad:library_id, _ = library_manager.open_library()try:- with scoped_current_library(library_id=library_id), pytest.raises(LibraryError, match="Duplicate PipeFunc file path"):+ with scoped_current_library(library_id=library_id):library_manager.load_libraries(library_id=library_id, library_dirs=[dir_a, dir_b])+ blueprint = MthdsParser.make_pipelex_bundle_blueprint(mthds_content=HOSTED_DEMO_MTHDS)+ # The caller's conflict, named by tree path alone, never by the directories it came from.+ with pytest.raises(+ BundleResourcePathError, match=re.escape("Two different files were submitted under the same path 'hosted_demo_funcs.py'")+ ) as exc_info:+ library_manager.load_from_blueprints(library_id=library_id, blueprints=[blueprint])+ assert tmp_dir not in str(exc_info.value)+ # The refusal joined none of the directories' files, so the next load is refused the same way.+ with pytest.raises(BundleResourcePathError, match=re.escape("'hosted_demo_funcs.py'")):+ library_manager.load_from_blueprints(library_id=library_id, blueprints=[blueprint])+ finally:+ library_manager.teardown(library_id=library_id)++ @pytest.mark.asyncio+ @pytest.mark.usefixtures("sandbox_hosted_mode")+ async def test_content_strings_name_the_tree_of_the_files_their_library_directory_submits(self):+ """The directory a server writes a request's files into holds no bundle: its files make the tree the content strings sit at the root of."""+ library_manager = get_library_manager()++ with tempfile.TemporaryDirectory() as tmp_dir:+ library_dir = Path(tmp_dir)+ (library_dir / "hosted_demo_funcs.py").write_text(CUSTOMER_FUNC_PY, encoding="utf-8")++ library_id, _ = library_manager.open_library()+ try:+ with scoped_current_library(library_id=library_id):+ library_manager.load_libraries(library_id=library_id, library_dirs=[library_dir])+ library_manager.load_from_blueprints(+ library_id=library_id, blueprints=[MthdsParser.make_pipelex_bundle_blueprint(mthds_content=HOSTED_DEMO_MTHDS)]+ )+ crate = library_manager.get_crate(library_id=library_id)+ assert crate is not None+ tree_bundle_ref = crate.tree_bundles["hosted_demo.make_note"]+ assert tree_bundle_ref.tree_path is None+ assert tree_bundle_ref.tree_digest == digest_of_contents({"hosted_demo_funcs.py": CUSTOMER_FUNC_PY.encode("utf-8")})+ call_files = await read_pipe_func_call_files(tree_digest=tree_bundle_ref.tree_digest, read_scope=None)+ assert call_files == {"hosted_demo_funcs.py": CUSTOMER_FUNC_PY.encode("utf-8")}finally:library_manager.teardown(library_id=library_id)@pytest.mark.usefixtures("sandbox_hosted_mode")def test_two_methods_shipping_different_files_at_one_path_load_side_by_side(self, tmp_path: Path):- """Each method's calls carry its own tree's files, so two methods' README.md, requirements.txt and METHODS.toml never clash."""+ """Each method's calls read its own tree's files, so two methods' README.md, requirements.txt and METHODS.toml never clash."""library_manager = get_library_manager()_write_method(method_dir=tmp_path / "first", name="first")_write_method(method_dir=tmp_path / "second", name="second")@@ -164,53 +210,31 @@ class TestHostedPipeFuncLoad:library_manager.load_libraries(library_id=library_id, library_dirs=[tmp_path / "first", tmp_path / "second"])crate = library_manager.get_crate(library_id=library_id)assert crate is not None- assert SUBMITTED_PYTHON_ROOT_KEY not in crate.pipe_func_files- assert len(crate.pipe_func_files) == 2- readmes = sorted(str(call_files["README.md"]) for call_files in crate.pipe_func_files.values())- assert readmes == ["# The first method\n", "# The second method\n"]+ assert len(crate.tree_digests()) == 2+ assert {tree_bundle_ref.tree_path for tree_bundle_ref in crate.tree_bundles.values()} == {"first.mthds", "second.mthds"}finally:library_manager.teardown(library_id=library_id)@pytest.mark.usefixtures("sandbox_hosted_mode")- def test_the_crate_builds_after_the_directory_its_files_were_read_from_is_removed(self, tmp_path: Path):+ def test_the_crate_builds_after_the_directory_its_tree_was_listed_from_is_removed(self, tmp_path: Path):+ """The crate names the tree by its digest alone, so building it reads no file."""library_manager = get_library_manager()library_dir = tmp_path / "request"library_dir.mkdir()(library_dir / "make_note.mthds").write_text(HOSTED_DEMO_MTHDS, encoding="utf-8")(library_dir / "hosted_demo_funcs.py").write_text(CUSTOMER_FUNC_PY, encoding="utf-8")- (library_dir / "notes").mkdir()- (library_dir / "notes" / "greeting.txt").write_text("hello", encoding="utf-8")library_id, _ = library_manager.open_library()try:with scoped_current_library(library_id=library_id):library_manager.load_libraries(library_id=library_id, library_dirs=[library_dir])+ tree_digest = list_method_tree(library_dir).digestshutil.rmtree(library_dir)crate = library_manager.get_crate(library_id=library_id)assert crate is not None- (call_files,) = crate.pipe_func_files.values()- assert call_files["hosted_demo_funcs.py"] == CUSTOMER_FUNC_PY- assert call_files["notes/greeting.txt"] == "hello"- finally:- library_manager.teardown(library_id=library_id)-- @pytest.mark.usefixtures("sandbox_hosted_mode")- def test_a_tree_holding_no_pipe_func_step_is_not_carried(self, tmp_path: Path):- library_manager = get_library_manager()- library_dir = tmp_path / "no_steps"- library_dir.mkdir()- (library_dir / "concepts.mthds").write_text('domain = "no_steps"\n\n[concept]\nMemo = "A memo"\n', encoding="utf-8")- (library_dir / "helpers.py").write_text("VALUE = 1\n", encoding="utf-8")-- library_id, _ = library_manager.open_library()- try:- with scoped_current_library(library_id=library_id):- library_manager.load_libraries(library_id=library_id, library_dirs=[library_dir])- crate = library_manager.get_crate(library_id=library_id)- assert crate is not None- assert crate.pipe_func_files == {}+ assert crate.tree_digests() == [tree_digest]finally:library_manager.teardown(library_id=library_id)diff --git a/tests/integration/pipelex/libraries/test_hosted_structures_refusal.py b/tests/integration/pipelex/libraries/test_hosted_structures_refusal.pyindex bd3df8036..372665879 100644--- a/tests/integration/pipelex/libraries/test_hosted_structures_refusal.py+++ b/tests/integration/pipelex/libraries/test_hosted_structures_refusal.py@@ -22,6 +22,7 @@ from pipelex.codegen.stamp import apply_stampfrom pipelex.core.concepts.exceptions import ConceptFactoryErrorfrom pipelex.interpreter_hub import get_concept_library, get_library_manager, scoped_current_libraryfrom pipelex.libraries.crate_normalization import normalize_crate+from pipelex.libraries.pipe_func_call_files import read_pipe_func_call_filesfrom pipelex.methods.exceptions import MethodStructuresRefusedErrorSENTINEL_LINE = 'open(r"{marker}", "w").write("ran")\n'@@ -280,7 +281,8 @@ class TestHostedStructuresRefusal:assert tmp_path.name not in message@pytest.mark.usefixtures("sandbox_hosted_mode")- def test_generated_structures_module_is_accepted_and_not_shipped(self, tmp_path: Path, load_empty_library: Callable[[], str]):+ @pytest.mark.asyncio+ async def test_generated_structures_module_is_accepted_and_not_shipped(self, tmp_path: Path, load_empty_library: Callable[[], str]):"""The module `pipelex build structures` writes into a bundle copies the method's own MTHDS concepts, so ahosted load accepts it as generated. It is never imported here, and it does not travel either: the sandboxgenerates its own from the same concepts, and two `structures` modules there would shadow each other.@@ -317,9 +319,10 @@ class TestHostedStructuresRefusal:hosted_crate = library_manager.get_crate(library_id=library_id)assert hosted_crate is not None- (call_files,) = hosted_crate.pipe_func_files.values()+ (tree_digest,) = hosted_crate.tree_digests()+ call_files = await read_pipe_func_call_files(tree_digest=tree_digest, read_scope=None)assert "structures/structures.py" not in call_files- assert call_files.get("helpers.py") == GREETING_HELPERS_PY+ assert call_files.get("helpers.py") == GREETING_HELPERS_PY.encode()assert not _is_imported(path=generated_file)@pytest.mark.usefixtures("sandbox_hosted_mode")diff --git a/tests/integration/pipelex/libraries/test_method_requirements_load.py b/tests/integration/pipelex/libraries/test_method_requirements_load.pyindex cb05322af..160c84161 100644--- a/tests/integration/pipelex/libraries/test_method_requirements_load.py+++ b/tests/integration/pipelex/libraries/test_method_requirements_load.py@@ -4,6 +4,7 @@ from pathlib import Pathimport pytestfrom pytest_mock import MockerFixture+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILESfrom pipelex.core.method_trees.tree_python import TREE_PYTHON_HOLDfrom pipelex.interpreter_hub import get_library_manager, get_required_pipe, scoped_current_libraryfrom pipelex.libraries.exceptions import MethodRequirementsNotMetError, PipeFuncPackageSetUnstatedError@@ -176,7 +177,10 @@ class TestMethodRequirementsLoad:assert [pipe.code for pipe in pipes] == ["crunch"]crate = library_manager.get_crate(library_id=library_id)assert crate is not None- assert any(f"{_MODULE_NAME}.py" in call_files for call_files in crate.pipe_func_files.values())+ (tree_digest,) = crate.tree_digests()+ held_tree = LOCAL_METHOD_FILES.held_tree(tree_digest=tree_digest)+ assert held_tree is not None+ assert f"{_MODULE_NAME}.py" in held_tree.tree_pathsfinally:library_manager.teardown(library_id=library_id)diff --git a/tests/integration/pipelex/pipeline/test_execution_seams.py b/tests/integration/pipelex/pipeline/test_execution_seams.pyindex 78508db8f..7489edbe0 100644--- a/tests/integration/pipelex/pipeline/test_execution_seams.py+++ b/tests/integration/pipelex/pipeline/test_execution_seams.py@@ -162,6 +162,29 @@ class TestExecutionSeams:library_manager.teardown(library_id=library_id)clear_current_library()+ async def test_a_run_of_a_bundle_in_no_tree_records_its_crate_fingerprint_only(self) -> None:+ library_manager = get_library_manager()+ library_id = "seams_run_record_no_tree_lib"+ _, qualified_main_pipe = acquire_library(library_id=library_id, mthds_contents=[_SEAMS_MTHDS])+ try:+ assert qualified_main_pipe is not None+ pipe_job = await prepare_pipe_job(+ storage_scope="test/scope",+ read_scope=None,+ user_id="test-user",+ pipe=get_required_entry_pipe(pipe_code=qualified_main_pipe),+ library_id=library_id,+ execution_config=_dry_mock_config(),+ pipe_run_mode=PipeRunMode.DRY,+ pipeline_run_id="seams-record-no-tree-run-id",+ )++ assert pipe_job.job_metadata.run_metadata.method_tree_digest is None+ assert pipe_job.job_metadata.run_metadata.crate_fingerprint+ finally:+ library_manager.teardown(library_id=library_id)+ clear_current_library()+@pytest.mark.parametrize("bad_scope",[diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/conftest.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/conftest.pyindex e6ddef85c..e3e6d5b9b 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/conftest.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/conftest.py@@ -8,10 +8,11 @@ from pipelex.cogt.doc_gen.exceptions import BUILT_IN_DOC_GEN_MODELfrom pipelex.interpreter_hub import get_interpreter_hubfrom pipelex.plugins.inference_backend_registry import InferenceFamilyfrom pipelex.plugins.plugin_model_declarations import PluginModelDeclarations-from pipelex.runtime_hub import get_inference_backend_registry, get_models_manager, get_runtime_hub+from pipelex.runtime_hub import get_inference_backend_registry, get_method_file_store, get_models_manager, get_runtime_hubfrom pipelex.system.configuration.config_loader import config_managerfrom pipelex.tools.misc.toml_utils import load_toml_with_tomlkit, save_toml_to_pathfrom tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import (+ RecordingMethodFileStore,StubEngines,WorkerLikePipeRun,make_doc_gen_backends,@@ -43,16 +44,28 @@ def stub_engines() -> Iterator[StubEngines]:@pytest.fixturedef remote_worker() -> Iterator[WorkerLikePipeRun]:- """Install a worker-like pipe run as the hub's, one that hands each job outside the process, as a boot orchestrator's does."""+ """Install a worker-like pipe run as the hub's, one that runs each job from its crate alone, as a boot orchestrator's does."""interpreter_hub = get_interpreter_hub()booted_pipe_run = interpreter_hub.get_required_pipe_run()- booted_leaves_process = interpreter_hub.does_pipe_run_leave_process()worker = WorkerLikePipeRun(in_process_pipe_run=booted_pipe_run)- interpreter_hub.set_pipe_run(worker, leaves_process=True)+ interpreter_hub.set_pipe_run(worker)try:yield workerfinally:- interpreter_hub.set_pipe_run(booted_pipe_run, leaves_process=booted_leaves_process)+ interpreter_hub.set_pipe_run(booted_pipe_run)+++def recording_store() -> Iterator[RecordingMethodFileStore]:+ """Install a method file store that serves what this process's libraries hold and records every read, as the hub's."""+ runtime_hub = get_runtime_hub()+ booted_store = get_method_file_store()+ store = RecordingMethodFileStore(served_by=booted_store)+ runtime_hub.set_method_file_store(method_file_store=store)+ try:+ yield store+ finally:+ runtime_hub.set_method_file_store(method_file_store=booted_store)@pytest.fixturediff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/doc_gen_helpers.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/doc_gen_helpers.pyindex c285094d3..c23abe2e4 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/doc_gen_helpers.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/doc_gen_helpers.py@@ -13,6 +13,7 @@ from pipelex.cogt.model_backends.backend import InferenceBackendfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.cogt.models.model_manager import ModelManagerfrom pipelex.config import get_config+from pipelex.core.method_trees.method_file_store import MethodFileStoreProtocolfrom pipelex.core.pipes.pipe_output import PipeOutputfrom pipelex.interpreter_hub import get_current_library, get_library_manager, set_current_libraryfrom pipelex.pipe_run.delivery_assignment import DeliveryAssignment@@ -32,6 +33,7 @@ from tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import Pipeif TYPE_CHECKING:from pipelex.libraries.library_crate import LibraryCrate+ from pipelex.pipe_machinery.pipe_abstract import PipeAbstract# The engines the stubs stand in for: the built-in pdf from the layout, and two of the document generation plugin's,# a pdf from HTML and a docx, which the stub plugin declares as the real plugin would.@@ -160,6 +162,29 @@ async def refusal_report(*, step_fields: str) -> str:return str(exc_info.value.to_error_report().model_dump())+class RecordingMethodFileStore(MethodFileStoreProtocol):+ """A method file store serving what another serves, recording the read scope of every read, and refusing all when told to."""++ def __init__(self, *, served_by: MethodFileStoreProtocol) -> None:+ self._served_by = served_by+ self.read_scopes: list[str | None] = []+ self.refuses = False++ @override+ async def read_tree_listing(self, *, tree_digest: str, read_scope: str | None) -> bytes | None:+ self.read_scopes.append(read_scope)+ if self.refuses:+ return None+ return await self._served_by.read_tree_listing(tree_digest=tree_digest, read_scope=read_scope)++ @override+ async def read_blob(self, *, sha256: str, read_scope: str | None) -> bytes | None:+ self.read_scopes.append(read_scope)+ if self.refuses:+ return None+ return await self._served_by.read_blob(sha256=sha256, read_scope=read_scope)++METHOD_MANIFEST = """[package]address = "github.com/pipelex-tests/invoice-printer"version = "1.0.0"@@ -184,16 +209,17 @@ def write_bundle(*, directory: Path, step_fields: str, as_method: bool = True) -class WorkerLikePipeRun(PipeRunProtocol):"""Runs a job the way a remote worker does: loads the crate it was handed into a library of its own and runs its own pipe.- Installed as the hub's pipe run, as a boot orchestrator's plugin installs its own (the `remote_worker` fixture), it- receives the job only after the submitter prepared it to leave the process. Its pipe, rebuilt from the crate, finds- only a reference to its office template in the library it runs in, and reads the bytes back from the run's storage,- as a Temporal activity does. `worker_read_scope`, when given, replaces the run's read scope on the worker.+ Installed as the hub's pipe run, as a boot orchestrator's plugin installs its own (the `remote_worker` fixture). Its+ pipe, rebuilt from the crate, which names the step's tree by digest and carries none of its files, reads nothing as it+ is built, and its print stage reads the template file through the method file store, as a Temporal activity does.+ `worker_read_scope`, when given, replaces the run's read scope on the worker."""def __init__(self, *, in_process_pipe_run: PipeRunProtocol, worker_read_scope: str | None = None) -> None:self._in_process_pipe_run = in_process_pipe_runself.worker_read_scope = worker_read_scopeself.received_crates: list[LibraryCrate] = []+ self.worker_pipes: list[PipeAbstract] = []@overrideasync def run(self, pipe_job: PipeJob, *, delivery_assignment: DeliveryAssignment | None = None) -> PipeOutput:@@ -211,6 +237,7 @@ class WorkerLikePipeRun(PipeRunProtocol):try:library_manager.load_from_crate(library_id=worker_library_id, crate=crate, is_crate_prevalidated=True)worker_pipe = library_manager.get_library(library_id=worker_library_id).pipe_library.get_required_pipe(pipe_code=pipe_job.pipe.pipe_ref)+ self.worker_pipes.append(worker_pipe)job_metadata = pipe_job.job_metadataif self.worker_read_scope is not None:run_metadata = job_metadata.run_metadata.model_copy(update={"read_scope": self.worker_read_scope})diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_dependency_template_file.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_dependency_template_file.pyindex 1dc44e651..0c9b521cf 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_dependency_template_file.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_dependency_template_file.py@@ -38,7 +38,7 @@ class TestPipeDocGenDependencyTemplateFile:library = LibraryFactory.make_empty()mocker.patch.object(get_library_manager(), "get_current_library", return_value=library)LibraryManager()._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]- library=library, package_address=_PACKAGE_ADDRESS, resolved_dep=resolved_dep+ library=library, library_id="dependency-test", package_address=_PACKAGE_ADDRESS, resolved_dep=resolved_dep)return library@@ -48,7 +48,7 @@ class TestPipeDocGenDependencyTemplateFile:pipe = library.dependency_libraries["invoicing"].pipe_library.get_required_pipe(pipe_code="doc_gen_tests.print_invoice")assert isinstance(pipe, PipeDocGen)- assert pipe.template == _TEMPLATE+ assert pipe.template_file_text == _TEMPLATEdef test_a_dependency_s_missing_template_file_is_refused_without_the_host_path(self, mocker: MockerFixture, tmp_path: Path) -> None:"""The refusal is located at the package's address and names the template file as the method does, never where the host installed it."""diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_from_crate.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_from_crate.pynew file mode 100644index 000000000..eeb9083e7--- /dev/null+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_from_crate.py@@ -0,0 +1,218 @@+"""A PipeDocGen step built from a library crate, which names its method tree by digest and carries none of its files."""++from collections.abc import Generator+from contextlib import contextmanager+from pathlib import Path++import pytest+from mthds.method_tree.digest import digest_of_contents++from pipelex.config import get_config+from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES, HeldFile+from pipelex.core.method_trees.tree_bundle import MethodFileRef, TreeBundleRef+from pipelex.core.pipes.exceptions import PipeLoadRefusalError+from pipelex.interpreter_hub import get_library_manager, scoped_current_library, set_current_library+from pipelex.libraries.library_crate import LibraryCrate+from pipelex.mthds_parsing.parser import MthdsParser+from pipelex.pipe_operators.doc_gen.exceptions import PipeDocGenTemplateFileUncheckedError+from pipelex.pipe_operators.doc_gen.pipe_doc_gen import PipeDocGen+from pipelex.pipe_operators.func.direct_pipe_func_executor import TRANSPORTED_LIBRARY_ID, DirectPipeFuncExecutor+from pipelex.pipe_operators.func.pipe_func_execution_dtos import PipeFuncExecutionRequest+from pipelex.pipe_operators.func.pipe_func_execution_transport import build_pipe_func_execution_request+from pipelex.pipe_run.pipe_run_params import PipeRunParams+from pipelex.system.job_metadata import JobMetadata, RunMetadata+from pipelex.system.pipe_run_mode import PipeRunMode+from tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import PipeDocGenTestData++_HTML_STEP = 'format = "pdf"\ntemplate_file = "invoice.html"'+_TEMPLATE = b"<h1>{{ invoice.number }}</h1>"+_HOLDER = "test_pipe_doc_gen_from_crate"+_PIPE_REF = "doc_gen_tests.print_invoice"++# One method tree holding a PipeFunc and a PipeDocGen printing from an HTML template file of the same tree.+_MIXED_MTHDS = """\+domain = "mixed_tree"+description = "A PipeFunc and a PipeDocGen template step in one method tree"++[concept.Greeting]+description = "A greeting"+[concept.Greeting.structure]+text = { type = "text", description = "the greeting text", required = true }++[concept.GreetingCard]+description = "The greeting as a printable file"+refines = "Document"++[pipe.greet]+type = "PipeFunc"+description = "Build a greeting via customer code"+output = "Greeting"+function_name = "mixed_funcs.greet_it"++[pipe.print_greeting]+type = "PipeDocGen"+description = "Print the greeting"+inputs = { greeting = "Greeting" }+output = "GreetingCard"+format = "pdf"+template_file = "templates/greeting.html"+"""++_MIXED_FUNC = """\+from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.system.registries.func_registry import pipe_func++from structures import mixed_tree__Greeting+++@pipe_func()+async def greet_it(working_memory: WorkingMemory) -> mixed_tree__Greeting:+ return mixed_tree__Greeting(text="hello")+"""+++def _crate_of_a_torn_down_library() -> LibraryCrate:+ """The crate of the test bundle sent with its template file, whose library, the only one holding its tree, is torn down."""+ library_manager = get_library_manager()+ library_id, _ = library_manager.open_library()+ try:+ with scoped_current_library(library_id=library_id):+ library_manager.add_submitted_files(library_id=library_id, submitted_files={"invoice.html": _TEMPLATE})+ library_manager.load_from_blueprints(+ library_id=library_id,+ blueprints=[MthdsParser.make_pipelex_bundle_blueprint(mthds_content=PipeDocGenTestData.bundle(step_fields=_HTML_STEP))],+ )+ crate = library_manager.get_crate(library_id=library_id)+ finally:+ library_manager.teardown(library_id=library_id)+ assert crate is not None+ assert LOCAL_METHOD_FILES.held_tree(tree_digest=digest_of_contents({"invoice.html": _TEMPLATE})) is None+ return crate+++@contextmanager+def _fresh_library() -> Generator[str, None, None]:+ library_manager = get_library_manager()+ library_id, _ = library_manager.open_library()+ try:+ with scoped_current_library(library_id=library_id):+ yield library_id+ finally:+ library_manager.teardown(library_id=library_id)+++@contextmanager+def _held_template(*, template: bytes) -> Generator[str, None, None]:+ """Hold the tree of the step's template file, as a library of this process holding the method does, and name it by digest."""+ tree = LOCAL_METHOD_FILES.hold_files(holder=_HOLDER, files={"invoice.html": HeldFile.of_bytes(data=template)})+ try:+ yield tree.digest+ finally:+ LOCAL_METHOD_FILES.release(holder=_HOLDER)+++@contextmanager+def _mixed_tree_request(*, tmp_path: Path) -> Generator[PipeFuncExecutionRequest, None, None]:+ """The request a sandbox-hosted deployment builds for the PipeFunc step of the mixed method, its library left open."""+ method_dir = tmp_path / "mixed_method"+ (method_dir / "mixed_funcs").mkdir(parents=True)+ (method_dir / "templates").mkdir()+ (method_dir / "mixed.mthds").write_text(_MIXED_MTHDS, encoding="utf-8")+ (method_dir / "mixed_funcs" / "__init__.py").write_text(_MIXED_FUNC, encoding="utf-8")+ (method_dir / "templates" / "greeting.html").write_text("<h1>{{ greeting.text }}</h1>", encoding="utf-8")++ pipe_func_config = get_config().interpreter.pipe_func+ previous_mode = pipe_func_config.execution_mode+ pipe_func_config.execution_mode = "local_sandbox"+ library_manager = get_library_manager()+ try:+ build_library_id, _ = library_manager.open_library()+ set_current_library(library_id=build_library_id)+ try:+ library_manager.load_libraries(library_id=build_library_id, library_dirs=[method_dir])+ yield build_pipe_func_execution_request(+ job_metadata=JobMetadata(+ run_metadata=RunMetadata(storage_scope="test/scope", read_scope=None, user_id="user", pipeline_run_id="run")+ ),+ pipe_code="mixed_tree.greet",+ function_name="mixed_funcs.greet_it",+ working_memory=WorkingMemoryFactory.make_empty(),+ pipe_run_params=PipeRunParams(run_mode=PipeRunMode.DRY, pipe_stack_limit=10, batch_max_concurrency=None),+ )+ finally:+ library_manager.teardown(library_id=build_library_id)+ finally:+ pipe_func_config.execution_mode = previous_mode++[email protected](loop_scope="class")[email protected]("stub_engines")+class TestPipeDocGenFromCrate:+ async def test_a_crate_validated_where_its_tree_is_held_checks_the_template_file(self) -> None:+ """The validation reads the template from the tree a library of this process holds, so the step holds its text."""+ crate = _crate_of_a_torn_down_library()++ with _held_template(template=_TEMPLATE), _fresh_library() as library_id:+ get_library_manager().load_from_crate(library_id=library_id, crate=crate)+ pipe = get_library_manager().get_library(library_id=library_id).pipe_library.get_required_pipe(pipe_code=_PIPE_REF)++ assert isinstance(pipe, PipeDocGen)+ assert pipe.template_file_text == _TEMPLATE.decode("utf-8")++ async def test_a_crate_validated_where_its_tree_is_held_reaches_the_verdict_the_template_file_gets_in_process(self) -> None:+ """A template reading a variable the step does not take is refused from the crate as from the bundle."""+ crate = _crate_of_a_torn_down_library()+ wrong_template = b"<h1>{{ invoice.number }} {{ total }}</h1>"+ crate_naming_the_wrong_template = crate.model_copy(+ update={"tree_bundles": {_PIPE_REF: TreeBundleRef(tree_digest=digest_of_contents({"invoice.html": wrong_template}), tree_path=None)}}+ )++ with _held_template(template=wrong_template), _fresh_library() as library_id, pytest.raises(PipeLoadRefusalError) as exc_info:+ get_library_manager().load_from_crate(library_id=library_id, crate=crate_naming_the_wrong_template)++ assert "Variable 'total' in the template file 'invoice.html' of PipeDocGen 'print_invoice' is not in the inputs of the pipe" in str(+ exc_info.value+ )++ async def test_a_crate_validated_where_no_library_holds_its_tree_is_refused_rather_than_passed_unchecked(self) -> None:+ crate = _crate_of_a_torn_down_library()++ with _fresh_library() as library_id, pytest.raises(PipeDocGenTemplateFileUncheckedError) as exc_info:+ get_library_manager().load_from_crate(library_id=library_id, crate=crate)++ message = str(exc_info.value)+ assert "HTML template file 'invoice.html'" in message+ assert "Validate the method where its files are" in message++ async def test_a_crate_loaded_without_validation_reads_no_file(self) -> None:+ """A worker's load of a crate its runner validated names the template by digest and reads nothing, held or not."""+ crate = _crate_of_a_torn_down_library()++ with _held_template(template=_TEMPLATE) as tree_digest, _fresh_library() as library_id:+ get_library_manager().load_from_crate(library_id=library_id, crate=crate, is_crate_prevalidated=True)+ pipe = get_library_manager().get_library(library_id=library_id).pipe_library.get_required_pipe(pipe_code=_PIPE_REF)++ assert isinstance(pipe, PipeDocGen)+ assert pipe.template_file_text is None+ assert pipe.template_file_ref == MethodFileRef(tree_digest=tree_digest, tree_path="invoice.html")++ async def test_a_transported_pipe_func_call_builds_its_sibling_template_step_by_the_crate_s_digest(self, tmp_path: Path) -> None:+ """The tree written for the call holds no bundle and a generated `structures` module: only the called step is built in it.++ The PipeDocGen step of the same tree is built as the crate names it, so it resolves its template file lexically and+ names it by the digest the crate names the tree by, the one a store serves it under.+ """+ library_manager = get_library_manager()+ with _mixed_tree_request(tmp_path=tmp_path) as request, scoped_current_library(library_id=TRANSPORTED_LIBRARY_ID):+ try:+ response = await DirectPipeFuncExecutor().run_pipe_func_transported(request=request)+ sibling = library_manager.get_library(library_id=TRANSPORTED_LIBRARY_ID).pipe_library.get_required_pipe(+ pipe_code="mixed_tree.print_greeting"+ )+ finally:+ library_manager.teardown(library_id=TRANSPORTED_LIBRARY_ID)++ assert response.function_qualname == "greet_it"+ assert isinstance(sibling, PipeDocGen)+ assert sibling.template_file_ref == MethodFileRef(tree_digest=request.tree_digest or "", tree_path="templates/greeting.html")diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_render_context.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_render_context.pynew file mode 100644index 000000000..d49140372--- /dev/null+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_render_context.py@@ -0,0 +1,136 @@+"""What a PipeDocGen step's HTML template file is printed with, and the libraries that type it where the run's is not held."""++from collections.abc import AsyncGenerator, Generator+from contextlib import asynccontextmanager++import pytest+from pytest_mock import MockerFixture++from pipelex.cogt.doc_gen.document_composition import ComposedTemplateFile+from pipelex.core.memory.working_memory_factory import WorkingMemoryFactory+from pipelex.interpreter_hub import get_concept_library, get_library_manager, scoped_current_library+from pipelex.libraries.library_crate import LibraryCrate+from pipelex.mthds_parsing.parser import MthdsParser+from pipelex.pipe_operators.doc_gen.pipe_doc_gen import PipeDocGen+from pipelex.pipe_operators.doc_gen.template_file_stage import RENDER_LIBRARIES, DocGenTemplateFileStage, RenderLibraryCache+from pipelex.pipe_run.pipe_run_params import PipeRunParams+from pipelex.system.pipe_run_mode import PipeRunMode+from tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import PipeDocGenTestData++_TEMPLATE = "<h1>{{ invoice.number }}</h1>"+_PIPE_REF = "doc_gen_tests.print_invoice"++_OTHER_CONCEPTS_MTHDS = """+domain = "render_library_tests"++[concept.Receipt]+description = "A receipt"+"""+++@asynccontextmanager+async def _composed_template_file() -> AsyncGenerator[tuple[ComposedTemplateFile, LibraryCrate], None]:+ """The template file the test bundle's step composes from a memory holding a stuff no input names, with the run's crate.++ The run's library is open for the block, and torn down after it.+ """+ library_manager = get_library_manager()+ library_id, _ = library_manager.open_library()+ try:+ with scoped_current_library(library_id=library_id):+ library_manager.add_submitted_files(library_id=library_id, submitted_files={"invoice.html": _TEMPLATE.encode("utf-8")})+ bundle = PipeDocGenTestData.bundle(step_fields='format = "pdf"\ntemplate_file = "invoice.html"')+ library_manager.load_from_blueprints(library_id=library_id, blueprints=[MthdsParser.make_pipelex_bundle_blueprint(mthds_content=bundle)])+ crate = library_manager.get_crate(library_id=library_id)+ assert crate is not None+ pipe = library_manager.get_library(library_id=library_id).pipe_library.get_required_pipe(pipe_code=_PIPE_REF)+ assert isinstance(pipe, PipeDocGen)+ working_memory = WorkingMemoryFactory.make_from_pipeline_inputs(+ {**PipeDocGenTestData.INVOICE_INPUTS, "unread": {"concept": "Text", "content": "Read by no template"}},+ concept_provider=get_concept_library(),+ read_scope=None,+ )+ composition = await pipe.compose(+ working_memory=working_memory,+ pipe_run_params=PipeRunParams(run_mode=PipeRunMode.DRY, pipe_stack_limit=10, batch_max_concurrency=None),+ )+ assert composition.template_file is not None+ yield composition.template_file, crate+ finally:+ library_manager.teardown(library_id=library_id)+++def released_render_libraries() -> Generator[None, None, None]:+ yield+ RENDER_LIBRARIES.release_idle()+++def _concepts_crate(*, mthds_content: str) -> LibraryCrate:+ library_manager = get_library_manager()+ library_id, _ = library_manager.open_library()+ try:+ with scoped_current_library(library_id=library_id):+ library_manager.load_from_blueprints(+ library_id=library_id, blueprints=[MthdsParser.make_pipelex_bundle_blueprint(mthds_content=mthds_content)]+ )+ crate = library_manager.get_crate(library_id=library_id)+ finally:+ library_manager.teardown(library_id=library_id)+ assert crate is not None+ return crate.concepts_only()++[email protected](loop_scope="class")[email protected]("stub_engines")+class TestPipeDocGenRenderContext:+ async def test_the_print_receives_the_stuffs_the_step_s_inputs_name_and_the_run_s_concepts_alone(self) -> None:+ """The composition crosses into the print activity's payload, so it carries neither the run's pipes nor data no input names."""+ async with _composed_template_file() as (template_file, crate):+ render_context = template_file.render_context++ assert render_context is not None+ assert set(render_context.working_memory_raw["root"]) == {"invoice"}+ assert render_context.crate_fingerprint == crate.fingerprint+ assert render_context.concepts_crate == crate.concepts_only().model_dump(mode="json")+ assert render_context.concepts_crate["pipes"] == {}+ assert render_context.concepts_crate["tree_bundles"] == {}+ assert "doc_gen_tests.Invoice" in render_context.concepts_crate["concepts"]++ @pytest.mark.usefixtures("released_render_libraries")+ async def test_prints_away_from_the_run_s_library_type_their_data_in_one_library_kept_for_the_concepts(self, mocker: MockerFixture) -> None:+ """Loading the concepts builds their classes, so the library typing a print's data is kept for the next print."""+ async with _composed_template_file() as (template_file, _crate):+ pass+ load_spy = mocker.spy(get_library_manager(), "load_from_crate")+ stage = DocGenTemplateFileStage()++ first = await stage.render_html_template_file(template_file=template_file, template_source=_TEMPLATE)+ second = await stage.render_html_template_file(template_file=template_file, template_source=_TEMPLATE)++ assert first == second == "<h1>INV-2026-0142</h1>"+ load_spy.assert_called_once()+ assert len(RENDER_LIBRARIES.held_library_ids()) == 1++ async def test_libraries_no_print_uses_are_torn_down_beyond_the_capacity_and_one_torn_down_elsewhere_is_loaded_again(self) -> None:+ library_manager = get_library_manager()+ cache = RenderLibraryCache(capacity=1)+ invoice_concepts = _concepts_crate(mthds_content=PipeDocGenTestData.bundle(step_fields='format = "pdf"\ntemplate = "<h1></h1>"'))+ receipt_concepts = _concepts_crate(mthds_content=_OTHER_CONCEPTS_MTHDS)+ try:+ with cache.library_for(concepts_crate=invoice_concepts) as invoice_library_id:+ with cache.library_for(concepts_crate=receipt_concepts) as receipt_library_id:+ # Both are in use, so neither is torn down past the capacity.+ assert cache.held_library_ids() == [invoice_library_id, receipt_library_id]+ assert cache.held_library_ids() == [invoice_library_id, receipt_library_id]+ # Both idle: the least recently used goes past the capacity.+ assert cache.held_library_ids() == [receipt_library_id]+ assert not library_manager.is_crate_loaded(library_id=invoice_library_id, fingerprint=invoice_concepts.fingerprint)++ library_manager.teardown(library_id=receipt_library_id)+ with cache.library_for(concepts_crate=receipt_concepts) as reloaded_library_id:+ assert reloaded_library_id != receipt_library_id+ assert library_manager.is_crate_loaded(library_id=reloaded_library_id, fingerprint=receipt_concepts.fingerprint)+ finally:+ cache.release_idle()+ assert cache.held_library_ids() == []diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.pysimilarity index 75%rename from tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.pyrename to tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.pyindex 4bd19c663..c819ca87a 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_bundle_resources.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_submitted_files.py@@ -4,20 +4,30 @@ from pathlib import Pathfrom typing import Anyimport pytest+from mthds.method_tree.digest import digest_of_contents+from pytest_mock import MockerFixturefrom pipelex.base_exceptions import PipelexError, ValidationErrorCategoryfrom pipelex.cogt.doc_gen.doc_gen_format import DocGenSourcefrom pipelex.cogt.doc_gen.template_check import TemplateFinding, TemplateFindingSeverity-from pipelex.core.bundle_resources.bundle_resource import BundleResources, make_bundle_resourcesfrom pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError+from pipelex.core.method_trees.exceptions import MethodFileUnavailableError+from pipelex.core.method_trees.tree_bundle import TreeBundleReffrom pipelex.core.stuffs.document_content import DocumentContent+from pipelex.pipe_operators.doc_gen.pipe_doc_gen import PipeDocGen+from pipelex.pipe_operators.doc_gen.template_file_stage import DocGenTemplateFileStagefrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.resolve_bundle import resolve_crate_from_contentsfrom pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.pipeline.validate_bundle import validate_bundlefrom pipelex.system.pipe_run_mode import PipeRunMode-from pipelex.system.storage_scope import DRY_RUN_STORAGE_SCOPE, LOCAL_STORAGE_SCOPE-from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import METHOD_MANIFEST, StubEngines, WorkerLikePipeRun, write_bundle+from tests.integration.pipelex.pipes.operator.pipe_doc_gen.doc_gen_helpers import (+ METHOD_MANIFEST,+ RecordingMethodFileStore,+ StubEngines,+ WorkerLikePipeRun,+ write_bundle,+)from tests.integration.pipelex.pipes.operator.pipe_doc_gen.test_data import PipeDocGenTestData_DOCX_TEMPLATE_STEP = 'format = "docx"\ntemplate_file = "templates/invoice.docx"'@@ -27,8 +37,8 @@ _DOCX_BYTES = b"PK docx template bytes"_ESCAPING_DOCX_STEP = 'format = "docx"\ntemplate_file = "../invoice.docx"'-def _docx_resources() -> BundleResources:- return make_bundle_resources(files={"./templates/invoice.docx": _DOCX_BYTES})+def _docx_files() -> dict[str, bytes]:+ return {"./templates/invoice.docx": _DOCX_BYTES}def _bundle_file_climbing_in_its_method_tree(*, method_dir: Path) -> Path:@@ -40,37 +50,49 @@ def _bundle_file_climbing_in_its_method_tree(*, method_dir: Path) -> Path:return write_bundle(directory=method_dir / "bundles", step_fields='format = "docx"\ntemplate_file = "../templates/invoice.docx"', as_method=False)-async def _load_from_content(*, load: str, content: str, resources: BundleResources | None) -> None:+async def _load_from_content(*, load: str, content: str, submitted_files: dict[str, bytes] | None) -> None:"""Validate the content, resolve its crate or run it, as the runner's routes do with a bundle sent as a string."""match load:case "validate":- await validate_bundle(mthds_contents=[content], bundle_resources=resources)+ await validate_bundle(mthds_contents=[content], submitted_files=submitted_files)case "resolve":- resolve_crate_from_contents(mthds_contents=[content], bundle_resources=resources)+ resolve_crate_from_contents(mthds_contents=[content], submitted_files=submitted_files)case _:- await PipelexMTHDSProtocol(bundle_resources=resources).execute(mthds_contents=[content], inputs=PipeDocGenTestData.INVOICE_INPUTS)+ await PipelexMTHDSProtocol(submitted_files=submitted_files).execute(mthds_contents=[content], inputs=PipeDocGenTestData.INVOICE_INPUTS)@pytest.mark.asyncio(loop_scope="class")-class TestPipeDocGenBundleResources:+class TestPipeDocGenSubmittedFiles:async def test_a_bundle_validates_with_its_template_file_and_the_check_runs_on_its_bytes(self, stub_engines: StubEngines) -> None:"""The dry run hands the engine's checker the bytes submitted with the bundle, found by the path the step names."""await validate_bundle(mthds_contents=[PipeDocGenTestData.bundle(step_fields=_DOCX_TEMPLATE_STEP)],- bundle_resources=_docx_resources(),+ submitted_files=_docx_files(),)(request,) = stub_engines.check_requestsassert request.template == _DOCX_BYTESassert request.template_name == "templates/invoice.docx"+ async def test_a_step_naming_its_template_with_a_repeated_slash_reads_the_file_submitted_under_its_one_spelling(+ self, stub_engines: StubEngines+ ) -> None:+ """Blueprint validation accepts `templates//invoice.docx`, so the step finds the file submitted as `templates/invoice.docx`."""+ await validate_bundle(+ mthds_contents=[PipeDocGenTestData.bundle(step_fields='format = "docx"\ntemplate_file = "templates//invoice.docx"')],+ submitted_files={"templates/invoice.docx": _DOCX_BYTES},+ )++ (request,) = stub_engines.check_requests+ assert request.template == _DOCX_BYTES+async def test_the_check_s_errors_on_a_submitted_template_fail_the_validation(self, stub_engines: StubEngines) -> None:stub_engines.findings = [TemplateFinding(severity=TemplateFindingSeverity.ERROR, message="The tag {{ invoice.totl }} names no field")]with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[PipeDocGenTestData.bundle(step_fields=_DOCX_TEMPLATE_STEP)],- bundle_resources=_docx_resources(),+ submitted_files=_docx_files(),)assert "invoice.totl" in str(exc_info.value.to_error_report().model_dump())@@ -97,10 +119,10 @@ class TestPipeDocGenBundleResources:names the field and never repeats the path, rather than a load refusal saying the file was not supplied."""content = PipeDocGenTestData.bundle(step_fields=f'format = "docx"\ntemplate_file = "{template_file}"')- resources = make_bundle_resources(files={"invoice.docx": _DOCX_BYTES}) if sends_a_file else None+ submitted_files = {"invoice.docx": _DOCX_BYTES} if sends_a_file else Nonewith pytest.raises(ValidateBundleError) as exc_info:- await _load_from_content(load=load, content=content, resources=resources)+ await _load_from_content(load=load, content=content, submitted_files=submitted_files)items = exc_info.value.to_error_report().validation_errorsassert items is not None@@ -185,10 +207,10 @@ class TestPipeDocGenBundleResources:@pytest.mark.usefixtures("stub_engines")async def test_a_file_no_step_names_is_refused_as_the_request_s_fault_not_as_a_verdict(self) -> None:- resources = make_bundle_resources(files={"templates/invoice.docx": _DOCX_BYTES, "templates/logo.png": b"png"})+ submitted_files = {"templates/invoice.docx": _DOCX_BYTES, "templates/logo.png": b"png"}with pytest.raises(BundleResourceNotNamedError) as exc_info:- await validate_bundle(mthds_contents=[PipeDocGenTestData.bundle(step_fields=_DOCX_TEMPLATE_STEP)], bundle_resources=resources)+ await validate_bundle(mthds_contents=[PipeDocGenTestData.bundle(step_fields=_DOCX_TEMPLATE_STEP)], submitted_files=submitted_files)assert "'templates/logo.png'" in exc_info.value.message@@ -198,13 +220,13 @@ class TestPipeDocGenBundleResources:with pytest.raises(ValidateBundleError) as exc_info:await validate_bundle(mthds_contents=[PipeDocGenTestData.bundle(step_fields='format = "pdf"\ntemplate_file = "invoice.html"')],- bundle_resources=make_bundle_resources(files={"invoice.html": b"<h1>{{ invoice.numbr }}</h1>"}),+ submitted_files={"invoice.html": b"<h1>{{ invoice.numbr }}</h1>"},)assert "numbr" in str(exc_info.value.to_error_report().model_dump())async def test_a_run_prints_with_the_submitted_html_template(self, stub_engines: StubEngines) -> None:- await PipelexMTHDSProtocol(bundle_resources=make_bundle_resources(files={"invoice.html": b"<h1>{{ invoice.number }}</h1>"})).execute(+ await PipelexMTHDSProtocol(submitted_files={"invoice.html": b"<h1>{{ invoice.number }}</h1>"}).execute(mthds_contents=[PipeDocGenTestData.bundle(step_fields='format = "pdf"\ntemplate_file = "invoice.html"')],inputs=PipeDocGenTestData.INVOICE_INPUTS,)@@ -214,7 +236,7 @@ class TestPipeDocGenBundleResources:assert job.html == "<h1>INV-2026-0142</h1>"async def test_a_run_hands_the_engine_the_submitted_template_file(self, stub_engines: StubEngines) -> None:- result = await PipelexMTHDSProtocol(bundle_resources=_docx_resources()).execute(+ result = await PipelexMTHDSProtocol(submitted_files=_docx_files()).execute(mthds_contents=[PipeDocGenTestData.bundle(step_fields=_DOCX_TEMPLATE_STEP)],inputs=PipeDocGenTestData.INVOICE_INPUTS,)@@ -229,7 +251,7 @@ class TestPipeDocGenBundleResources:assert job.data["invoice"]["number"] == "INV-2026-0142"async def test_a_dry_run_checks_the_submitted_template_file_and_prints_nothing(self, stub_engines: StubEngines) -> None:- result = await PipelexMTHDSProtocol(pipe_run_mode=PipeRunMode.DRY, bundle_resources=_docx_resources()).execute(+ result = await PipelexMTHDSProtocol(pipe_run_mode=PipeRunMode.DRY, submitted_files=_docx_files()).execute(mthds_contents=[PipeDocGenTestData.bundle(step_fields=_DOCX_TEMPLATE_STEP)],inputs=PipeDocGenTestData.INVOICE_INPUTS,)@@ -241,51 +263,84 @@ class TestPipeDocGenBundleResources:assert request.template == _DOCX_BYTESassert stub_engines.engine.jobs == []+ @pytest.mark.parametrize("pipe_run_mode", [pytest.param(PipeRunMode.LIVE, id="live"), pytest.param(PipeRunMode.DRY, id="dry")])@pytest.mark.parametrize(- ("pipe_run_mode", "storage_scope", "is_stored"),+ ("step_fields", "submitted_files"),[- pytest.param(PipeRunMode.LIVE, LOCAL_STORAGE_SCOPE, True, id="live"),- pytest.param(PipeRunMode.DRY, LOCAL_STORAGE_SCOPE, True, id="dry"),- pytest.param(PipeRunMode.DRY, DRY_RUN_STORAGE_SCOPE, False, id="dry_run_placeholder_scope"),+ pytest.param(_DOCX_TEMPLATE_STEP, {"templates/invoice.docx": _DOCX_BYTES}, id="office"),+ pytest.param('format = "pdf"\ntemplate_file = "invoice.html"', {"invoice.html": b"<h1>{{ invoice.number }}</h1>"}, id="html"),],)- async def test_a_run_handed_to_a_remote_worker_reads_its_template_from_the_run_s_storage(+ async def test_a_run_handed_to_a_remote_worker_reads_its_template_through_the_method_file_store(self,stub_engines: StubEngines,remote_worker: WorkerLikePipeRun,+ recording_store: RecordingMethodFileStore,+ mocker: MockerFixture,pipe_run_mode: PipeRunMode,- storage_scope: str,- is_stored: bool,+ step_fields: str,+ submitted_files: dict[str, bytes],) -> None:- """The job leaves the process carrying a reference, and the worker's step reads the stored bytes, to print or to check.+ """The crate names the step's tree by digest and carries none of its files, and the print stage reads the template under the run's read scope.- A run whose storage scope is the dry-run placeholder stores nothing, so its template travels inline.+ An HTML template file is rendered there too, a dry print included, with the step's data typed by the run's crate."""- await PipelexMTHDSProtocol(pipe_run_mode=pipe_run_mode, storage_scope=storage_scope, bundle_resources=_docx_resources()).execute(- mthds_contents=[PipeDocGenTestData.bundle(step_fields=_DOCX_TEMPLATE_STEP)],+ remote_worker.worker_read_scope = "acme/runs"+ render_spy = mocker.spy(DocGenTemplateFileStage, "render_html_template_file")++ await PipelexMTHDSProtocol(pipe_run_mode=pipe_run_mode, submitted_files=submitted_files).execute(+ mthds_contents=[PipeDocGenTestData.bundle(step_fields=step_fields)],inputs=PipeDocGenTestData.INVOICE_INPUTS,)(received_crate,) = remote_worker.received_crates- received = received_crate.bundle_resources["templates/invoice.docx"]- assert (received.uri is not None) == is_stored- assert received.is_inline != is_stored- templates_read = [request.template for request in stub_engines.check_requests] + [job.template for job in stub_engines.engine.jobs]- assert templates_read == [_DOCX_BYTES]-- async def test_a_worker_reads_no_stored_template_outside_the_run_s_read_scope_even_to_check_it(- self, stub_engines: StubEngines, remote_worker: WorkerLikePipeRun+ assert received_crate.tree_bundles["doc_gen_tests.print_invoice"] == TreeBundleRef(+ tree_digest=digest_of_contents(submitted_files), tree_path=None+ )+ assert "invoice.number }}" not in received_crate.model_dump_json()+ # The worker's step, built from the crate, read no file: its compose stage names the template, and its print reads it.+ (worker_pipe,) = remote_worker.worker_pipes+ assert isinstance(worker_pipe, PipeDocGen)+ assert worker_pipe.template_file_text is None+ # An HTML template's print receives the stuffs the step's inputs name and the run's concepts, none of its pipes.+ for render_call in render_spy.call_args_list:+ render_context = render_call.kwargs["template_file"].render_context+ assert set(render_context.working_memory_raw["root"]) == {"invoice"}+ assert render_context.concepts_crate["pipes"] == {}+ assert "doc_gen_tests.Invoice" in render_context.concepts_crate["concepts"]+ assert render_context.crate_fingerprint == received_crate.fingerprint+ assert recording_store.read_scopes+ assert set(recording_store.read_scopes) == {"acme/runs"}+ match (pipe_run_mode, step_fields):+ case (PipeRunMode.LIVE, 'format = "docx"\ntemplate_file = "templates/invoice.docx"'):+ assert [job.template for job in stub_engines.engine.jobs] == [_DOCX_BYTES]+ assert render_spy.call_count == 0+ case (PipeRunMode.DRY, 'format = "docx"\ntemplate_file = "templates/invoice.docx"'):+ assert [request.template for request in stub_engines.check_requests] == [_DOCX_BYTES]+ assert stub_engines.engine.jobs == []+ assert render_spy.call_count == 0+ case (PipeRunMode.LIVE, _):+ assert [job.html for job in stub_engines.engine.jobs] == ["<h1>INV-2026-0142</h1>"]+ assert render_spy.call_count == 1+ case (PipeRunMode.DRY, _):+ assert stub_engines.engine.jobs == []+ assert render_spy.call_count == 1++ async def test_a_template_file_the_store_does_not_serve_fails_the_print_naming_it(+ self, stub_engines: StubEngines, remote_worker: WorkerLikePipeRun, recording_store: RecordingMethodFileStore) -> None:- """The dry run's template check reads a stored template under the run's read scope, as the print stage does."""- remote_worker.worker_read_scope = "another-tenant"+ """A worker whose store serves no file of the step's tree cannot print, and says which file by its tree path, not a host path."""+ recording_store.refuses = Truewith pytest.raises(PipelexError) as exc_info:- await PipelexMTHDSProtocol(pipe_run_mode=PipeRunMode.DRY, bundle_resources=_docx_resources()).execute(+ await PipelexMTHDSProtocol(pipe_run_mode=PipeRunMode.DRY, submitted_files=_docx_files()).execute(mthds_contents=[PipeDocGenTestData.bundle(step_fields=_DOCX_TEMPLATE_STEP)],inputs=PipeDocGenTestData.INVOICE_INPUTS,)- assert "Refused to read the template file 'templates/invoice.docx'" in str(exc_info.value.to_error_report().model_dump())+ assert remote_worker.received_crates+ report = str(exc_info.value.to_error_report().model_dump())+ assert MethodFileUnavailableError.__name__ in reportassert stub_engines.check_requests == []@pytest.mark.parametrize(@@ -358,8 +413,7 @@ class TestPipeDocGenBundleResources:) -> None:"""A host library's step and a submitted step naming the same template path each read their own file, here and on a worker.- A worker's library holds the crate's submitted files before it builds any pipe, the host library's included,- so the host step must not take the submitted file for its own there either.+ The crate names each step's tree by digest, so on a worker too each step's print reads the file of its own tree."""host_dir = tmp_path / "host"host_dir.mkdir()@@ -368,7 +422,7 @@ class TestPipeDocGenBundleResources:PipeDocGenTestData.bundle(step_fields=step_fields).replace("doc_gen_tests", "doc_gen_host"), encoding="utf-8")(host_dir / "invoice.docx").write_bytes(b"host template")- submitted = make_bundle_resources(files={"invoice.docx": b"submitted template"})+ submitted = {"invoice.docx": b"submitted template"}host_inputs: dict[str, Any] = {"invoice": {**PipeDocGenTestData.INVOICE_INPUTS["invoice"], "concept": "doc_gen_host.Invoice"}}runs: list[tuple[str, dict[str, Any]]] = [("doc_gen_host.print_invoice", host_inputs),@@ -379,7 +433,7 @@ class TestPipeDocGenBundleResources:request.getfixturevalue("remote_worker")for pipe_code, inputs in runs:- await PipelexMTHDSProtocol(library_dirs=[str(host_dir)], bundle_resources=submitted).execute(+ await PipelexMTHDSProtocol(library_dirs=[str(host_dir)], submitted_files=submitted).execute(pipe_code=pipe_code,mthds_contents=[PipeDocGenTestData.bundle(step_fields=step_fields)],inputs=inputs,diff --git a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_files.py b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_files.pyindex f87dfe739..175b2964f 100644--- a/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_files.py+++ b/tests/integration/pipelex/pipes/operator/pipe_doc_gen/test_pipe_doc_gen_template_files.py@@ -1,10 +1,13 @@from pathlib import Pathimport pytest+from mthds.method_tree.models import MethodTree+from pytest_mock import MockerFixturefrom pipelex.cogt.doc_gen.input_shape import InputShapeKindfrom pipelex.cogt.doc_gen.template_check import TemplateFinding, TemplateFindingSeverity-from pipelex.core.bundle_resources.bundle_resource import make_bundle_resources+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES+from pipelex.core.method_trees.tree_bundle import MethodFileReffrom pipelex.pipe_operators.doc_gen.pipe_doc_gen import PipeDocGenfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.pipeline.validate_bundle import ValidateBundleResult, validate_bundle@@ -24,7 +27,7 @@ async def _validate_with_html_template_file(*, directory: Path, load: str, templcase _:return await validate_bundle(mthds_contents=[PipeDocGenTestData.bundle(step_fields=step_fields)],- bundle_resources=make_bundle_resources(files={"invoice.html": template_bytes}),+ submitted_files={"invoice.html": template_bytes},)@@ -72,7 +75,10 @@ class TestPipeDocGenTemplateFiles:(pipe,) = result.pipesassert isinstance(pipe, PipeDocGen)- assert pipe.template == "<h1>{{ invoice.number }}</h1>"+ assert pipe.template is None+ assert pipe.template_file_text == "<h1>{{ invoice.number }}</h1>"+ assert isinstance(pipe.template_file_ref, MethodFileRef)+ assert pipe.template_file_ref.tree_path == "templates/invoice.html"@pytest.mark.usefixtures("stub_engines")async def test_a_bundle_file_named_alone_reads_no_file_beside_it(self, tmp_path: Path) -> None:@@ -125,6 +131,26 @@ class TestPipeDocGenTemplateFiles:assert "could not read the template file 'invoice.html' as UTF-8 text" in str(exc_info.value.to_error_report().model_dump())+ @pytest.mark.usefixtures("stub_engines")+ async def test_an_html_template_file_changed_after_its_tree_was_listed_is_refused_not_read_from_disk(+ self, tmp_path: Path, mocker: MockerFixture+ ) -> None:+ """The load reads the file as its tree's listing recorded it, or not at all: bytes changed since are never read unchecked."""+ (tmp_path / "invoice.html").write_bytes(b"<h1>{{ invoice.number }}</h1>")+ bundle_path = write_bundle(directory=tmp_path, step_fields='format = "pdf"\ntemplate_file = "invoice.html"')+ hold_tree = LOCAL_METHOD_FILES.hold_tree++ def hold_then_change(*, holder: str, tree: MethodTree) -> None:+ hold_tree(holder=holder, tree=tree)+ (tmp_path / "invoice.html").write_bytes(b"<h1>{{ invoice.customer }}</h1>")++ mocker.patch.object(LOCAL_METHOD_FILES, "hold_tree", side_effect=hold_then_change)++ with pytest.raises(ValidateBundleError) as exc_info:+ await validate_bundle(mthds_file_path=bundle_path)++ assert "could not read the template file 'invoice.html' as its method tree listed it" in str(exc_info.value.to_error_report().model_dump())+@pytest.mark.usefixtures("stub_engines")@pytest.mark.parametrize("load", ["from_its_directory", "from_content"])async def test_an_html_template_file_reads_the_same_whichever_way_its_bundle_loads(self, tmp_path: Path, load: str) -> None:@@ -135,7 +161,7 @@ class TestPipeDocGenTemplateFiles:(pipe,) = result.pipesassert isinstance(pipe, PipeDocGen)- assert pipe.template == template_bytes.decode("utf-8")+ assert pipe.template_file_text == template_bytes.decode("utf-8")async def test_the_engine_s_checker_findings_fail_the_dry_run(self, tmp_path: Path, stub_engines: StubEngines) -> None:"""The dry run hands the checker the file's bytes, the inputs' shapes and the mock data, and an error finding fails it."""diff --git a/tests/unit/pipelex/cogt/content_generation/test_assignment_read_coverage.py b/tests/unit/pipelex/cogt/content_generation/test_assignment_read_coverage.pyindex cd2ec817c..bf89f738b 100644--- a/tests/unit/pipelex/cogt/content_generation/test_assignment_read_coverage.py+++ b/tests/unit/pipelex/cogt/content_generation/test_assignment_read_coverage.py@@ -32,7 +32,7 @@ from pipelex.cogt.content_generation.assignment_models import (from pipelex.cogt.content_generation.cogt_run_params import CogtRunParamsfrom pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSourcefrom pipelex.cogt.doc_gen.doc_gen_setting import DocGenSetting-from pipelex.cogt.doc_gen.document_composition import DocumentComposition+from pipelex.cogt.doc_gen.document_composition import ComposedTemplateFile, DocumentCompositionfrom pipelex.cogt.doc_gen.layout_tree import ImageBlock, LayoutDocument, SectionBlockfrom pipelex.cogt.document.prompt_document import PromptDocumentUrifrom pipelex.cogt.extract.extract_input import ExtractInput@@ -44,7 +44,7 @@ from pipelex.cogt.judgment.judgment_models import JudgmentPrompt, YesNoQuestionfrom pipelex.cogt.judgment.judgment_setting import JudgmentSettingfrom pipelex.cogt.llm.llm_prompt import LLMPromptfrom pipelex.cogt.llm.llm_setting import LLMSetting-from pipelex.core.bundle_resources.bundle_resource import BundleResource+from pipelex.core.method_trees.tree_bundle import MethodFileReffrom pipelex.system.job_metadata import JobMetadata, RunMetadatafrom pipelex.system.pipe_run_mode import PipeRunModefrom pipelex.tools.uri.uri_read_scope import UriReference@@ -63,8 +63,8 @@ URL_FIELD_INVENTORY: dict[type[BaseModel], set[str]] = {ExtractAssignment: {"extract_input.image_uri", "extract_input.document_uri"},RenderPageViewsAssignment: {"document_uri"},# A section's blocks hold blocks again: the walk names the images inside one section and stops where a section would enclose itself.- # A template file submitted with the bundle and stored with the run is read back by the print stage too.- RenderDocumentAssignment: {"composition.layout.blocks.url", "composition.layout.blocks.blocks.url", "composition.template_resource.uri"},+ # A template file is a method file, named by its tree's digest and read through the method file store, never by a URI.+ RenderDocumentAssignment: {"composition.layout.blocks.url", "composition.layout.blocks.blocks.url"},SearchAssignment: set(),SearchObjectAssignment: set(),JudgmentAssignment: {"prompt.images.uri", "prompt.documents.uri"},@@ -238,9 +238,8 @@ class TestAssignmentReadCoverage:referenced_uris = sample.referenced_uris()assert {uri_reference.uri for uri_reference in referenced_uris} == expected_uris, assignment_class.__name__- def test_a_document_printed_from_a_stored_template_file_declares_it(self) -> None:- """A composition holds a layout or a template file, never both, so the template file's field gets a sample of its own."""- stored_template = BundleResource.make_inline(content=b"template").stored_at(uri="pipelex-storage://s/assets/bundle/invoice.docx")+ def test_a_document_printed_from_a_template_file_declares_no_uri_read(self) -> None:+ """The template file is a file of the step's method tree, read through the method file store under the run's read scope."""assignment = RenderDocumentAssignment(job_metadata=_job_metadata(),cogt_run_params=CogtRunParams(run_mode=PipeRunMode.DRY),@@ -249,15 +248,16 @@ class TestAssignmentReadCoverage:source=DocGenSource.TEMPLATE_FILE,filename="invoice.docx",title="Invoice",- template_resource=stored_template,- template_name="templates/invoice.docx",+ template_file=ComposedTemplateFile(+ file=MethodFileRef(tree_digest="sha256:" + "e" * 64, tree_path="templates/invoice.docx"),+ name="templates/invoice.docx",+ pipe_ref="invoicing.print_invoice",+ ),),doc_gen_setting=DocGenSetting(model="pipelex-docx"),)- referenced_uris = assignment.referenced_uris()-- assert [uri_reference.uri for uri_reference in referenced_uris] == ["pipelex-storage://s/assets/bundle/invoice.docx"]+ assert assignment.referenced_uris() == []def test_the_extract_input_declares_an_image_too(self) -> None:referenced_uris = ExtractInput(image_uri="pipelex-storage://s/scan.png").referenced_uris()diff --git a/tests/unit/pipelex/cogt/content_generation/test_doc_gen_print_template_file.py b/tests/unit/pipelex/cogt/content_generation/test_doc_gen_print_template_file.pynew file mode 100644index 000000000..9da9ed792--- /dev/null+++ b/tests/unit/pipelex/cogt/content_generation/test_doc_gen_print_template_file.py@@ -0,0 +1,96 @@+"""The print stage of a PipeDocGen step reads its template file through the method file store, where IO is allowed.++The compose stage names the file by its tree's digest and its tree path; the print reads it under the run's read scope,+renders an HTML one through the interpreter's template file stage, and hands an office one's bytes to its engine.+"""++import pytest+from pytest_mock import MockerFixture++from pipelex.cogt.content_generation import doc_gen_generate+from pipelex.cogt.content_generation.assignment_models import RenderDocumentAssignment+from pipelex.cogt.content_generation.cogt_run_params import CogtRunParams+from pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSource+from pipelex.cogt.doc_gen.doc_gen_setting import DocGenSetting+from pipelex.cogt.doc_gen.document_composition import ComposedTemplateFile, DocumentComposition, TemplateRenderContext+from pipelex.cogt.doc_gen.exceptions import DocGenRenderError+from pipelex.core.method_trees.tree_bundle import MethodFileRef+from pipelex.system.job_metadata import JobMetadata, RunMetadata+from pipelex.system.pipe_run_mode import PipeRunMode++_FILE = MethodFileRef(tree_digest="sha256:" + "1" * 64, tree_path="templates/invoice.html")+++def _assignment(*, composition: DocumentComposition) -> RenderDocumentAssignment:+ return RenderDocumentAssignment(+ job_metadata=JobMetadata(+ run_metadata=RunMetadata(user_id="u", pipeline_run_id="run_1", storage_scope="acme/runs/run_1", read_scope="acme/runs")+ ),+ cogt_run_params=CogtRunParams(run_mode=PipeRunMode.LIVE),+ composition=composition,+ doc_gen_setting=DocGenSetting(model="pipelex-pdf"),+ )+++def _html_template_file() -> ComposedTemplateFile:+ return ComposedTemplateFile(+ file=_FILE,+ name="templates/invoice.html",+ pipe_ref="invoicing.print_invoice",+ render_context=TemplateRenderContext(crate_fingerprint="", concepts_crate={}, working_memory_raw={}),+ )++[email protected](loop_scope="class")+class TestDocGenPrintTemplateFile:+ async def test_an_html_template_file_is_read_under_the_run_s_read_scope_and_rendered(self, mocker: MockerFixture) -> None:+ read_spy = mocker.patch.object(doc_gen_generate, "read_method_file", new=mocker.AsyncMock(return_value=b"<h1>{{ invoice.number }}</h1>"))+ stage = mocker.MagicMock()+ stage.render_html_template_file = mocker.AsyncMock(return_value="<h1>INV-1</h1>")+ mocker.patch.object(doc_gen_generate, "get_template_file_stage", return_value=stage)+ template_file = _html_template_file()+ composition = DocumentComposition(+ format=DocGenFormat.PDF, source=DocGenSource.HTML, filename="invoice.pdf", title="Invoice", template_file=template_file+ )++ read_template = await doc_gen_generate.read_template_file(render_assignment=_assignment(composition=composition))++ assert read_template.html == "<h1>INV-1</h1>"+ assert read_template.template is None+ read_spy.assert_awaited_once_with(file_ref=_FILE, read_scope="acme/runs")+ stage.render_html_template_file.assert_awaited_once_with(template_file=template_file, template_source="<h1>{{ invoice.number }}</h1>")++ async def test_an_office_template_file_s_bytes_go_to_the_engine_unrendered(self, mocker: MockerFixture) -> None:+ mocker.patch.object(doc_gen_generate, "read_method_file", new=mocker.AsyncMock(return_value=b"PK docx"))+ stage_getter = mocker.patch.object(doc_gen_generate, "get_template_file_stage")+ composition = DocumentComposition(+ format=DocGenFormat.DOCX,+ source=DocGenSource.TEMPLATE_FILE,+ filename="invoice.docx",+ title="Invoice",+ template_file=ComposedTemplateFile(file=_FILE, name="invoice.docx", pipe_ref="invoicing.print_invoice"),+ )++ read_template = await doc_gen_generate.read_template_file(render_assignment=_assignment(composition=composition))++ assert read_template.template == b"PK docx"+ assert read_template.html is None+ stage_getter.assert_not_called()++ async def test_an_html_template_file_that_is_not_utf8_fails_the_print_naming_it(self, mocker: MockerFixture) -> None:+ mocker.patch.object(doc_gen_generate, "read_method_file", new=mocker.AsyncMock(return_value="<p>émise</p>".encode("latin-1")))+ composition = DocumentComposition(+ format=DocGenFormat.PDF, source=DocGenSource.HTML, filename="invoice.pdf", title="Invoice", template_file=_html_template_file()+ )++ with pytest.raises(DocGenRenderError, match=r"'templates/invoice\.html'.*not UTF-8"):+ await doc_gen_generate.read_template_file(render_assignment=_assignment(composition=composition))++ async def test_a_document_printed_from_no_template_file_reads_nothing(self, mocker: MockerFixture) -> None:+ read_spy = mocker.patch.object(doc_gen_generate, "read_method_file", new=mocker.AsyncMock())+ composition = DocumentComposition(format=DocGenFormat.PDF, source=DocGenSource.HTML, filename="invoice.pdf", title="Invoice", html="<p>x</p>")++ read_template = await doc_gen_generate.read_template_file(render_assignment=_assignment(composition=composition))++ assert read_template == (None, None)+ read_spy.assert_not_awaited()diff --git a/tests/unit/pipelex/cogt/doc_gen/test_document_composition.py b/tests/unit/pipelex/cogt/doc_gen/test_document_composition.pyindex d52bd63c2..400b40b44 100644--- a/tests/unit/pipelex/cogt/doc_gen/test_document_composition.py+++ b/tests/unit/pipelex/cogt/doc_gen/test_document_composition.py@@ -1,13 +1,25 @@-from pathlib import Path-import pytestfrom pydantic import ValidationErrorfrom pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat, DocGenSource-from pipelex.cogt.doc_gen.document_composition import DocumentComposition+from pipelex.cogt.doc_gen.document_composition import ComposedTemplateFile, DocumentComposition, TemplateRenderContextfrom pipelex.cogt.doc_gen.layout_tree import ImageBlock, LayoutDocument, SectionBlock-from pipelex.core.bundle_resources.bundle_resource import BundleResource-from pipelex.tools.storage.in_memory_storage_provider import InMemoryStorageProvider+from pipelex.core.method_trees.tree_bundle import MethodFileRef++_TREE_DIGEST = "sha256:" + "a" * 64++_OFFICE_TEMPLATE_FILE = ComposedTemplateFile(+ file=MethodFileRef(tree_digest=_TREE_DIGEST, tree_path="templates/invoice.docx"),+ name="templates/invoice.docx",+ pipe_ref="invoicing.print_invoice",+)++_HTML_TEMPLATE_FILE = ComposedTemplateFile(+ file=MethodFileRef(tree_digest=_TREE_DIGEST, tree_path="templates/report.html"),+ name="templates/report.html",+ pipe_ref="invoicing.print_report",+ render_context=TemplateRenderContext(crate_fingerprint="", concepts_crate={}, working_memory_raw={}),+)class TestDocumentComposition:@@ -48,67 +60,59 @@ class TestDocumentComposition:)assert composition.referenced_uris() == []- @pytest.mark.asyncio- async def test_the_render_job_carries_the_template_file_s_bytes(self, tmp_path: Path) -> None:- template_file = tmp_path / "invoice.docx"- template_file.write_bytes(b"docx bytes")+ def test_the_render_job_carries_what_the_print_stage_read(self) -> None:composition = DocumentComposition(format=DocGenFormat.DOCX,source=DocGenSource.TEMPLATE_FILE,filename="invoice.docx",title="Invoice",- template_path=str(template_file),- template_name="invoice.docx",+ template_file=_OFFICE_TEMPLATE_FILE,data={"invoice": {"number": "INV-1"}},)- job = await composition.make_render_job(storage_provider=InMemoryStorageProvider())+ job = composition.make_render_job(template=b"docx bytes")assert job.template == b"docx bytes"- assert job.template_name == "invoice.docx"+ assert job.template_name == "templates/invoice.docx"assert job.data == {"invoice": {"number": "INV-1"}}- @pytest.mark.asyncio- async def test_a_template_file_submitted_with_its_bundle_is_read_from_its_resource(self) -> None:- """Inline, the bytes are the composition's own; stored, they are read back through the run's storage, under its read scope."""- storage_provider = InMemoryStorageProvider()- inline = BundleResource.make_inline(content=b"docx bytes")- uri = await storage_provider.store(b"docx bytes", key="org/run/assets/bundle/digest/invoice.docx")- stored = inline.stored_at(uri=uri)-- for resource in (inline, stored):- composition = DocumentComposition(- format=DocGenFormat.DOCX,- source=DocGenSource.TEMPLATE_FILE,- filename="invoice.docx",- title="Invoice",- template_resource=resource,- template_name="invoice.docx",- )- job = await composition.make_render_job(storage_provider=storage_provider)- assert job.template == b"docx bytes"+ def test_an_html_template_file_prints_as_the_html_the_print_stage_rendered(self) -> None:+ composition = DocumentComposition(+ format=DocGenFormat.PDF, source=DocGenSource.HTML, filename="report.pdf", title="Report", template_file=_HTML_TEMPLATE_FILE+ )++ job = composition.make_render_job(html="<p>INV-1</p>")++ assert composition.renders_html_template_file+ assert job.html == "<p>INV-1</p>"+ assert job.template is None- stored_composition = DocumentComposition(+ def test_a_template_file_travels_by_its_tree_and_tree_path_never_its_bytes(self) -> None:+ """The composition crosses a workflow boundary, so it names the file and the print stage reads it."""+ composition = DocumentComposition(format=DocGenFormat.DOCX,source=DocGenSource.TEMPLATE_FILE,filename="invoice.docx",title="Invoice",- template_resource=stored,- template_name="invoice.docx",+ template_file=_OFFICE_TEMPLATE_FILE,)- (uri_reference,) = stored_composition.referenced_uris()- assert uri_reference.uri == uri- assert uri_reference.position == "the template file 'invoice.docx'"- def test_a_template_file_read_from_disk_and_from_its_resource_is_refused(self) -> None:+ restored = DocumentComposition.model_validate_json(composition.model_dump_json())++ assert restored == composition+ assert restored.template_file is not None+ assert restored.template_file.file == MethodFileRef(tree_digest=_TREE_DIGEST, tree_path="templates/invoice.docx")+ assert composition.referenced_uris() == []++ def test_rendered_html_and_a_template_file_to_render_are_refused_together(self) -> None:with pytest.raises(ValidationError, match="not both"):DocumentComposition(- format=DocGenFormat.DOCX,- source=DocGenSource.TEMPLATE_FILE,- filename="invoice.docx",- title="Invoice",- template_path="/nowhere/invoice.docx",- template_resource=BundleResource.make_inline(content=b"docx bytes"),+ format=DocGenFormat.PDF,+ source=DocGenSource.HTML,+ filename="report.pdf",+ title="Report",+ html="<p>Report</p>",+ template_file=_HTML_TEMPLATE_FILE,)def test_a_composition_without_its_payload_is_refused(self) -> None:@@ -123,5 +127,5 @@ class TestDocumentComposition:filename="report.pdf",title="Report",html="<p>Report</p>",- template_path="/nowhere/report.docx",+ template_file=_OFFICE_TEMPLATE_FILE,)diff --git a/tests/unit/pipelex/core/bundle_resources/test_bundle_resource.py b/tests/unit/pipelex/core/bundle_resources/test_bundle_resource.pyindex 580a59c2d..f0196998c 100644--- a/tests/unit/pipelex/core/bundle_resources/test_bundle_resource.py+++ b/tests/unit/pipelex/core/bundle_resources/test_bundle_resource.py@@ -1,17 +1,11 @@-import base64-import hashlib-import pytest-from pydantic import ValidationErrorfrom pipelex.core.bundle_resources.bundle_resource import (- BundleResource,canonical_resource_path,canonical_resource_path_or_none,- make_bundle_resources,+ canonical_submitted_files,)-from pipelex.core.bundle_resources.exceptions import BundleResourceError, BundleResourcePathError-from pipelex.tools.storage.in_memory_storage_provider import InMemoryStorageProvider+from pipelex.core.bundle_resources.exceptions import BundleResourcePathErrorclass TestCanonicalResourcePath:@@ -52,65 +46,12 @@ class TestCanonicalResourcePath:assert canonical_resource_path_or_none(path=path) is None-class TestBundleResource:- def test_an_inline_resource_carries_its_bytes_and_their_digest(self) -> None:- resource = BundleResource.make_inline(content=b"docx bytes")-- assert resource.is_inline- assert resource.size == len(b"docx bytes")- assert resource.sha256 == hashlib.sha256(b"docx bytes").hexdigest()- assert resource.content_b64 == base64.b64encode(b"docx bytes").decode("ascii")- assert resource.inline_bytes() == b"docx bytes"-- def test_a_resource_round_trips_through_json(self) -> None:- """A crate carries its resources as JSON, so the bytes travel base64-encoded."""- resource = BundleResource.make_inline(content=bytes(range(256)))-- assert BundleResource.model_validate_json(resource.model_dump_json()) == resource-- @pytest.mark.parametrize(- "fields",- [- {"sha256": "abc", "size": 1},- {"sha256": "abc", "size": 1, "content_b64": "eA==", "uri": "pipelex-storage://run/assets/bundle/abc/x.docx"},- {"sha256": "abc", "size": 1, "uri": "https://example.com/x.docx"},- ],- ids=["neither", "both", "not_a_storage_uri"],- )- def test_a_resource_carries_its_bytes_one_way(self, fields: dict[str, object]) -> None:- """Inline or by a pipelex-storage reference, exactly one of the two."""- with pytest.raises(ValidationError):- BundleResource.model_validate(fields)-- @pytest.mark.asyncio- async def test_a_stored_resource_is_read_back_and_checked_against_its_digest(self) -> None:- storage_provider = InMemoryStorageProvider()- resource = BundleResource.make_inline(content=b"docx bytes")- uri = await storage_provider.store(b"docx bytes", key="run/assets/bundle/digest/invoice.docx")- stored = resource.stored_at(uri=uri)-- assert not stored.is_inline- assert await stored.read_bytes(storage_provider=storage_provider) == b"docx bytes"- with pytest.raises(BundleResourceError):- stored.inline_bytes()-- @pytest.mark.asyncio- async def test_stored_bytes_that_changed_are_refused(self) -> None:- storage_provider = InMemoryStorageProvider()- uri = await storage_provider.store(b"other bytes", key="run/assets/bundle/digest/invoice.docx")- stored = BundleResource.make_inline(content=b"docx bytes").stored_at(uri=uri)-- with pytest.raises(BundleResourceError, match="no longer matches"):- await stored.read_bytes(storage_provider=storage_provider)---class TestMakeBundleResources:+class TestCanonicalSubmittedFiles:def test_files_are_keyed_by_their_canonical_path(self) -> None:- resources = make_bundle_resources(files={"./invoice.docx": b"docx", "templates/report.html": b"<h1></h1>"})+ files = canonical_submitted_files(files={"./invoice.docx": b"docx", "templates/report.html": b"<h1></h1>"})- assert set(resources) == {"invoice.docx", "templates/report.html"}- assert resources["invoice.docx"].inline_bytes() == b"docx"+ assert files == {"invoice.docx": b"docx", "templates/report.html": b"<h1></h1>"}def test_two_spellings_of_one_file_are_refused(self) -> None:with pytest.raises(BundleResourcePathError, match="name the same file"):- make_bundle_resources(files={"invoice.docx": b"a", "./invoice.docx": b"b"})+ canonical_submitted_files(files={"invoice.docx": b"a", "./invoice.docx": b"b"})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.pyindex e960b4090..c033d5dc0 100644--- a/tests/unit/pipelex/core/bundle_resources/test_bundle_resource_exceptions.py+++ b/tests/unit/pipelex/core/bundle_resources/test_bundle_resource_exceptions.py@@ -1,15 +1,11 @@import pytestfrom pipelex.base_exceptions import DisclosureMode, ErrorDomain, PipelexError-from pipelex.core.bundle_resources.exceptions import (- BundleResourceNotNamedError,- BundleResourcePathError,- BundleResourcesTooLargeError,-)+from pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError, BundleResourcePathErrorclass TestBundleResourceExceptions:- @pytest.mark.parametrize("error_class", [BundleResourceNotNamedError, BundleResourcesTooLargeError, BundleResourcePathError])+ @pytest.mark.parametrize("error_class", [BundleResourceNotNamedError, 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()diff --git a/tests/unit/pipelex/core/method_trees/conftest.py b/tests/unit/pipelex/core/method_trees/conftest.pyindex df42b3515..291ae5134 100644--- a/tests/unit/pipelex/core/method_trees/conftest.py+++ b/tests/unit/pipelex/core/method_trees/conftest.py@@ -2,6 +2,7 @@ from collections.abc import Iteratorimport pytest+from pipelex.core.method_trees.method_file_store import LocalMethodFileStorefrom pipelex.core.method_trees.tree_python import TREE_PYTHON_HOLD@@ -11,3 +12,9 @@ def released_hold() -> Iterator[None]:yieldTREE_PYTHON_HOLD.release_all()TREE_PYTHON_HOLD.unload_if_unheld()+++def store() -> LocalMethodFileStore:+ """A method file store of the test's own, holding nothing."""+ return LocalMethodFileStore()diff --git a/tests/unit/pipelex/core/method_trees/test_crate_file_references.py b/tests/unit/pipelex/core/method_trees/test_crate_file_references.pynew file mode 100644index 000000000..22ae56610--- /dev/null+++ b/tests/unit/pipelex/core/method_trees/test_crate_file_references.py@@ -0,0 +1,50 @@+import pytest+from mthds.method_tree.exceptions import MethodTreeRefusedError++from pipelex.core.method_trees.file_references import resolve_crate_file_reference+from pipelex.core.method_trees.tree_bundle import TreeBundleRef++_TREE_DIGEST = "sha256:" + "f" * 64+++class TestCrateFileReferences:+ """A pipe built from a crate resolves the file its bundle names lexically, reading nothing: the crate carries no listing."""++ @pytest.mark.parametrize(+ ("tree_path", "reference", "expected"),+ [+ ("main.mthds", "templates/invoice.docx", "templates/invoice.docx"),+ ("bundles/invoice.mthds", "../templates/invoice.html", "templates/invoice.html"),+ ("bundles/invoice.mthds", "./invoice.html", "bundles/invoice.html"),+ (None, "templates/invoice.docx", "templates/invoice.docx"),+ (None, "templates//invoice.docx", "templates/invoice.docx"),+ (None, "./templates/./invoice.docx", "templates/invoice.docx"),+ ],+ ids=[+ "beside_the_bundle",+ "climbing_in_the_tree",+ "dot_segment",+ "content_string_at_the_root",+ "repeated_slash_at_the_root",+ "dot_segments_at_the_root",+ ],+ )+ def test_a_reference_joins_the_bundle_s_tree_path(self, tree_path: str | None, reference: str, expected: str) -> None:+ tree_bundle_ref = TreeBundleRef(tree_digest=_TREE_DIGEST, tree_path=tree_path)++ assert resolve_crate_file_reference(reference=reference, tree_bundle_ref=tree_bundle_ref) == expected++ @pytest.mark.parametrize(+ ("tree_path", "reference", "reason"),+ [+ ("main.mthds", "../outside.docx", "climbs above the root"),+ (None, "../outside.docx", "climbs above the root"),+ ("main.mthds", "/etc/invoice.docx", "cannot name a file of a method tree"),+ ],+ ids=["climbs_above_the_root", "climbs_from_the_root", "absolute"],+ )+ def test_a_reference_no_tree_can_hold_is_refused(self, tree_path: str | None, reference: str, reason: str) -> None:+ tree_bundle_ref = TreeBundleRef(tree_digest=_TREE_DIGEST, tree_path=tree_path)++ with pytest.raises(MethodTreeRefusedError, match=reason):+ resolve_crate_file_reference(reference=reference, tree_bundle_ref=tree_bundle_ref)diff --git a/tests/unit/pipelex/core/method_trees/test_method_file_store.py b/tests/unit/pipelex/core/method_trees/test_method_file_store.pynew file mode 100644index 000000000..dc63af50e--- /dev/null+++ b/tests/unit/pipelex/core/method_trees/test_method_file_store.py@@ -0,0 +1,140 @@+import asyncio+from pathlib import Path++import pytest+from mthds.method_tree.digest import digest_of_contents, sha256_hex, tree_files_from_contents, tree_listing+from mthds.method_tree.lister import list_method_tree+from pytest_mock import MockerFixture++from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES, HeldFile, LocalMethodFileStore, tree_of_held_files+from pipelex.runtime_hub import get_method_file_store++_FILES = {"main.mthds": b'domain = "letters"\n', "templates/letter.html": b"<p>{{ name }}</p>\n", "logo.png": bytes(range(64))}+++def _held(files: dict[str, bytes]) -> dict[str, HeldFile]:+ return {path: HeldFile.of_bytes(data=data) for path, data in files.items()}+++class TestLocalMethodFileStore:+ def test_a_tree_of_held_files_has_the_digest_of_the_same_files_anywhere(self) -> None:+ tree = tree_of_held_files(files=_held(_FILES))++ assert tree.digest == digest_of_contents(_FILES)+ assert tree.directory is None+ assert tree.tree_paths == sorted(_FILES)++ @pytest.mark.asyncio+ async def test_a_held_tree_serves_its_listing_and_its_files(self, store: LocalMethodFileStore) -> None:+ tree = store.hold_files(holder="library", files=_held(_FILES))++ listing = await store.read_tree_listing(tree_digest=tree.digest, read_scope=None)++ assert listing == tree_listing(tree_files_from_contents(_FILES))+ assert await store.read_blob(sha256=sha256_hex(_FILES["logo.png"]), read_scope=None) == _FILES["logo.png"]+ assert store.read_held_file(tree_digest=tree.digest, tree_path="templates/letter.html") == _FILES["templates/letter.html"]++ @pytest.mark.asyncio+ async def test_a_tree_is_served_until_its_last_holder_releases_it(self, store: LocalMethodFileStore) -> None:+ tree = store.hold_files(holder="first", files=_held(_FILES))+ store.hold_files(holder="second", files=_held(_FILES))++ store.release(holder="first")+ assert store.held_tree(tree_digest=tree.digest) is not None++ store.release(holder="second")+ assert store.held_tree(tree_digest=tree.digest) is None+ assert await store.read_tree_listing(tree_digest=tree.digest, read_scope=None) is None+ assert await store.read_blob(sha256=sha256_hex(_FILES["logo.png"]), read_scope=None) is None++ def test_a_tree_listed_from_a_directory_is_read_from_it(self, store: LocalMethodFileStore, tmp_path: Path) -> None:+ (tmp_path / "templates").mkdir()+ for tree_path, data in _FILES.items():+ (tmp_path / tree_path).write_bytes(data)+ tree = list_method_tree(tmp_path)++ store.hold_tree(holder="library", tree=tree)++ assert store.read_held_file(tree_digest=tree.digest, tree_path="logo.png") == _FILES["logo.png"]++ def test_a_file_edited_after_its_tree_was_listed_is_not_served(self, store: LocalMethodFileStore, tmp_path: Path) -> None:+ (tmp_path / "templates").mkdir()+ for tree_path, data in _FILES.items():+ (tmp_path / tree_path).write_bytes(data)+ tree = list_method_tree(tmp_path)+ store.hold_tree(holder="library", tree=tree)++ (tmp_path / "templates" / "letter.html").write_bytes(b"<p>edited</p>\n")++ assert store.read_held_file(tree_digest=tree.digest, tree_path="templates/letter.html") is None++ def test_a_tree_assembled_in_memory_is_held_with_its_files(self, store: LocalMethodFileStore) -> None:+ with pytest.raises(ValueError, match="hold_files"):+ store.hold_tree(holder="library", tree=tree_of_held_files(files=_held(_FILES)))++ def test_the_hub_reads_through_the_local_store_unless_a_plugin_claims_the_slot(self) -> None:+ assert get_method_file_store() is LOCAL_METHOD_FILES++ def test_a_tree_two_libraries_hold_is_served_from_whichever_source_still_holds_its_bytes(+ self, store: LocalMethodFileStore, tmp_path: Path+ ) -> None:+ first_dir = tmp_path / "first"+ second_dir = tmp_path / "second"+ for directory in (first_dir, second_dir):+ (directory / "templates").mkdir(parents=True)+ for tree_path, data in _FILES.items():+ (directory / tree_path).write_bytes(data)+ first_tree = list_method_tree(first_dir)+ second_tree = list_method_tree(second_dir)+ assert first_tree.digest == second_tree.digest+ store.hold_tree(holder="first", tree=first_tree)+ store.hold_tree(holder="second", tree=second_tree)++ (first_dir / "logo.png").unlink()++ assert store.read_held_file(tree_digest=first_tree.digest, tree_path="logo.png") == _FILES["logo.png"]+ store.release(holder="second")+ assert store.read_held_file(tree_digest=first_tree.digest, tree_path="logo.png") is None+ assert store.read_held_file(tree_digest=first_tree.digest, tree_path="main.mthds") == _FILES["main.mthds"]++ def test_a_tree_held_again_by_its_holder_keeps_its_first_sources(self, store: LocalMethodFileStore) -> None:+ tree = store.hold_files(holder="library", files=_held(_FILES))++ assert store.holds(holder="library", tree_digest=tree.digest)+ store.hold_files(holder="library", files=_held(_FILES))++ assert len(store.held_files_with_hash(sha256=sha256_hex(_FILES["logo.png"]))) == 1+ assert not store.holds(holder="other", tree_digest=tree.digest)++ @pytest.mark.asyncio+ async def test_the_index_by_hash_follows_holds_and_releases(self, store: LocalMethodFileStore) -> None:+ logo_sha256 = sha256_hex(_FILES["logo.png"])+ store.hold_files(holder="first", files=_held(_FILES))+ store.hold_files(holder="second", files=_held({"assets/logo.png": _FILES["logo.png"]}))+ assert len(store.held_files_with_hash(sha256=logo_sha256)) == 2++ store.release(holder="first")+ assert len(store.held_files_with_hash(sha256=logo_sha256)) == 1+ assert store.held_files_with_hash(sha256=sha256_hex(_FILES["main.mthds"])) == []+ assert await store.read_blob(sha256=logo_sha256, read_scope=None) == _FILES["logo.png"]++ store.hold_files(holder="third", files=_held(_FILES))+ store.release_all()+ assert store.held_files_with_hash(sha256=logo_sha256) == []+ assert await store.read_blob(sha256=logo_sha256, read_scope=None) is None++ @pytest.mark.asyncio+ async def test_a_blob_on_disk_is_read_off_the_event_loop_and_checked_against_its_hash(+ self, store: LocalMethodFileStore, tmp_path: Path, mocker: MockerFixture+ ) -> None:+ (tmp_path / "templates").mkdir()+ for tree_path, data in _FILES.items():+ (tmp_path / tree_path).write_bytes(data)+ store.hold_tree(holder="library", tree=list_method_tree(tmp_path))+ to_thread_spy = mocker.spy(asyncio, "to_thread")++ assert await store.read_blob(sha256=sha256_hex(_FILES["logo.png"]), read_scope=None) == _FILES["logo.png"]+ to_thread_spy.assert_called_once()++ (tmp_path / "logo.png").write_bytes(b"edited")+ assert await store.read_blob(sha256=sha256_hex(_FILES["logo.png"]), read_scope=None) is Nonediff --git a/tests/unit/pipelex/core/method_trees/test_method_files.py b/tests/unit/pipelex/core/method_trees/test_method_files.pynew file mode 100644index 000000000..985d470f6--- /dev/null+++ b/tests/unit/pipelex/core/method_trees/test_method_files.py@@ -0,0 +1,117 @@+import re++import pytest+from mthds.method_tree.digest import DIGEST_PREFIX, digest_of_contents, sha256_hex, tree_files_from_contents, tree_listing+from pytest_mock import MockerFixture++from pipelex.core.method_trees.exceptions import MethodFileUnavailableError+from pipelex.core.method_trees.method_file_store import HeldFile, LocalMethodFileStore+from pipelex.core.method_trees.method_files import StoredTree, TreeListing, read_method_file, read_stored_trees, read_tree_files, read_tree_listing+from pipelex.core.method_trees.tree_bundle import MethodFileRef++_FILES = {"main.mthds": b'domain = "letters"\n', "templates/letter.html": b"<p>{{ name }}</p>\n", "logo.png": bytes(range(64))}+++def _held(files: dict[str, bytes]) -> dict[str, HeldFile]:+ return {path: HeldFile.of_bytes(data=data) for path, data in files.items()}+++class TestMethodFiles:+ @pytest.fixture(autouse=True)+ def _isolated_store(self, mocker: MockerFixture, store: LocalMethodFileStore) -> None:+ mocker.patch("pipelex.core.method_trees.method_files.get_method_file_store", return_value=store)++ def test_a_listing_is_checked_against_the_digest_that_names_it(self) -> None:+ listing = tree_listing(tree_files_from_contents(_FILES))++ parsed = TreeListing.parse(tree_digest=digest_of_contents(_FILES), listing=listing)++ assert parsed.files == {tree_path: sha256_hex(data) for tree_path, data in _FILES.items()}+ with pytest.raises(MethodFileUnavailableError, match="not the one its digest names"):+ TreeListing.parse(tree_digest=digest_of_contents({"other.txt": b"x"}), listing=listing)++ @pytest.mark.asyncio+ async def test_a_method_file_is_read_by_its_tree_and_tree_path(self, store: LocalMethodFileStore) -> None:+ tree = store.hold_files(holder="library", files=_held(_FILES))++ data = await read_method_file(file_ref=MethodFileRef(tree_digest=tree.digest, tree_path="templates/letter.html"), read_scope=None)++ assert data == _FILES["templates/letter.html"]++ @pytest.mark.asyncio+ async def test_a_file_the_tree_does_not_hold_is_refused_naming_it(self, store: LocalMethodFileStore) -> None:+ tree = store.hold_files(holder="library", files=_held(_FILES))++ with pytest.raises(MethodFileUnavailableError, match=re.escape("holds no file 'templates/missing.html'")):+ await read_method_file(file_ref=MethodFileRef(tree_digest=tree.digest, tree_path="templates/missing.html"), read_scope=None)++ @pytest.mark.asyncio+ async def test_bytes_the_store_serves_wrong_are_refused(self, store: LocalMethodFileStore, mocker: MockerFixture) -> None:+ tree = store.hold_files(holder="library", files=_held(_FILES))+ mocker.patch.object(store, "read_blob", return_value=b"tampered")++ with pytest.raises(MethodFileUnavailableError, match="are not the file's"):+ await read_tree_files(tree_digest=tree.digest, read_scope="org/acme")++ @pytest.mark.asyncio+ async def test_the_read_scope_reaches_the_store(self, store: LocalMethodFileStore, mocker: MockerFixture) -> None:+ tree = store.hold_files(holder="library", files=_held(_FILES))+ read_tree_listing_spy = mocker.spy(store, "read_tree_listing")++ listing = await read_tree_listing(tree_digest=tree.digest, read_scope="org/acme")++ assert set(listing.files) == set(_FILES)+ read_tree_listing_spy.assert_called_once_with(tree_digest=tree.digest, read_scope="org/acme")++ @pytest.mark.asyncio+ async def test_a_filter_reads_only_the_files_it_keeps(self, store: LocalMethodFileStore) -> None:+ tree = store.hold_files(holder="library", files=_held(_FILES))++ files = await read_tree_files(tree_digest=tree.digest, read_scope=None, keeps=lambda tree_path: tree_path.endswith(".png"))++ assert files == {"logo.png": _FILES["logo.png"]}++ def test_a_listing_splits_on_line_feeds_alone(self) -> None:+ """U+2028 and U+2029 may sit in a tree path, and `str.splitlines` would split a line on either."""+ files = {"notes/line\u2028separator.txt": b"a", "notes/paragraph\u2029separator.txt": b"b", "main.mthds": b"c"}+ listing = tree_listing(tree_files_from_contents(files))++ parsed = TreeListing.parse(tree_digest=digest_of_contents(files), listing=listing)++ assert parsed.files == {tree_path: sha256_hex(data) for tree_path, data in files.items()}++ def test_a_listing_whose_last_line_has_no_line_feed_is_refused(self) -> None:+ """A listing its digest names, but whose last line has lost its line feed, is not one the standard writes."""+ truncated = tree_listing(tree_files_from_contents(_FILES)).rstrip(b"\n")++ with pytest.raises(MethodFileUnavailableError, match="does not end with a line feed"):+ TreeListing.parse(tree_digest=DIGEST_PREFIX + sha256_hex(truncated), listing=truncated)++ def test_an_empty_listing_names_an_empty_tree(self) -> None:+ assert TreeListing.parse(tree_digest=digest_of_contents({}), listing=b"").files == {}++ @pytest.mark.asyncio+ async def test_the_trees_a_job_names_are_read_as_a_store_keeps_them(self, store: LocalMethodFileStore) -> None:+ """Each tree once, its listing under its digest and each distinct file once, under its hash, read under the run's read scope."""+ tree = store.hold_files(holder="library", files=_held({**_FILES, "copy/logo.png": _FILES["logo.png"]}))+ other = store.hold_files(holder="library", files=_held({"notes.txt": b"notes"}))++ stored_trees = await read_stored_trees(tree_digests=[tree.digest, other.digest], read_scope="org/acme")++ assert stored_trees == [+ StoredTree(+ tree_digest=tree.digest,+ listing=tree_listing(tree_files_from_contents({**_FILES, "copy/logo.png": _FILES["logo.png"]})),+ blobs={sha256_hex(data): data for data in _FILES.values()},+ ),+ StoredTree(+ tree_digest=other.digest,+ listing=tree_listing(tree_files_from_contents({"notes.txt": b"notes"})),+ blobs={sha256_hex(b"notes"): b"notes"},+ ),+ ]++ @pytest.mark.asyncio+ async def test_a_tree_no_library_holds_cannot_be_copied(self) -> None:+ with pytest.raises(MethodFileUnavailableError, match="holds no tree"):+ await read_stored_trees(tree_digests=[digest_of_contents({"gone.txt": b"gone"})], read_scope=None)diff --git a/tests/unit/pipelex/core/method_trees/test_tree_files.py b/tests/unit/pipelex/core/method_trees/test_tree_files.pyindex 97d2d14e5..2a7d7edc1 100644--- a/tests/unit/pipelex/core/method_trees/test_tree_files.py+++ b/tests/unit/pipelex/core/method_trees/test_tree_files.py@@ -3,26 +3,26 @@ from pathlib import Pathimport pytestfrom mthds.method_tree.lister import list_method_tree-from pipelex.core.method_trees.exceptions import TreePythonError-from pipelex.core.method_trees.tree_files import Base64FileEntry, encode_tree_file, read_call_files, tree_file_bytes, write_call_files-from pipelex.libraries.pipe_func_call_files import travels_with_call+from pipelex.core.method_trees.exceptions import MethodFileUnavailableError, TreePythonError+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES+from pipelex.core.method_trees.tree_files import write_call_files+from pipelex.libraries.pipe_func_call_files import read_pipe_func_call_files, travels_with_call_PNG_BYTES = b"\x89PNG\r\n\x1a\n\x00\x00"+_HOLDER = "test_tree_files"+++def released_holder():+ yield _HOLDER+ LOCAL_METHOD_FILES.release(holder=_HOLDER)class TestTreeFiles:- @pytest.mark.parametrize(- ("data", "is_text"),- [pytest.param(b"VAT_RATE = 0.2\n", True, id="utf-8-text"), pytest.param(_PNG_BYTES, False, id="binary")],- )- def test_a_file_travels_as_its_text_or_in_base64_and_round_trips(self, data: bytes, is_text: bool) -> None:- entry = encode_tree_file(data=data)-- assert isinstance(entry, str) is is_text- assert isinstance(entry, Base64FileEntry) is not is_text- assert tree_file_bytes(entry=entry) == data-- def test_a_call_receives_every_file_of_the_tree_but_its_bundles_and_what_the_tree_excludes(self, tmp_path: Path) -> None:+ @pytest.mark.asyncio+ async def test_a_call_receives_every_file_of_the_tree_but_its_bundles_and_what_the_tree_excludes(+ self, tmp_path: Path, released_holder: str+ ) -> None:method_dir = tmp_path / "invoicing"(method_dir / "funcs").mkdir(parents=True)(method_dir / "invoicing.mthds").write_text('domain = "invoicing"\n', encoding="utf-8")@@ -30,33 +30,26 @@ class TestTreeFiles:(method_dir / "logo.png").write_bytes(_PNG_BYTES)(method_dir / ".gitignore").write_text("scratch.py\n", encoding="utf-8")(method_dir / "scratch.py").write_text("NOT_SHIPPED = True\n", encoding="utf-8")- (method_dir / "structures.py").write_text(- "# Generated by Pipelex\nfrom pipelex.core.stuffs.structured_content import StructuredContent\n", encoding="utf-8"- )-- files = read_call_files(tree=list_method_tree(method_dir))-- assert sorted(files) == ["funcs/totals.py", "logo.png", "structures.py"]- assert files["funcs/totals.py"] == "TOTAL = 1\n"- assert files["logo.png"] == Base64FileEntry.make_from_bytes(_PNG_BYTES)+ tree = list_method_tree(method_dir)+ LOCAL_METHOD_FILES.hold_tree(holder=released_holder, tree=tree)- def test_a_filter_keeps_a_file_out_of_the_call(self, tmp_path: Path) -> None:- method_dir = tmp_path / "filtered"- method_dir.mkdir()- (method_dir / "filtered.mthds").write_text('domain = "filtered"\n', encoding="utf-8")- (method_dir / "helpers.py").write_text("X = 1\n", encoding="utf-8")+ files = await read_pipe_func_call_files(tree_digest=tree.digest, read_scope=None)- def _keeps(*, tree_path: str, data: bytes) -> bool:- return tree_path != "helpers.py" and bool(data)+ assert sorted(files) == ["funcs/totals.py", "logo.png"]+ assert files["funcs/totals.py"] == b"TOTAL = 1\n"+ assert files["logo.png"] == _PNG_BYTES- files = read_call_files(tree=list_method_tree(method_dir), keeps=_keeps)+ @pytest.mark.asyncio+ async def test_a_tree_no_library_holds_cannot_be_read(self) -> None:+ with pytest.raises(MethodFileUnavailableError, match="holds no tree"):+ await read_pipe_func_call_files(tree_digest="sha256:" + "0" * 64, read_scope=None)- assert files == {}+ def test_a_file_that_is_not_a_generated_structures_module_travels(self) -> None:assert travels_with_call(tree_path="logo.png", data=_PNG_BYTES)assert travels_with_call(tree_path="helpers.py", data=b"X = 1\n")def test_the_files_a_call_received_are_written_at_their_tree_paths(self, tmp_path: Path) -> None:- write_call_files(files={"funcs/totals.py": "TOTAL = 1\n", "logo.png": Base64FileEntry.make_from_bytes(_PNG_BYTES)}, destination=tmp_path)+ write_call_files(files={"funcs/totals.py": b"TOTAL = 1\n", "logo.png": _PNG_BYTES}, destination=tmp_path)assert (tmp_path / "funcs" / "totals.py").read_text(encoding="utf-8") == "TOTAL = 1\n"assert (tmp_path / "logo.png").read_bytes() == _PNG_BYTES@@ -67,6 +60,7 @@ class TestTreeFiles:destination.mkdir()with pytest.raises(TreePythonError, match="which is not a tree path"):- write_call_files(files={tree_path: "X = 1\n"}, destination=destination)+ write_call_files(files={"first.py": b"X = 1\n", tree_path: b"X = 1\n"}, destination=destination)assert not (tmp_path / "escape.py").exists()+ assert not (destination / "first.py").exists()diff --git a/tests/unit/pipelex/errors/test_error_pages_generator.py b/tests/unit/pipelex/errors/test_error_pages_generator.pyindex c5d65a7b8..032f97464 100644--- a/tests/unit/pipelex/errors/test_error_pages_generator.py+++ b/tests/unit/pipelex/errors/test_error_pages_generator.py@@ -8,7 +8,8 @@ from typing import TYPE_CHECKINGimport pytestfrom pipelex.base_exceptions import PipelexError-from pipelex.core.bundle_resources.exceptions import BundleResourceError, BundleResourceNotNamedError+from pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError+from pipelex.core.method_trees.exceptions import MethodFileUnavailableErrorfrom pipelex.errors.error_pages_generator import (_MACRO_SECTIONS, # pyright: ignore[reportPrivateUsage]AUTHORED_MARKER,@@ -127,7 +128,7 @@ class TestErrorPagesGenerator: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)+ assert "`retryable`" not in render_error_page(MethodFileUnavailableError)def test_report_total_sums_four_populations(self) -> None:"""``total`` should equal the sum of ``written`` + ``unchanged`` + ``preserved`` + ``removed``."""diff --git a/tests/unit/pipelex/libraries/test_bundle_resources.py b/tests/unit/pipelex/libraries/test_bundle_resources.pyindex 785fc7040..135741425 100644--- a/tests/unit/pipelex/libraries/test_bundle_resources.py+++ b/tests/unit/pipelex/libraries/test_bundle_resources.py@@ -1,22 +1,12 @@-import mimetypesimport reimport 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-from pipelex.libraries.bundle_resources import (- BUNDLE_RESOURCES_STORAGE_PREFIX,- bundle_resource_reads,- check_bundle_resources,- relocate_run_resources,-)-from pipelex.libraries.library_crate import LibraryCrate++from pipelex.core.bundle_resources.exceptions import BundleResourceNotNamedError+from pipelex.libraries.bundle_resources import check_submitted_files, named_bundle_filesfrom pipelex.libraries.library_crate_factory import LibraryCrateFactoryfrom pipelex.mthds_parsing.parser import MthdsParserfrom pipelex.mthds_parsing.pipelex_bundle_blueprint import PipelexBundleBlueprint-from pipelex.tools.storage.in_memory_storage_provider import InMemoryStorageProvider_BUNDLE = """domain = "bundle_resources_tests"@@ -47,140 +37,29 @@ 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)-class TestBundleResources:- def test_each_named_file_is_keyed_by_its_canonical_path_with_when_it_is_read(self) -> None:- """An office template is read when its step runs, an HTML template when the method loads."""- reads = bundle_resource_reads(pipe_blueprints=(_blueprint().pipe or {}).values())+class TestSubmittedFiles:+ def test_each_named_file_is_keyed_by_its_canonical_path(self) -> None:+ named = named_bundle_files(pipe_blueprints=(_blueprint().pipe or {}).values())- assert reads == {"templates/report.docx": BundleResourceReadStage.RUN, "summary.html": BundleResourceReadStage.LOAD}+ assert named == {"templates/report.docx", "summary.html"}def test_files_the_steps_name_pass_whatever_their_spelling(self) -> None:- resources = make_bundle_resources(files={"templates/report.docx": b"docx", "./summary.html": b"<h1></h1>"})-- check_bundle_resources(blueprints=[_blueprint()], bundle_resources=resources)+ check_submitted_files(blueprints=[_blueprint()], submitted_files={"templates//report.docx": b"docx", "./summary.html": b"<h1></h1>"})def test_a_file_no_step_names_is_refused_naming_it(self) -> None:- resources = make_bundle_resources(files={"templates/report.docx": b"docx", "report.docx": b"docx", "logo.png": b"png"})-- with pytest.raises(BundleResourceNotNamedError) as exc_info:- check_bundle_resources(blueprints=[_blueprint()], bundle_resources=resources)-- assert "'logo.png', 'report.docx'" in exc_info.value.message- assert "templates/report.docx" not in exc_info.value.message-- def test_files_read_at_load_over_the_bound_are_refused_naming_them_and_the_limit(self) -> None:- """An HTML template travels inline with the method wherever it runs, so its size is bounded when the bundle loads."""- resources = make_bundle_resources(files={"summary.html": b"x" * (MAX_LOAD_STAGE_RESOURCES_BYTES + 1)})-- with pytest.raises(BundleResourcesTooLargeError) as exc_info:- check_bundle_resources(blueprints=[_blueprint()], bundle_resources=resources)-- assert "('summary.html')" in exc_info.value.message- assert f"{MAX_LOAD_STAGE_RESOURCES_BYTES // 1024} KiB limit" in exc_info.value.message-- def test_a_file_read_when_its_step_runs_is_not_bounded_by_the_load_stage_limit(self) -> None:- """An office template moves to the run's storage before the run leaves the process, so only the request bounds it."""- resources = make_bundle_resources(- files={"templates/report.docx": b"x" * (MAX_LOAD_STAGE_RESOURCES_BYTES + 1), "summary.html": b"<h1></h1>"},- )-- check_bundle_resources(blueprints=[_blueprint()], bundle_resources=resources)-- @pytest.mark.asyncio- async def test_a_file_read_when_its_step_runs_is_stored_and_carried_by_reference(self) -> None:- """The office template moves to the run's storage; the HTML template, read at load, stays inline."""- storage_provider = InMemoryStorageProvider()- 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)-- relocated = await relocate_run_resources(crate=crate, storage_provider=storage_provider, storage_scope="org/method/run")-- stored = relocated.bundle_resources["templates/report.docx"]- assert stored.uri == f"pipelex-storage://org/method/run/{BUNDLE_RESOURCES_STORAGE_PREFIX}/{stored.sha256}/report.docx"- assert stored.content_b64 is None- assert await stored.read_bytes(storage_provider=storage_provider) == b"docx bytes"- assert relocated.bundle_resources["summary.html"].is_inline- # The crate the run was built from is left as it was.- 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()])-- relocated = await relocate_run_resources(crate=crate, storage_provider=InMemoryStorageProvider(), storage_scope="run")-- assert relocated is crate-- def test_resources_round_trip_and_stay_out_of_the_fingerprint(self) -> None:- """Like the files a PipeFunc call receives, the files travel with the crate but are not part of its structure."""- resources = make_bundle_resources(files={"templates/report.docx": b"docx bytes"})- bare = LibraryCrateFactory.make_from_blueprints([_blueprint()])- with_resources = LibraryCrateFactory.make_from_blueprints([_blueprint()], bundle_resources=resources)-- restored = LibraryCrate.model_validate_json(with_resources.model_dump_json())-- assert restored.bundle_resources == resources- assert bare.fingerprint == with_resources.fingerprint+ with pytest.raises(BundleResourceNotNamedError, match=re.escape("'templates/other.docx'")):+ check_submitted_files(blueprints=[_blueprint()], submitted_files={"templates/other.docx": b"docx"})++ def test_no_file_submitted_is_no_refusal(self) -> None:+ check_submitted_files(blueprints=[_blueprint()], submitted_files={})++ def test_a_bundle_in_no_tree_names_none_in_its_crate(self) -> None:+ """A bundle parsed from a string with no file submitted beside it belongs to no tree."""+ crate = LibraryCrateFactory.make_from_blueprints(blueprints=[_blueprint()])++ assert crate.tree_bundles == {}+ assert crate.tree_digests() == []diff --git a/tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py b/tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.pyindex 3313dd7ff..d4515d48f 100644--- a/tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py+++ b/tests/unit/pipelex/libraries/test_dependency_multi_file_reconciliation.py@@ -111,6 +111,7 @@ class TestDependencyMultiFileReconciliation:manager = LibraryManager()manager._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]library=library,+ library_id="dependency-test",package_address="github.com/org/summary-dep",resolved_dep=self._build_resolved_dep(tmp_path=tmp_path,@@ -140,6 +141,7 @@ class TestDependencyMultiFileReconciliation:manager = LibraryManager()manager._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]library=library,+ library_id="dependency-test",package_address="github.com/org/summary-dep",resolved_dep=self._build_resolved_dep(tmp_path=tmp_path,@@ -166,6 +168,7 @@ class TestDependencyMultiFileReconciliation:with pytest.raises(PipeLibraryError):manager._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]library=library,+ library_id="dependency-test",package_address="github.com/org/summary-dep",resolved_dep=self._build_resolved_dep(tmp_path=tmp_path,diff --git a/tests/unit/pipelex/libraries/test_dependency_pipe_build_refusals.py b/tests/unit/pipelex/libraries/test_dependency_pipe_build_refusals.pyindex 63a638e0c..e0d7b66fd 100644--- a/tests/unit/pipelex/libraries/test_dependency_pipe_build_refusals.py+++ b/tests/unit/pipelex/libraries/test_dependency_pipe_build_refusals.py@@ -66,6 +66,7 @@ class TestDependencyPipeBuildRefusals:mocker.patch.object(get_library_manager(), "get_current_library", return_value=library)LibraryManager()._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]library=library,+ library_id="dependency-test",package_address="github.com/harbour-board/harbour-dep",resolved_dep=resolved_dep,)diff --git a/tests/unit/pipelex/libraries/test_dependency_preliminary_text_export.py b/tests/unit/pipelex/libraries/test_dependency_preliminary_text_export.pyindex f8fe007a0..0d257a392 100644--- a/tests/unit/pipelex/libraries/test_dependency_preliminary_text_export.py+++ b/tests/unit/pipelex/libraries/test_dependency_preliminary_text_export.py@@ -77,6 +77,7 @@ class TestDependencyPreliminaryTextExport:manager = LibraryManager()manager._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]library=library,+ library_id="dependency-test",package_address="github.com/org/review-dep",resolved_dep=self._build_resolved_dep(tmp_path=tmp_path, exported={"make_review"}),)@@ -104,6 +105,7 @@ class TestDependencyPreliminaryTextExport:manager = LibraryManager()manager._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]library=library,+ library_id="dependency-test",package_address="github.com/org/review-dep",resolved_dep=self._build_resolved_dep(tmp_path=tmp_path, exported=set()),)diff --git a/tests/unit/pipelex/libraries/test_dependency_ref_qualification.py b/tests/unit/pipelex/libraries/test_dependency_ref_qualification.pyindex ba6497695..f70fdfeef 100644--- a/tests/unit/pipelex/libraries/test_dependency_ref_qualification.py+++ b/tests/unit/pipelex/libraries/test_dependency_ref_qualification.py@@ -72,6 +72,7 @@ class TestDependencyRefQualification:manager = LibraryManager()manager._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]library=library,+ library_id="dependency-test",package_address="github.com/org/charts-dep",resolved_dep=ResolvedDependency(alias="charts_dep",diff --git a/tests/unit/pipelex/libraries/test_dependency_structure_classes.py b/tests/unit/pipelex/libraries/test_dependency_structure_classes.pyindex 4eebc5bbc..b35c95c9f 100644--- a/tests/unit/pipelex/libraries/test_dependency_structure_classes.py+++ b/tests/unit/pipelex/libraries/test_dependency_structure_classes.py@@ -107,6 +107,7 @@ class TestDependencyStructureClasses:with scoped_current_library(library_id=library_id):library_manager._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]library=library,+ library_id=library_id,resolved_dep=_make_resolved_dep(tmp_path=tmp_path, mthds_content=DEP_NOTES_MTHDS),package_address=DEP_ADDRESS,)@@ -133,6 +134,7 @@ class TestDependencyStructureClasses:with scoped_current_library(library_id=library_id), pytest.raises(LibraryLoadingError, match=cycle_refusal):library_manager._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]library=library,+ library_id=library_id,resolved_dep=_make_resolved_dep(tmp_path=tmp_path, mthds_content=DEP_CYCLIC_NOTES_MTHDS),package_address=DEP_ADDRESS,)@@ -147,6 +149,7 @@ class TestDependencyStructureClasses:with scoped_current_library(library_id=library_id):library_manager._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]library=library,+ library_id=library_id,resolved_dep=_make_resolved_dep(tmp_path=tmp_path, mthds_content=DEP_WITH_ITS_OWN_DEPENDENCY_MTHDS),package_address=DEP_ADDRESS,)diff --git a/tests/unit/pipelex/libraries/test_host_bundle_files.py b/tests/unit/pipelex/libraries/test_host_bundle_files.pyindex e09f6931a..2302ca4e9 100644--- a/tests/unit/pipelex/libraries/test_host_bundle_files.py+++ b/tests/unit/pipelex/libraries/test_host_bundle_files.py@@ -1,11 +1,9 @@from pathlib import Pathimport kajson-import pytestfrom mthds.method_tree.lister import list_method_treefrom pipelex.core.method_trees.tree_bundle import TreeBundle, TreeBundleRef-from pipelex.libraries.exceptions import CrateIntegrityErrorfrom pipelex.libraries.library_crate import LibraryCratefrom pipelex.libraries.library_crate_factory import LibraryCrateFactoryfrom pipelex.libraries.library_manager import MTHDS_METHODS_DIRNAME, find_methods_dirs_from_blueprints@@ -48,7 +46,7 @@ class TestHostBundleFiles:assert from_content.host_bundle_file is Noneassert from_content.source == str(bundle_path)- def test_the_crate_carries_the_tree_of_its_file_loaded_pipes_only(self, tmp_path: Path) -> None:+ def test_the_crate_names_the_tree_of_its_file_loaded_pipes_only(self, tmp_path: Path) -> None:"""A `source` the bundle's text writes on a pipe, or a caller's label, never becomes a tree to read files from."""bundle_path = _write_bundle(directory=tmp_path)other_dir = tmp_path / "other"@@ -61,32 +59,23 @@ class TestHostBundleFiles:crate = LibraryCrateFactory.make_from_blueprints(blueprints=[from_file, from_content])- assert crate.tree_bundles == {"host_files_tests.summarize": TreeBundleRef(tree_key=tree_bundle.tree_key, tree_path="bundle.mthds")}- assert list(crate.method_trees) == [tree_bundle.tree_key]- assert crate.tree_bundles_by_pipe_ref() == {"host_files_tests.summarize": tree_bundle}+ assert crate.tree_bundles == {"host_files_tests.summarize": TreeBundleRef(tree_digest=tree_bundle.tree.digest, tree_path="bundle.mthds")}+ assert crate.tree_digests() == [tree_bundle.tree.digest]assert crate.pipes["host_files_other.summarize"].source == str(bundle_path)- # The trees travel as text, so the crate crosses any boundary a Temporal payload does, kajson's included.+ # The crate names the tree by digest, so it crosses any boundary a Temporal payload does, kajson's included, and+ # carries no path of this host.for round_tripped in (LibraryCrate.model_validate_json(crate.model_dump_json()), kajson.loads(kajson.dumps(crate))):assert isinstance(round_tripped, LibraryCrate)assert round_tripped.fingerprint == crate.fingerprint- assert round_tripped.tree_bundles_by_pipe_ref() == {"host_files_tests.summarize": tree_bundle}- # The trees travel with the crate but are no part of what it is: the fingerprint ignores them.+ assert round_tripped.tree_bundles == crate.tree_bundles+ assert str(tmp_path) not in crate.model_dump_json(include={"tree_bundles"})+ # The trees a crate names are no part of what it is: the fingerprint ignores them.unplaced = LibraryCrateFactory.make_from_blueprints(blueprints=[MthdsParser.make_pipelex_bundle_blueprint(bundle_path=bundle_path), from_content],)- assert unplaced.method_trees == {}+ assert unplaced.tree_bundles == {}assert unplaced.fingerprint == crate.fingerprint- def test_a_crate_naming_a_tree_it_does_not_carry_is_refused(self, tmp_path: Path) -> None:- bundle_path = _write_bundle(directory=tmp_path)- crate = LibraryCrateFactory.make_from_blueprints(blueprints=[MthdsParser.make_pipelex_bundle_blueprint(bundle_path=bundle_path)])- broken = crate.model_copy(- update={"tree_bundles": {"host_files_tests.summarize": TreeBundleRef(tree_key="directory:/x:sha256:0", tree_path="bundle.mthds")}}- )-- with pytest.raises(CrateIntegrityError, match="carries no such tree"):- broken.tree_bundles_by_pipe_ref()-def test_method_packages_are_searched_above_a_file_read_here_only(self, tmp_path: Path) -> None:"""Walking up from a caller's label would search this host's directories wherever the caller pointed."""methods_dir = tmp_path / MTHDS_METHODS_DIRNAMEdiff --git a/tests/unit/pipelex/libraries/test_library_crate_pipe_func_files.py b/tests/unit/pipelex/libraries/test_library_crate_pipe_func_files.pydeleted file mode 100644index 49b8cc07f..000000000--- a/tests/unit/pipelex/libraries/test_library_crate_pipe_func_files.py+++ /dev/null@@ -1,60 +0,0 @@-from typing import ClassVar--from pipelex.core.method_trees.tree_files import Base64FileEntry, TreeFileEntry-from pipelex.libraries.library_crate import SUBMITTED_PYTHON_ROOT_KEY, LibraryCrate-from pipelex.libraries.library_crate_factory import LibraryCrateFactory-from tests.unit.pipelex.libraries.test_library_crate_data import BlueprintSamples---class TestLibraryCratePipeFuncFiles:- """The files a PipeFunc call receives, captured on the crate: they round-trip, but never touch the fingerprint."""-- _FILES: ClassVar[dict[str, dict[str, TreeFileEntry]]] = {- SUBMITTED_PYTHON_ROOT_KEY: {- "funcs/score.py": "from pipelex.core.memory.working_memory import WorkingMemory\n\n\ndef compute_score(working_memory): ...\n",- "structures/weighted_score.py": "from pydantic import BaseModel\n\n\nclass WeightedScore(BaseModel):\n value: float\n",- "data/logo.png": Base64FileEntry(base64="iVBORw0KGgo="),- },- }-- def test_pipe_func_files_default_empty(self):- """A crate built without files carries an empty mapping (local/direct mode)."""- crate = LibraryCrateFactory.make_from_blueprints(blueprints=[BlueprintSamples.SCORING_BUNDLE])- assert crate.pipe_func_files == {}-- def test_pipe_func_files_round_trip(self):- """The files survive a JSON round-trip verbatim, a binary file as its base64, alongside the rest of the crate."""- crate = LibraryCrateFactory.make_from_blueprints(- blueprints=[BlueprintSamples.SCORING_BUNDLE],- pipe_func_files=self._FILES,- )- assert crate.pipe_func_files == self._FILES-- restored = LibraryCrate.model_validate_json(crate.model_dump_json())- assert restored.pipe_func_files == self._FILES- # The rest of the crate is unaffected by carrying files.- assert restored.concepts == crate.concepts- assert restored.pipes == crate.pipes- assert restored.fingerprint == crate.fingerprint-- def test_fingerprint_excludes_pipe_func_files(self):- """The structural fingerprint is identical whether or not files travel, and regardless of their content.-- Folding files into the fingerprint would break load_from_crate's structural-dedupe contract,- so two crates that differ ONLY in pipe_func_files must hash the same.- """- bare = LibraryCrateFactory.make_from_blueprints(blueprints=[BlueprintSamples.SCORING_BUNDLE])- with_files = LibraryCrateFactory.make_from_blueprints(- blueprints=[BlueprintSamples.SCORING_BUNDLE],- pipe_func_files=self._FILES,- )- other_files = LibraryCrateFactory.make_from_blueprints(- blueprints=[BlueprintSamples.SCORING_BUNDLE],- pipe_func_files={SUBMITTED_PYTHON_ROOT_KEY: {"funcs/score.py": "def compute_score(working_memory): return 42\n"}},- )-- assert bare.fingerprint != ""- assert bare.fingerprint == with_files.fingerprint- assert with_files.fingerprint == other_files.fingerprint- # And the instance method agrees: files are not part of compute_fingerprint.- assert with_files.compute_fingerprint() == bare.compute_fingerprint()diff --git a/tests/unit/pipelex/libraries/test_library_crate_tree_digests.py b/tests/unit/pipelex/libraries/test_library_crate_tree_digests.pynew file mode 100644index 000000000..d3feaf62e--- /dev/null+++ b/tests/unit/pipelex/libraries/test_library_crate_tree_digests.py@@ -0,0 +1,74 @@+from pathlib import Path++from pipelex.core.method_trees.method_file_store import HeldFile, tree_of_held_files+from pipelex.core.method_trees.tree_bundle import TreeBundle, TreeBundleRef+from pipelex.libraries.library_crate import LibraryCrate+from pipelex.libraries.library_crate_factory import LibraryCrateFactory+from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipelexBundleBlueprint+from tests.unit.pipelex.libraries.test_library_crate_data import BlueprintSamples+++def _placed_blueprint(*, files: dict[str, bytes], tree_path: str | None) -> PipelexBundleBlueprint:+ blueprint = BlueprintSamples.SCORING_BUNDLE.model_copy(deep=True)+ tree = tree_of_held_files(files={path: HeldFile.of_bytes(data=data) for path, data in files.items()})+ blueprint.place_in_tree(tree_bundle=TreeBundle(tree=tree, tree_path=tree_path))+ return blueprint+++_FILES = {+ "main.mthds": b'domain = "scoring"\n',+ "funcs/score.py": b"def compute_score(working_memory): ...\n",+ "templates/report.docx": bytes(range(256)),+}+++class TestLibraryCrateTreeDigests:+ """A crate names the tree each pipe's bundle belongs to by its digest, and carries none of the tree's files."""++ def test_a_bundle_in_no_tree_names_none(self) -> None:+ crate = LibraryCrateFactory.make_from_blueprints(blueprints=[BlueprintSamples.SCORING_BUNDLE.model_copy(deep=True)])++ assert crate.tree_bundles == {}+ assert crate.tree_digests() == []++ def test_each_pipe_names_its_tree_by_digest_and_its_bundle_by_tree_path(self) -> None:+ blueprint = _placed_blueprint(files=_FILES, tree_path="main.mthds")+ tree_bundle = blueprint.tree_bundle+ assert tree_bundle is not None++ crate = LibraryCrateFactory.make_from_blueprints(blueprints=[blueprint])++ assert crate.tree_bundles+ expected_ref = TreeBundleRef(tree_digest=tree_bundle.tree.digest, tree_path="main.mthds")+ assert all(tree_bundle_ref == expected_ref for tree_bundle_ref in crate.tree_bundles.values())+ assert crate.tree_digests() == [tree_bundle.tree.digest]++ def test_bundles_parsed_from_content_strings_name_their_tree_with_no_tree_path(self) -> None:+ crate = LibraryCrateFactory.make_from_blueprints(blueprints=[_placed_blueprint(files=_FILES, tree_path=None)])++ assert {tree_bundle_ref.tree_path for tree_bundle_ref in crate.tree_bundles.values()} == {None}++ def test_the_crate_carries_no_file_nor_host_path(self, tmp_path: Path) -> None:+ crate = LibraryCrateFactory.make_from_blueprints(blueprints=[_placed_blueprint(files=_FILES, tree_path="main.mthds")])+ crate_json = crate.model_dump_json()++ assert "compute_score(working_memory): ..." not in crate_json+ assert "funcs/score.py" not in crate_json+ assert str(tmp_path) not in crate_json+ assert set(LibraryCrate.model_fields) >= {"tree_bundles"}+ assert not {"pipe_func_files", "bundle_resources", "method_trees"} & set(LibraryCrate.model_fields)++ def test_tree_references_round_trip_and_stay_out_of_the_fingerprint(self) -> None:+ bare = LibraryCrateFactory.make_from_blueprints(blueprints=[BlueprintSamples.SCORING_BUNDLE.model_copy(deep=True)])+ placed = LibraryCrateFactory.make_from_blueprints(blueprints=[_placed_blueprint(files=_FILES, tree_path="main.mthds")])+ other_tree = LibraryCrateFactory.make_from_blueprints(+ blueprints=[+ _placed_blueprint(files={**_FILES, "funcs/score.py": b"def compute_score(working_memory): return 42\n"}, tree_path="main.mthds")+ ]+ )++ restored = LibraryCrate.model_validate_json(placed.model_dump_json())+ assert restored.tree_bundles == placed.tree_bundles+ assert bare.fingerprint != ""+ assert bare.fingerprint == placed.fingerprint == other_tree.fingerprint+ assert placed.tree_digests() != other_tree.tree_digests()diff --git a/tests/unit/pipelex/libraries/test_library_tree_holds.py b/tests/unit/pipelex/libraries/test_library_tree_holds.pynew file mode 100644index 000000000..8bafcb367--- /dev/null+++ b/tests/unit/pipelex/libraries/test_library_tree_holds.py@@ -0,0 +1,43 @@+from pathlib import Path++from pytest_mock import MockerFixture++from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES+from pipelex.interpreter_hub import get_library_manager, scoped_current_library++_MANIFEST = '[package]\naddress = "github.com/pipelex-tests/tree-holds"\nversion = "1.0.0"\ndescription = "A method of several bundles"\n'+++def _bundle(*, domain: str) -> str:+ return f"""+domain = "{domain}"++[pipe.greet]+type = "PipeCompose"+description = "Greet someone"+inputs = {{ name = "Text" }}+output = "Text"+template = "Hello $name"+"""+++class TestLibraryTreeHolds:+ def test_a_tree_of_several_bundles_is_held_once_and_released_with_its_library(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """Holding a tree indexes every file it lists, so a load holds each tree once, not once per bundle it places there."""+ method_dir = tmp_path / "method"+ method_dir.mkdir()+ (method_dir / "METHODS.toml").write_text(_MANIFEST, encoding="utf-8")+ for domain in ("tree_holds_first", "tree_holds_second", "tree_holds_third"):+ (method_dir / f"{domain}.mthds").write_text(_bundle(domain=domain), encoding="utf-8")+ hold_tree_spy = mocker.spy(LOCAL_METHOD_FILES, "hold_tree")+ library_manager = get_library_manager()+ library_id, _ = library_manager.open_library()+ try:+ with scoped_current_library(library_id=library_id):+ library_manager.load_libraries(library_id=library_id, library_dirs=[method_dir])+ hold_tree_spy.assert_called_once()+ tree = hold_tree_spy.call_args.kwargs["tree"]+ assert LOCAL_METHOD_FILES.holds(holder=library_id, tree_digest=tree.digest)+ finally:+ library_manager.teardown(library_id=library_id)+ assert not LOCAL_METHOD_FILES.holds(holder=library_id, tree_digest=tree.digest)diff --git a/tests/unit/pipelex/libraries/test_method_trees.py b/tests/unit/pipelex/libraries/test_method_trees.pyindex c3e3988af..aad74b62f 100644--- a/tests/unit/pipelex/libraries/test_method_trees.py+++ b/tests/unit/pipelex/libraries/test_method_trees.py@@ -13,7 +13,7 @@ from pipelex.libraries.method_trees import (list_library_dir_trees,list_package_method_tree,reporting_host_library_tree_faults,- submitted_python_files,+ submitted_tree_files,tree_bundle_of_lone_file,tree_python_sources,)@@ -219,7 +219,10 @@ class TestMethodTrees:_touch(directory=tmp_path, tree_path="rooted/python/helpers.py", content="X = 3\n")submitted = {- library_tree.library_dir.name: submitted_python_files(library_tree=library_tree)+ library_tree.library_dir.name: {+ path: held_file.source.read_bytes() if isinstance(held_file.source, Path) else held_file.source+ for path, held_file in submitted_tree_files(library_tree=library_tree).items()+ }for library_tree in list_library_dir_trees(library_dirs=[tmp_path / "submitted", tmp_path / "method", tmp_path / "rooted" / "python"])}diff --git a/tests/unit/pipelex/libraries/test_mthds_version_warning.py b/tests/unit/pipelex/libraries/test_mthds_version_warning.pyindex a40927359..3ef1deb72 100644--- a/tests/unit/pipelex/libraries/test_mthds_version_warning.py+++ b/tests/unit/pipelex/libraries/test_mthds_version_warning.py@@ -94,6 +94,7 @@ class TestMthdsVersionWarning:manager._load_single_dependency( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]library=library,+ library_id="dependency-test",package_address="github.com/org/dep-pkg",resolved_dep=resolved_dep,)diff --git a/tests/unit/pipelex/libraries/test_submitted_tree.py b/tests/unit/pipelex/libraries/test_submitted_tree.pynew file mode 100644index 000000000..0210de60c--- /dev/null+++ b/tests/unit/pipelex/libraries/test_submitted_tree.py@@ -0,0 +1,78 @@+import re++import pytest+from mthds.method_tree.digest import digest_of_contents++from pipelex.core.bundle_resources.exceptions import BundleResourcePathError+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES+from pipelex.core.method_trees.tree_bundle import TreeBundleRef+from pipelex.interpreter_hub import get_library_manager, scoped_current_library+from pipelex.mthds_parsing.parser import MthdsParser+from pipelex.mthds_parsing.pipelex_bundle_blueprint import PipelexBundleBlueprint++_COMPOSE_BUNDLE = """+domain = "submitted_tree_tests"++[pipe.greet]+type = "PipeCompose"+description = "Greet someone"+inputs = { name = "Text" }+output = "Text"+template = "Hello $name"+"""+++def _compose_blueprint() -> PipelexBundleBlueprint:+ return MthdsParser.make_pipelex_bundle_blueprint(mthds_content=_COMPOSE_BUNDLE)+++class TestSubmittedTree:+ """The files submitted with content strings make one tree, held for the library's runs, that the content strings sit at the root of."""++ def test_the_content_strings_name_the_tree_of_their_submitted_files(self) -> None:+ library_manager = get_library_manager()+ library_id, _ = library_manager.open_library()+ try:+ with scoped_current_library(library_id=library_id):+ library_manager.add_submitted_files(library_id=library_id, submitted_files={"./templates/report.docx": b"docx"})+ library_manager.load_from_blueprints(library_id=library_id, blueprints=[_compose_blueprint()])+ crate = library_manager.get_crate(library_id=library_id)+ assert crate is not None+ tree_bundle_ref = crate.tree_bundles["submitted_tree_tests.greet"]+ assert tree_bundle_ref == TreeBundleRef(tree_digest=digest_of_contents({"templates/report.docx": b"docx"}), tree_path=None)+ assert LOCAL_METHOD_FILES.read_held_file(tree_digest=tree_bundle_ref.tree_digest, tree_path="templates/report.docx") == b"docx"+ finally:+ library_manager.teardown(library_id=library_id)+ assert LOCAL_METHOD_FILES.held_tree(tree_digest=tree_bundle_ref.tree_digest) is None++ @pytest.mark.parametrize(+ "submitted_files",+ [+ pytest.param({"templates/report.docx": b"a", "Templates/report.docx": b"b"}, id="case_folded"),+ pytest.param({"templates": b"a", "templates/report.docx": b"b"}, id="file_and_directory"),+ ],+ )+ def test_files_that_cannot_make_one_tree_are_refused(self, submitted_files: dict[str, bytes]) -> None:+ library_manager = get_library_manager()+ library_id, _ = library_manager.open_library()+ try:+ with pytest.raises(BundleResourcePathError, match="cannot make one tree"):+ library_manager.add_submitted_files(library_id=library_id, submitted_files=submitted_files)+ finally:+ library_manager.teardown(library_id=library_id)++ def test_two_files_submitted_under_one_path_with_different_bytes_are_the_caller_s_conflict(self) -> None:+ """The refusal is the caller's to read, so it is an input error naming the path, and it joins nothing."""+ library_manager = get_library_manager()+ library_id, _ = library_manager.open_library()+ try:+ library_manager.add_submitted_files(library_id=library_id, submitted_files={"templates/report.docx": b"first"})+ with pytest.raises(BundleResourcePathError, match=re.escape("submitted under the same path 'templates/report.docx'")):+ library_manager.add_submitted_files(library_id=library_id, submitted_files={"notes.txt": b"n", "templates/report.docx": b"second"})+ with scoped_current_library(library_id=library_id):+ library_manager.load_from_blueprints(library_id=library_id, blueprints=[_compose_blueprint()])+ crate = library_manager.get_crate(library_id=library_id)+ assert crate is not None+ assert crate.tree_bundles["submitted_tree_tests.greet"].tree_digest == digest_of_contents({"templates/report.docx": b"first"})+ finally:+ library_manager.teardown(library_id=library_id)diff --git a/tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_pipe_doc_gen_blueprint.py b/tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_pipe_doc_gen_blueprint.pyindex ce85583e2..5ae51feb4 100644--- a/tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_pipe_doc_gen_blueprint.py+++ b/tests/unit/pipelex/pipe_operators/pipe_doc_gen/test_pipe_doc_gen_blueprint.py@@ -4,7 +4,7 @@ import pytestfrom pydantic import ValidationErrorfrom pipelex.cogt.doc_gen.doc_gen_format import DocGenFormat-from pipelex.core.bundle_resources.bundle_resource import BundleResourceReadStage, canonical_resource_path_or_none+from pipelex.core.bundle_resources.bundle_resource import canonical_resource_path_or_nonefrom pipelex.core.method_trees.file_references import BundleFileOrigin, BundleValidationContextfrom pipelex.pipe_operators.doc_gen.pipe_doc_gen_blueprint import PipeDocGenBlueprint@@ -16,6 +16,10 @@ def _blueprint(*, file_origin: BundleFileOrigin | None = None, **overrides: Any)return PipeDocGenBlueprint.model_validate(kwargs, context=context)+_NO_FILE: set[str] = set()+_NO_OVERRIDE: dict[str, Any] = {}++class TestPipeDocGenBlueprint:def test_a_pdf_without_a_template_is_the_auto_layout(self) -> None:blueprint = _blueprint(filename="invoice-{{ invoice.number }}")@@ -115,15 +119,15 @@ class TestPipeDocGenBlueprint:assert blueprint.template == "<h1>$invoice.number</h1>"@pytest.mark.parametrize(- ("overrides", "expected_reads"),+ ("overrides", "expected_files"),[- ({"template_file": "templates/invoice.html"}, {"templates/invoice.html": BundleResourceReadStage.LOAD}),- ({"format": "docx", "template_file": "invoice.docx"}, {"invoice.docx": BundleResourceReadStage.RUN}),- ({"format": "xlsx", "template_file": "./invoice.xlsx"}, {"./invoice.xlsx": BundleResourceReadStage.RUN}),- ({"template": "<p>{{ invoice.number }}</p>"}, {}),- ({}, {}),+ ({"template_file": "templates/invoice.html"}, {"templates/invoice.html"}),+ ({"format": "docx", "template_file": "invoice.docx"}, {"invoice.docx"}),+ ({"format": "xlsx", "template_file": "./invoice.xlsx"}, {"./invoice.xlsx"}),+ ({"template": "<p>{{ invoice.number }}</p>"}, _NO_FILE),+ (_NO_OVERRIDE, _NO_FILE),],)- def test_the_file_it_reads_from_its_bundle_and_when(self, overrides: dict[str, Any], expected_reads: dict[str, BundleResourceReadStage]) -> None:- """An HTML template file is read while the method loads, to check it against the inputs; an office one only when the step prints."""- assert _blueprint(**overrides).bundle_resource_reads == expected_reads+ def test_the_file_of_its_tree_it_names(self, overrides: dict[str, Any], expected_files: set[str]) -> None:+ """A step names its template file, as written; the print stage reads it, an HTML one checked at load too."""+ assert _blueprint(**overrides).named_file_references == expected_filesdiff --git a/tests/unit/pipelex/pipe_operators/pipe_func/test_direct_executor_workdir.py b/tests/unit/pipelex/pipe_operators/pipe_func/test_direct_executor_workdir.pyindex e200c398c..fd66605f8 100644--- a/tests/unit/pipelex/pipe_operators/pipe_func/test_direct_executor_workdir.py+++ b/tests/unit/pipelex/pipe_operators/pipe_func/test_direct_executor_workdir.py@@ -1,4 +1,6 @@import sys+from collections.abc import Generator+from contextlib import contextmanagerfrom pathlib import Pathimport pytest@@ -8,10 +10,12 @@ from pytest_mock import MockerFixturefrom pipelex.base_exceptions import PipelexErrorfrom pipelex.config import get_configfrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactory+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES, HeldFile+from pipelex.core.method_trees.tree_files import write_call_filesfrom pipelex.interpreter_hub import get_library_manager, scoped_current_library, set_current_libraryfrom pipelex.libraries.library_crate import LibraryCrate-from pipelex.pipe_operators.func import direct_pipe_func_executor-from pipelex.pipe_operators.func.direct_pipe_func_executor import DirectPipeFuncExecutor+from pipelex.libraries.pipe_func_call_files import read_pipe_func_call_files+from pipelex.pipe_operators.func.direct_pipe_func_executor import TRANSPORTED_LIBRARY_ID, DirectPipeFuncExecutorfrom pipelex.pipe_operators.func.pipe_func_execution_dtos import PipeFuncExecutionRequest, PipeFuncExecutionResponsefrom pipelex.pipe_operators.func.pipe_func_execution_transport import build_pipe_func_execution_requestfrom pipelex.pipe_run.pipe_run_params import PipeRunParams@@ -61,10 +65,25 @@ def _dry_run_params() -> PipeRunParams:return PipeRunParams(run_mode=PipeRunMode.DRY, pipe_stack_limit=10, batch_max_concurrency=None)-def _missing_pipe_request(*, files: dict[str, str]) -> PipeFuncExecutionRequest:+_HOLDER = "test_direct_executor_workdir"+++@contextmanager+def _held_call_files(*, files: dict[str, str]) -> Generator[str, None, None]:+ """Hold a tree of these files in the local method file store, as the library that built a call does, and name it by digest."""+ tree = LOCAL_METHOD_FILES.hold_files(+ holder=_HOLDER, files={tree_path: HeldFile.of_bytes(data=source.encode("utf-8")) for tree_path, source in files.items()}+ )+ try:+ yield tree.digest+ finally:+ LOCAL_METHOD_FILES.release(holder=_HOLDER)+++def _missing_pipe_request(*, tree_digest: str) -> PipeFuncExecutionRequest:return PipeFuncExecutionRequest(crate=LibraryCrate(),- files=dict(files),+ tree_digest=tree_digest,working_memory_raw={},pipe_code="missing_pipe",function_name="missing_funcs.missing_func",@@ -74,7 +93,7 @@ def _missing_pipe_request(*, files: dict[str, str]) -> PipeFuncExecutionRequest:async def _run_transported(*, request: PipeFuncExecutionRequest, tree_root: Path | None = None) -> PipeFuncExecutionResponse:- library_id = direct_pipe_func_executor._TRANSPORTED_LIBRARY_ID # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ library_id = TRANSPORTED_LIBRARY_IDwith scoped_current_library(library_id=library_id):try:if tree_root is None:@@ -84,8 +103,13 @@ async def _run_transported(*, request: PipeFuncExecutionRequest, tree_root: Pathget_library_manager().teardown(library_id=library_id)-def _greet_request(*, tmp_path: Path) -> PipeFuncExecutionRequest:- """The request a sandbox-hosted deployment builds for the greet step of a method folder holding its Python."""+@contextmanager+def _greet_request(*, tmp_path: Path) -> Generator[PipeFuncExecutionRequest, None, None]:+ """The request a sandbox-hosted deployment builds for the greet step of a method folder holding its Python.++ The library that built it stays open while the call runs, as a run's library does: it holds the method's tree, whose+ files the call reads through the method file store.+ """method_dir = tmp_path / "greet_method"(method_dir / "greet_demo_funcs").mkdir(parents=True)(method_dir / "greet.mthds").write_text(_GREET_MTHDS, encoding="utf-8")@@ -101,7 +125,7 @@ def _greet_request(*, tmp_path: Path) -> PipeFuncExecutionRequest:set_current_library(library_id=build_library_id)try:library_manager.load_libraries(library_id=build_library_id, library_dirs=[method_dir])- return build_pipe_func_execution_request(+ yield build_pipe_func_execution_request(job_metadata=_job_metadata(),# Qualified, as PipeFunc sends it: the transported library is keyed by pipe_ref and its lookup is strict.pipe_code="greet_demo.greet",@@ -123,8 +147,8 @@ class TestDirectExecutorWorkdir:workdir.mkdir()mocker.patch("tempfile.mkdtemp", return_value=str(workdir))- with pytest.raises((PipelexError, ValidationError)):- await _run_transported(request=_missing_pipe_request(files={"missing_funcs.py": "x = 1\n"}))+ with _held_call_files(files={"missing_funcs.py": "x = 1\n"}) as tree_digest, pytest.raises((PipelexError, ValidationError)):+ await _run_transported(request=_missing_pipe_request(tree_digest=tree_digest))assert not workdir.exists()@@ -135,8 +159,8 @@ class TestDirectExecutorWorkdir:workdir.mkdir()mocker.patch("tempfile.mkdtemp", return_value=str(workdir))- with pytest.raises((PipelexError, ValidationError)):- await _run_transported(request=_missing_pipe_request(files={"missing_funcs/helpers.py": "x = 1\n"}))+ with _held_call_files(files={"missing_funcs/helpers.py": "x = 1\n"}) as tree_digest, pytest.raises((PipelexError, ValidationError)):+ await _run_transported(request=_missing_pipe_request(tree_digest=tree_digest))stale_entries = [entry for entry in sys.path if Path(entry).is_relative_to(workdir)]assert stale_entries == []@@ -150,8 +174,8 @@ class TestDirectExecutorWorkdir:linked_workdir.symlink_to(real_workdir, target_is_directory=True)mocker.patch("tempfile.mkdtemp", return_value=str(linked_workdir))- with pytest.raises((PipelexError, ValidationError)):- await _run_transported(request=_missing_pipe_request(files={"missing_funcs/probe.py": "x = 1\n"}))+ with _held_call_files(files={"missing_funcs/probe.py": "x = 1\n"}) as tree_digest, pytest.raises((PipelexError, ValidationError)):+ await _run_transported(request=_missing_pipe_request(tree_digest=tree_digest))stale_entries = [entry for entry in sys.path if Path(entry).is_relative_to(real_workdir) or Path(entry).is_relative_to(linked_workdir)]assert stale_entries == []@@ -160,15 +184,17 @@ class TestDirectExecutorWorkdir:async def test_transported_run_imports_by_import_path_and_generates_concept_structures(self, tmp_path: Path):"""A PipeFunc that imports a sibling module and its output concept's structure runs in the box.- The call carries every file of the step's tree but the bundles: the function's module and the module it imports- travel at their tree paths, and the box regenerates `structures.py` from the crate's concepts, so the method- ships no copy of it that could drift from the .mthds.+ The call names the step's tree by digest and its files are read through the method file store, every one but+ the bundles: the function's module and the module it imports are written at their tree paths, and the box+ regenerates `structures.py` from the crate's concepts, so the method ships no copy of it that could drift from+ the .mthds."""- request = _greet_request(tmp_path=tmp_path)- assert sorted(request.files) == ["greet_demo_funcs/greeting.py", "greet_demo_funcs/wording.py"]- assert request.crate.pipe_func_files == {}+ with _greet_request(tmp_path=tmp_path) as request:+ assert request.tree_digest is not None+ call_files = await read_pipe_func_call_files(tree_digest=request.tree_digest, read_scope=None)+ assert sorted(call_files) == ["greet_demo_funcs/greeting.py", "greet_demo_funcs/wording.py"]- response = await _run_transported(request=request)+ response = await _run_transported(request=request)assert response.function_module == "greet_demo_funcs.greeting"assert response.function_qualname == "greet_it"@@ -177,15 +203,13 @@ class TestDirectExecutorWorkdir:@pytest.mark.asyncioasync def test_transported_run_at_a_root_the_client_filled(self, tmp_path: Path):"""A sandbox client may unpack the call's files itself and hand the directory over; nothing is written beside them."""- request = _greet_request(tmp_path=tmp_path)tree_root = (tmp_path / "unpacked").resolve()- for tree_path, entry in request.files.items():- target = tree_root.joinpath(*tree_path.split("/"))- target.parent.mkdir(parents=True, exist_ok=True)- assert isinstance(entry, str)- target.write_text(entry, encoding="utf-8")+ tree_root.mkdir()+ with _greet_request(tmp_path=tmp_path) as request:+ assert request.tree_digest is not None+ write_call_files(files=await read_pipe_func_call_files(tree_digest=request.tree_digest, read_scope=None), destination=tree_root)- response = await _run_transported(request=request.model_copy(update={"files": {}}), tree_root=tree_root)+ response = await _run_transported(request=request, tree_root=tree_root)assert response.function_qualname == "greet_it"assert (tree_root / "structures.py").is_file()diff --git a/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_execution_transport.py b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_execution_transport.pyindex f644210c5..aa349d0fc 100644--- a/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_execution_transport.py+++ b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_execution_transport.py@@ -7,15 +7,17 @@ must forbid extras (it is a wire contract)."""import pytest-from mthds.method_tree.file_entry import Base64FileEntryfrom pydantic import ValidationError+from pytest_mock import MockerFixture-from pipelex.core.method_trees.tree_files import tree_file_bytes+from pipelex.core.memory.working_memory import WorkingMemory+from pipelex.core.method_trees.tree_bundle import TreeBundleReffrom pipelex.libraries.library_crate import LibraryCratefrom pipelex.pipe_operators.func.pipe_func_execution_transport import (DEFAULT_PIPE_FUNC_TIMEOUT_SECONDS,PipeFuncExecutionRequest,PipeFuncExecutionResponse,+ build_pipe_func_execution_request,)from pipelex.pipe_run.pipe_run_params import PipeRunParamsfrom pipelex.system.job_metadata import JobMetadata, RunMetadata@@ -40,21 +42,42 @@ class TestPipeFuncExecutionTransport:assert "working_memory_raw" in PipeFuncExecutionRequest.model_fieldsassert PipeFuncExecutionRequest.model_fields["timeout_seconds"].default == DEFAULT_PIPE_FUNC_TIMEOUT_SECONDS- def test_request_carries_the_call_files_as_file_entries(self) -> None:- """The call's files travel at their tree paths, text as text and other bytes in Base64, and survive a JSON round-trip."""- binary = bytes([0, 159, 146, 150])+ def test_request_names_the_tree_of_the_called_step_by_digest_and_carries_no_file(self) -> None:+ """The call's files are read through the method file store by whoever runs it, so the request names the tree only."""+ tree_digest = "sha256:" + "b" * 64request = PipeFuncExecutionRequest(- crate=LibraryCrate(),- files={"funcs/totals.py": "TOTAL = 3\n", "assets/logo.bin": Base64FileEntry.make_from_bytes(binary)},+ crate=LibraryCrate(tree_bundles={"my_domain.my_pipe": TreeBundleRef(tree_digest=tree_digest, tree_path="main.mthds")}),+ tree_digest=tree_digest,working_memory_raw={},pipe_code="my_domain.my_pipe",function_name="funcs.totals.compute_totals",job_metadata=JobMetadata(run_metadata=RunMetadata(storage_scope="test/scope", read_scope=None, user_id="user", pipeline_run_id="run")),pipe_run_params=PipeRunParams(run_mode=PipeRunMode.DRY, pipe_stack_limit=10, batch_max_concurrency=None),)+again = PipeFuncExecutionRequest.model_validate_json(request.model_dump_json())- assert tree_file_bytes(entry=again.files["funcs/totals.py"]) == b"TOTAL = 3\n"- assert tree_file_bytes(entry=again.files["assets/logo.bin"]) == binary++ assert again.tree_digest == tree_digest+ assert "files" not in PipeFuncExecutionRequest.model_fields++ @pytest.mark.parametrize("in_a_tree", [True, False], ids=["step-in-a-tree", "step-in-no-tree"])+ def test_the_built_request_names_the_tree_the_crate_names_for_the_step(self, mocker: MockerFixture, in_a_tree: bool) -> None:+ tree_digest = "sha256:" + "c" * 64+ tree_bundles = {"my_domain.my_pipe": TreeBundleRef(tree_digest=tree_digest, tree_path=None)} if in_a_tree else {}+ mocker.patch("pipelex.pipe_operators.func.pipe_func_execution_transport.get_current_library", return_value="library")+ library_manager = mocker.MagicMock()+ library_manager.get_crate.return_value = LibraryCrate(tree_bundles=tree_bundles)+ mocker.patch("pipelex.pipe_operators.func.pipe_func_execution_transport.get_library_manager", return_value=library_manager)++ request = build_pipe_func_execution_request(+ job_metadata=JobMetadata(run_metadata=RunMetadata(storage_scope="test/scope", read_scope=None, user_id="user", pipeline_run_id="run")),+ pipe_code="my_domain.my_pipe",+ function_name="funcs.totals.compute_totals",+ working_memory=WorkingMemory(),+ pipe_run_params=PipeRunParams(run_mode=PipeRunMode.DRY, pipe_stack_limit=10, batch_max_concurrency=None),+ )++ assert request.tree_digest == (tree_digest if in_a_tree else None)def test_request_rejects_non_finite_timeout(self) -> None:"""A non-finite timeout would disable the runaway-code guard, so the wire contract rejects it."""diff --git a/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_hosted_mode.py b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_hosted_mode.pyindex 4e0f8728b..95165ad80 100644--- a/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_hosted_mode.py+++ b/tests/unit/pipelex/pipe_operators/pipe_func/test_pipe_func_hosted_mode.py@@ -1,3 +1,4 @@+from collections.abc import Iteratorfrom typing import Callableimport pytest@@ -5,11 +6,10 @@ from pydantic import ValidationErrorfrom pytest_mock import MockerFixturefrom pipelex.core.memory.working_memory_factory import WorkingMemoryFactory-from pipelex.core.method_trees.tree_files import TreeFileEntry+from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES, HeldFile+from pipelex.core.method_trees.tree_bundle import TreeBundle, TreeBundleReffrom pipelex.core.pipes.exceptions import PipeValidationErrorfrom pipelex.core.stuffs.list_content import ListContent-from pipelex.interpreter_hub import get_library_manager-from pipelex.libraries.library_crate import SUBMITTED_PYTHON_ROOT_KEYfrom pipelex.pipe_machinery.pipe_factory import PipeFactoryfrom pipelex.pipe_operators.func import pipe_func as pipe_func_modulefrom pipelex.pipe_operators.func.pipe_func import PipeFunc@@ -43,17 +43,24 @@ def _make_pipe_func(*, output: str = "native.Text") -> PipeFunc:return PipeFactory[PipeFunc].make_from_blueprint(domain_code="hosted_test", pipe_code="hosted_pipe", blueprint=blueprint)-def _capture_submitted_files(*, library_id: str, files: dict[str, TreeFileEntry] | None, mocker: MockerFixture) -> None:- library_manager = get_library_manager()- original = library_manager.get_pipe_func_files+_HOLDER = "test_pipe_func_hosted_mode"- def get_pipe_func_files(*, library_id: str, root_key: str) -> dict[str, TreeFileEntry] | None:- if root_key == SUBMITTED_PYTHON_ROOT_KEY:- return files- return original(library_id=library_id, root_key=root_key)- mocker.patch.object(library_manager, "get_pipe_func_files", side_effect=get_pipe_func_files)- assert library_id+def submit_files() -> Iterator[Callable[[dict[str, str] | None], PipeFunc]]:+ """Build the step as the library manager builds one parsed from a content string, with these files submitted beside it."""++ def _submit(files: dict[str, str] | None) -> PipeFunc:+ pipe_func = _make_pipe_func()+ if files is not None:+ tree = LOCAL_METHOD_FILES.hold_files(+ holder=_HOLDER, files={tree_path: HeldFile.of_bytes(data=source.encode("utf-8")) for tree_path, source in files.items()}+ )+ pipe_func.place_in_tree(tree_bundle=TreeBundle(tree=tree, tree_path=None))+ return pipe_func++ yield _submit+ LOCAL_METHOD_FILES.release(holder=_HOLDER)class TestPipeFuncHostedMode:@@ -64,21 +71,35 @@ class TestPipeFuncHostedMode:with pytest.raises(ValidationError, match="pipelex fix function-names"):PipeFuncBlueprint(description="A flat name", inputs={}, output="native.Text", function_name="compute_totals")- def test_hosted_validation_reads_the_submitted_files(self, load_empty_library: Callable[[], str], mocker: MockerFixture):+ def test_hosted_validation_reads_the_submitted_files(+ self, load_empty_library: Callable[[], str], submit_files: Callable[[dict[str, str] | None], PipeFunc], mocker: MockerFixture+ ):"""In sandbox-hosted mode a step parsed from a string is validated from the files submitted with it, never imported."""- library_id = load_empty_library()+ load_empty_library()mocker.patch("pipelex.pipe_operators.func.pipe_func.is_pipe_func_sandbox_hosted", return_value=True)- _capture_submitted_files(library_id=library_id, files={"sandbox_funcs/totals.py": _SANDBOX_MODULE}, mocker=mocker)- _make_pipe_func().validate_output_with_library()+ submit_files({"sandbox_funcs/totals.py": _SANDBOX_MODULE}).validate_output_with_library()- def test_a_step_proves_its_function_once_however_often_it_is_validated(self, load_empty_library: Callable[[], str], mocker: MockerFixture):- """A dependency package's step is validated as it is built and again with its consumer's library: it reads its module once."""- library_id = load_empty_library()+ def test_a_step_built_from_a_crate_is_not_checked_again(self, load_empty_library: Callable[[], str], mocker: MockerFixture):+ """Its tree is named by digest only: the process that assembled the crate proved the function, and this one reads nothing."""+ load_empty_library()mocker.patch("pipelex.pipe_operators.func.pipe_func.is_pipe_func_sandbox_hosted", return_value=True)- _capture_submitted_files(library_id=library_id, files={"sandbox_funcs/totals.py": _SANDBOX_MODULE}, mocker=mocker)locate_spy = mocker.spy(pipe_func_module, "locate_in_files")pipe_func = _make_pipe_func()+ pipe_func.place_in_tree(tree_bundle=TreeBundleRef(tree_digest="sha256:" + "d" * 64, tree_path="main.mthds"))++ pipe_func.validate_output_with_library()++ assert locate_spy.call_count == 0++ def test_a_step_proves_its_function_once_however_often_it_is_validated(+ self, load_empty_library: Callable[[], str], submit_files: Callable[[dict[str, str] | None], PipeFunc], mocker: MockerFixture+ ):+ """A dependency package's step is validated as it is built and again with its consumer's library: it reads its module once."""+ load_empty_library()+ mocker.patch("pipelex.pipe_operators.func.pipe_func.is_pipe_func_sandbox_hosted", return_value=True)+ locate_spy = mocker.spy(pipe_func_module, "locate_in_files")+ pipe_func = submit_files({"sandbox_funcs/totals.py": _SANDBOX_MODULE})pipe_func.validate_once_built()pipe_func.validate_with_libraries()@@ -96,18 +117,19 @@ class TestPipeFuncHostedMode:)def test_hosted_validation_refuses_what_the_submitted_files_cannot_prove(self,- files: dict[str, TreeFileEntry] | None,+ files: dict[str, str] | None,expected_message: str,load_empty_library: Callable[[], str],+ submit_files: Callable[[dict[str, str] | None], PipeFunc],mocker: MockerFixture,):"""A missing module, an unmarked function or a shadowing module is refused at validation, naming the step."""- library_id = load_empty_library()+ load_empty_library()mocker.patch("pipelex.pipe_operators.func.pipe_func.is_pipe_func_sandbox_hosted", return_value=True)- _capture_submitted_files(library_id=library_id, files=files, mocker=mocker)+ pipe_func = submit_files(files)with pytest.raises(PipeValidationError) as raised:- _make_pipe_func().validate_output_with_library()+ pipe_func.validate_output_with_library()assert raised.value.error_type == PipeValidationErrorType.PIPE_FUNC_FUNCTION_REFUSEDassert raised.value.pipe_code == "hosted_pipe"diff --git a/tests/unit/pipelex/pipeline/test_direct_bundle_validator.py b/tests/unit/pipelex/pipeline/test_direct_bundle_validator.pyindex 9d4904a01..b9a9398b8 100644--- a/tests/unit/pipelex/pipeline/test_direct_bundle_validator.py+++ b/tests/unit/pipelex/pipeline/test_direct_bundle_validator.py@@ -16,7 +16,6 @@ from typing import TYPE_CHECKINGimport pytestfrom pipelex.base_exceptions import ErrorReport-from pipelex.core.bundle_resources.bundle_resource import make_bundle_resourcesfrom pipelex.pipeline.direct_bundle_validator import DirectBundleValidatorfrom pipelex.pipeline.exceptions import ValidateBundleErrorfrom pipelex.system.caller_identity import CallerIdentity@@ -30,7 +29,7 @@ class TestDirectBundleValidator:async def test_valid_sweep_is_returned_as_the_valid_arm(self, mocker: MockerFixture) -> None:"""A successful in-process sweep's report is returned verbatim, with arguments forwarded."""report = mocker.MagicMock(name="validation_report")- bundle_resources = make_bundle_resources(files={"invoice.docx": b"docx bytes"})+ submitted_files = {"invoice.docx": b"docx bytes"}in_process_mock = mocker.patch("pipelex.pipeline.direct_bundle_validator.validate_bundles_in_process",new=mocker.AsyncMock(return_value=report),@@ -43,7 +42,7 @@ class TestDirectBundleValidator:library_dirs=[Path("lib_dir")],caller_identity=CallerIdentity(user_id="user-42", extras={"organization": "org_acme"}),graph_pipe_code="extract_document_markdown",- bundle_resources=bundle_resources,+ submitted_files=submitted_files,)assert verdict is report@@ -55,7 +54,7 @@ class TestDirectBundleValidator:graph_pipe_code="extract_document_markdown",log_context="API validate",caller_identity=CallerIdentity(user_id="user-42", extras={"organization": "org_acme"}),- bundle_resources=bundle_resources,+ submitted_files=submitted_files,)async def test_validate_bundle_error_becomes_the_invalid_arm(self, mocker: MockerFixture) -> None:@@ -73,7 +72,7 @@ class TestDirectBundleValidator:library_dirs=None,caller_identity=None,graph_pipe_code=None,- bundle_resources=None,+ submitted_files=None,)assert isinstance(verdict, ErrorReport)@@ -95,5 +94,5 @@ class TestDirectBundleValidator:library_dirs=None,caller_identity=None,graph_pipe_code=None,- bundle_resources=None,+ submitted_files=None,)diff --git a/tests/unit/pipelex/pipeline/test_runner_validate_plumbing.py b/tests/unit/pipelex/pipeline/test_runner_validate_plumbing.pyindex 40584e735..087f1ecc9 100644--- a/tests/unit/pipelex/pipeline/test_runner_validate_plumbing.py+++ b/tests/unit/pipelex/pipeline/test_runner_validate_plumbing.py@@ -24,7 +24,6 @@ from typing import TYPE_CHECKING, Any, NamedTupleimport pytest-from pipelex.core.bundle_resources.bundle_resource import make_bundle_resourcesfrom pipelex.core.pipes.pipe_io_artifacts import PipeIOArtifactsfrom pipelex.pipeline.runner import PipelexMTHDSProtocolfrom pipelex.system.caller_identity import CallerIdentity, get_current_caller_identity@@ -85,8 +84,8 @@ class TestRunnerValidatePlumbing:The protocol validation returns a verdict, so it asks the sweep to collect the dry runs' warnings for it."""env = self._patch_env(mocker, library_ids=[None, "val-lib"])- bundle_resources = make_bundle_resources(files={"templates/invoice.docx": b"template"})- runner = PipelexMTHDSProtocol(library_dirs=["dir_alpha", "nested/dir_beta"], library_dirs_are_callers=True, bundle_resources=bundle_resources)+ submitted_files = {"templates/invoice.docx": b"template"}+ runner = PipelexMTHDSProtocol(library_dirs=["dir_alpha", "nested/dir_beta"], library_dirs_are_callers=True, submitted_files=submitted_files)await runner.validate(mthds_contents=["bundle-content"], allow_signatures=True)@@ -97,7 +96,7 @@ class TestRunnerValidatePlumbing:allow_signatures=True,library_dirs_are_callers=True,collect_dry_run_warnings=True,- bundle_resources=bundle_resources,+ submitted_files=submitted_files,)async def test_no_library_dirs_passes_none_and_strict_default(self, mocker: MockerFixture) -> None:@@ -114,7 +113,7 @@ class TestRunnerValidatePlumbing:allow_signatures=False,library_dirs_are_callers=False,collect_dry_run_warnings=True,- bundle_resources=None,+ submitted_files=None,)async def test_validation_runs_with_the_protocols_caller_in_scope(self, mocker: MockerFixture) -> None:diff --git a/tests/unit/pipelex/plugins/test_bundle_validator_registry.py b/tests/unit/pipelex/plugins/test_bundle_validator_registry.pyindex e0132bf69..d984d927c 100644--- a/tests/unit/pipelex/plugins/test_bundle_validator_registry.py+++ b/tests/unit/pipelex/plugins/test_bundle_validator_registry.py@@ -19,11 +19,10 @@ from pipelex.plugins.registrar import PluginOrigin, PluginRegistrarfrom pipelex.runtime_bridge.orchestration_mode import DIRECT_ORCHESTRATION_MODEif TYPE_CHECKING:- from collections.abc import Sequence+ from collections.abc import Mapping, Sequencefrom pathlib import Pathfrom pipelex.base_exceptions import ErrorReport- from pipelex.core.bundle_resources.bundle_resource import BundleResourcesfrom pipelex.pipeline.validation_report import PipelexValidationReportfrom pipelex.system.caller_identity import CallerIdentityfrom pipelex.system.configuration.configs import PipelexConfig@@ -41,7 +40,7 @@ class _FakeBundleValidator:library_dirs: Sequence[Path] | None,caller_identity: CallerIdentity | None,graph_pipe_code: str | None,- bundle_resources: BundleResources | None,+ submitted_files: Mapping[str, bytes] | None,) -> PipelexValidationReport | ErrorReport:raise NotImplementedErrordiff --git a/tests/unit/pipelex/plugins/test_plugin_discovery.py b/tests/unit/pipelex/plugins/test_plugin_discovery.pyindex f50021d51..346b5872c 100644--- a/tests/unit/pipelex/plugins/test_plugin_discovery.py+++ b/tests/unit/pipelex/plugins/test_plugin_discovery.py@@ -165,6 +165,14 @@ class TestPluginDiscovery:_build_registrar_with(mocker=mocker, plugins=[future_plugin])assert "from_the_future" in str(exc_info.value)+ def test_a_plugin_written_before_crates_named_their_trees_is_refused(self, mocker: MockerFixture) -> None:+ """Plugin API v6 handed validators `bundle_resources` and executors the call's `files`; a v6 plugin would fail on its first call."""+ v6_plugin = _InferencePlugin(name="written_against_v6", sdk="v6_sdk", targets_api=6)+ with pytest.raises(PluginApiVersionMismatchError) as exc_info:+ _build_registrar_with(mocker=mocker, plugins=[v6_plugin])+ assert "written_against_v6" in str(exc_info.value)+ assert PLUGIN_API_VERSION == 7+def test_duplicate_inference_backend_names_both(self, mocker: MockerFixture) -> None:with pytest.raises(DuplicateInferenceBackendError) as exc_info:_build_registrar_with(mocker=mocker, plugins=[_InferencePlugin(name="alpha", sdk="dup"), _InferencePlugin(name="beta", sdk="dup")])diff --git a/tests/unit/pipelex/plugins/test_plugin_group_split.py b/tests/unit/pipelex/plugins/test_plugin_group_split.pyindex 2fe6cbece..6e089e8f0 100644--- a/tests/unit/pipelex/plugins/test_plugin_group_split.py+++ b/tests/unit/pipelex/plugins/test_plugin_group_split.py@@ -53,6 +53,7 @@ KERNEL_TIER_CLAIMS: dict[str, Callable[[PluginRegistrar], None]] = {"content_generator": lambda registrar: registrar.claim_content_generator(object),"task_manager": lambda registrar: registrar.claim_task_manager(object),"isolated_execution_probe": lambda registrar: registrar.claim_isolated_execution_probe(object),+ "method_file_store": lambda registrar: registrar.claim_method_file_store(object),}diff --git a/tests/unit/pipelex/test_runtime_boot_releases_boot_scoped_state.py b/tests/unit/pipelex/test_runtime_boot_releases_boot_scoped_state.pyindex 1f20a2103..5adc4814c 100644--- a/tests/unit/pipelex/test_runtime_boot_releases_boot_scoped_state.py+++ b/tests/unit/pipelex/test_runtime_boot_releases_boot_scoped_state.py@@ -14,8 +14,19 @@ that claims nothing inherits rather than overwrites, and only the release standsTemporal worker's replay/activity split and the next thing to ask `is_in_isolated_execution()`."""+import pytest++from pipelex.core.method_trees.method_file_store import LOCAL_METHOD_FILES, LocalMethodFileStore+from pipelex.pipe_operators.doc_gen.template_file_stage import DocGenTemplateFileStagefrom pipelex.pipelex import Pipelex-from pipelex.runtime_hub import get_boot_orchestrator, get_runtime_hub, is_dry_run_forced, is_in_isolated_execution+from pipelex.runtime_hub import (+ get_boot_orchestrator,+ get_method_file_store,+ get_runtime_hub,+ get_template_file_stage,+ is_dry_run_forced,+ is_in_isolated_execution,+)from pipelex.system.runtime import IntegrationMode, runtime_manager@@ -70,3 +81,25 @@ class TestTeardownReleasesBootScopedHubState:)finally:Pipelex.teardown_if_needed()+++class TestMethodFileSeams:+ def test_a_boot_installs_the_local_store_and_the_template_file_stage_and_teardown_releases_them(self) -> None:+ """Unclaimed, the method file store is the local one; the interpreter's boot installs the template file stage, and teardown removes it."""+ Pipelex.teardown_if_needed()+ try:+ Pipelex.make(+ integration_mode=IntegrationMode.CI if runtime_manager.is_ci_testing else IntegrationMode.PYTEST,+ needs_inference=False,+ )+ assert get_method_file_store() is LOCAL_METHOD_FILES+ assert isinstance(get_template_file_stage(), DocGenTemplateFileStage)+ get_runtime_hub().set_method_file_store(method_file_store=LocalMethodFileStore())++ Pipelex.teardown_if_needed()++ assert get_method_file_store() is LOCAL_METHOD_FILES, "teardown left a store a plugin installed for a boot that no longer exists"+ with pytest.raises(RuntimeError, match="template file stage is not installed"):+ get_template_file_stage()+ finally:+ Pipelex.teardown_if_needed()